Unverified Commit 19e2edcf authored by Josh Story's avatar Josh Story Committed by GitHub

Reland "[dynamicIO] warn for disallowed dynamic in dev" (#71567)

Reverts vercel/next.js#71566 which relands #71526 

merge after 15 is released
parent 51bfe3c1
......@@ -40,27 +40,13 @@ export function ClientPageRoot({
)
}
if (store.isStaticGeneration) {
// We are in a prerender context
const { createPrerenderSearchParamsFromClient } =
require('../../server/request/search-params') as typeof import('../../server/request/search-params')
clientSearchParams = createPrerenderSearchParamsFromClient(store)
const { createSearchParamsFromClient } =
require('../../server/request/search-params') as typeof import('../../server/request/search-params')
clientSearchParams = createSearchParamsFromClient(searchParams, store)
const { createPrerenderParamsFromClient } =
require('../../server/request/params') as typeof import('../../server/request/params')
clientParams = createPrerenderParamsFromClient(params, store)
} else {
const { createRenderSearchParamsFromClient } =
require('../../server/request/search-params') as typeof import('../../server/request/search-params')
clientSearchParams = createRenderSearchParamsFromClient(
searchParams,
store
)
const { createRenderParamsFromClient } =
require('../../server/request/params') as typeof import('../../server/request/params')
clientParams = createRenderParamsFromClient(params, store)
}
const { createParamsFromClient } =
require('../../server/request/params') as typeof import('../../server/request/params')
clientParams = createParamsFromClient(params, store)
return <Component params={clientParams} searchParams={clientSearchParams} />
} else {
......
......@@ -38,16 +38,10 @@ export function ClientSegmentRoot({
)
}
const { createPrerenderParamsFromClient } =
const { createParamsFromClient } =
require('../../server/request/params') as typeof import('../../server/request/params')
clientParams = createParamsFromClient(params, store)
if (store.isStaticGeneration) {
clientParams = createPrerenderParamsFromClient(params, store)
} else {
const { createRenderParamsFromClient } =
require('../../server/request/params') as typeof import('../../server/request/params')
clientParams = createRenderParamsFromClient(params, store)
}
return <Component {...slots} params={clientParams} />
} else {
const { createRenderParamsFromClient } =
......
......@@ -21,18 +21,19 @@
*/
import type { WorkStore } from '../app-render/work-async-storage.external'
import type { WorkUnitStore } from '../app-render/work-unit-async-storage.external'
import type {
WorkUnitStore,
RequestStore,
PrerenderStoreLegacy,
PrerenderStoreModern,
} from '../app-render/work-unit-async-storage.external'
// Once postpone is in stable we should switch to importing the postpone export directly
import React from 'react'
import { DynamicServerError } from '../../client/components/hooks-server-context'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
import {
workUnitAsyncStorage,
type PrerenderStoreLegacy,
type PrerenderStoreModern,
} from './work-unit-async-storage.external'
import { workUnitAsyncStorage } from './work-unit-async-storage.external'
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils'
import {
......@@ -71,6 +72,8 @@ export type DynamicTrackingState = {
syncDynamicExpression: undefined | string
syncDynamicErrorWithStack: null | Error
// Dev only
syncDynamicLogged?: boolean
}
// Stores dynamic reasons used during an SSR render.
......@@ -78,7 +81,7 @@ export type DynamicValidationState = {
hasSuspendedDynamic: boolean
hasDynamicMetadata: boolean
hasDynamicViewport: boolean
syncDynamicErrors: Array<Error>
hasSyncDynamicErrors: boolean
dynamicErrors: Array<Error>
}
......@@ -98,7 +101,7 @@ export function createDynamicValidationState(): DynamicValidationState {
hasSuspendedDynamic: false,
hasDynamicMetadata: false,
hasDynamicViewport: false,
syncDynamicErrors: [],
hasSyncDynamicErrors: false,
dynamicErrors: [],
}
}
......@@ -295,6 +298,14 @@ export function abortOnSynchronousPlatformIOAccess(
return abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore)
}
export function trackSynchronousPlatformIOAccessInDev(
requestStore: RequestStore
): void {
// We don't actually have a controller to abort but we do the semantic equivalent by
// advancing the request store out of prerender mode
requestStore.prerenderPhase = false
}
/**
* use this function when prerendering with dynamicIO. If we are doing a
* prospective prerender we don't actually abort because we want to discover
......@@ -316,6 +327,11 @@ export function abortAndThrowOnSynchronousRequestDataAccess(
if (dynamicTracking.syncDynamicErrorWithStack === null) {
dynamicTracking.syncDynamicExpression = expression
dynamicTracking.syncDynamicErrorWithStack = errorWithStack
if (prerenderStore.validating === true) {
// We always log Request Access in dev at the point of calling the function
// So we mark the dynamic validation as not requiring it to be printed
dynamicTracking.syncDynamicLogged = true
}
}
}
abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore)
......@@ -324,6 +340,10 @@ export function abortAndThrowOnSynchronousRequestDataAccess(
)
}
// For now these implementations are the same so we just reexport
export const trackSynchronousRequestDataAccessInDev =
trackSynchronousPlatformIOAccessInDev
/**
* This component will call `React.postpone` that throws the postponed error.
*/
......@@ -578,15 +598,11 @@ export function trackAllowedDynamicAccess(
} else if (hasSuspenseRegex.test(componentStack)) {
dynamicValidation.hasSuspendedDynamic = true
return
} else if (typeof serverDynamic.syncDynamicExpression === 'string') {
const message = `In Route "${route}" this parent component stack may help you locate where ${serverDynamic.syncDynamicExpression} was used.`
const error = createErrorWithComponentStack(message, componentStack)
dynamicValidation.syncDynamicErrors.push(error)
return
} else if (typeof clientDynamic.syncDynamicExpression === 'string') {
const message = `In Route "${route}" this parent component stack may help you locate where ${clientDynamic.syncDynamicExpression} was used.`
const error = createErrorWithComponentStack(message, componentStack)
dynamicValidation.syncDynamicErrors.push(error)
} else if (
serverDynamic.syncDynamicErrorWithStack ||
clientDynamic.syncDynamicErrorWithStack
) {
dynamicValidation.hasSyncDynamicErrors = true
return
} else {
// The thrownValue must have been the RENDER_COMPLETE abortReason because the only kinds of errors tracked here are
......@@ -608,33 +624,37 @@ function createErrorWithComponentStack(
}
export function throwIfDisallowedDynamic(
workStore: WorkStore,
route: string,
dynamicValidation: DynamicValidationState,
serverDynamic: DynamicTrackingState,
clientDynamic: DynamicTrackingState
): void {
const syncDynamicErrors = dynamicValidation.syncDynamicErrors
let syncError: null | Error, syncExpression: undefined | string
if (serverDynamic.syncDynamicExpression) {
let syncError: null | Error
let syncExpression: undefined | string
let syncLogged: boolean
if (serverDynamic.syncDynamicErrorWithStack) {
syncError = serverDynamic.syncDynamicErrorWithStack
syncExpression = serverDynamic.syncDynamicExpression!
} else if (clientDynamic.syncDynamicExpression) {
syncLogged = serverDynamic.syncDynamicLogged === true
} else if (clientDynamic.syncDynamicErrorWithStack) {
syncError = clientDynamic.syncDynamicErrorWithStack
syncExpression = clientDynamic.syncDynamicExpression!
syncLogged = clientDynamic.syncDynamicLogged === true
} else {
syncError = null
syncExpression = undefined
syncLogged = false
}
if (syncDynamicErrors.length && syncError) {
console.error(syncError)
for (let i = 0; i < syncDynamicErrors.length; i++) {
console.error(syncDynamicErrors[i])
if (dynamicValidation.hasSyncDynamicErrors && syncError) {
if (!syncLogged) {
// In dev we already log errors about sync dynamic access. But during builds we need to ensure
// the offending sync error is logged before we exit the build
console.error(syncError)
}
// The actual error should have been logged when the sync access ocurred
throw new StaticGenBailoutError(
`Route "${workStore.route}" could not be prerendered.`
`Route "${route}" could not be prerendered.`
)
}
......@@ -645,7 +665,7 @@ export function throwIfDisallowedDynamic(
}
throw new StaticGenBailoutError(
`Route "${workStore.route}" could not be prerendered.`
`Route "${route}" could not be prerendered.`
)
}
......@@ -654,21 +674,21 @@ export function throwIfDisallowedDynamic(
if (syncError) {
console.error(syncError)
throw new StaticGenBailoutError(
`Route "${workStore.route}" has a \`generateMetadata\` that could not finish rendering before ${syncExpression} was used. Follow the instructions in the error for this expression to resolve.`
`Route "${route}" has a \`generateMetadata\` that could not finish rendering before ${syncExpression} was used. Follow the instructions in the error for this expression to resolve.`
)
}
throw new StaticGenBailoutError(
`Route "${workStore.route}" has a \`generateMetadata\` that depends on Request data (\`cookies()\`, etc...) or external data (\`fetch(...)\`, etc...) but the rest of the route was static or only used cached data (\`"use cache"\`). If you expected this route to be prerenderable update your \`generateMetadata\` to not use Request data and only use cached external data. Otherwise, add \`await connection()\` somewhere within this route to indicate explicitly it should not be prerendered.`
`Route "${route}" has a \`generateMetadata\` that depends on Request data (\`cookies()\`, etc...) or external data (\`fetch(...)\`, etc...) but the rest of the route was static or only used cached data (\`"use cache"\`). If you expected this route to be prerenderable update your \`generateMetadata\` to not use Request data and only use cached external data. Otherwise, add \`await connection()\` somewhere within this route to indicate explicitly it should not be prerendered.`
)
} else if (dynamicValidation.hasDynamicViewport) {
if (syncError) {
console.error(syncError)
throw new StaticGenBailoutError(
`Route "${workStore.route}" has a \`generateViewport\` that could not finish rendering before ${syncExpression} was used. Follow the instructions in the error for this expression to resolve.`
`Route "${route}" has a \`generateViewport\` that could not finish rendering before ${syncExpression} was used. Follow the instructions in the error for this expression to resolve.`
)
}
throw new StaticGenBailoutError(
`Route "${workStore.route}" has a \`generateViewport\` that depends on Request data (\`cookies()\`, etc...) or external data (\`fetch(...)\`, etc...) but the rest of the route was static or only used cached data (\`"use cache"\`). If you expected this route to be prerenderable update your \`generateViewport\` to not use Request data and only use cached external data. Otherwise, add \`await connection()\` somewhere within this route to indicate explicitly it should not be prerendered.`
`Route "${route}" has a \`generateViewport\` that depends on Request data (\`cookies()\`, etc...) or external data (\`fetch(...)\`, etc...) but the rest of the route was static or only used cached data (\`"use cache"\`). If you expected this route to be prerenderable update your \`generateViewport\` to not use Request data and only use cached external data. Otherwise, add \`await connection()\` somewhere within this route to indicate explicitly it should not be prerendered.`
)
}
}
......
......@@ -51,7 +51,7 @@ export type RequestStore = {
// DEV-only
usedDynamic?: boolean
environment?: 'Prerender' | 'Server'
prerenderPhase?: boolean
} & PhasePartial
/**
......@@ -94,6 +94,12 @@ export type PrerenderStoreModern = {
expire: number // server expiration time
stale: number // client expiration time
tags: null | string[]
// DEV ONLY
// When used this flag informs certain APIs to skip logging because we're
// not part of the primary render path and are just prerendering to produce
// validation results
validating?: boolean
} & PhasePartial
export type PrerenderStorePPR = {
......
......@@ -48,7 +48,7 @@ export function createDedupedByCallsiteServerErrorLoggerDev<Args extends any[]>(
// asyncApiBeingAccessedSynchronously
// <userland callsite>
// TODO: This breaks if sourcemaps with ignore lists are enabled.
const key = callStackFrames[3]
const key = callStackFrames[4]
errorRef.current = message
flushCurrentErrorIfNew(key)
}
......
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
import { abortOnSynchronousPlatformIOAccess } from '../app-render/dynamic-rendering'
import {
abortOnSynchronousPlatformIOAccess,
trackSynchronousPlatformIOAccessInDev,
} from '../app-render/dynamic-rendering'
import { InvariantError } from '../../shared/lib/invariant-error'
type ApiType = 'time' | 'random' | 'crypto'
......@@ -36,6 +39,12 @@ export function io(expression: string, type: ApiType) {
workUnitStore
)
}
} else if (
workUnitStore.type === 'request' &&
workUnitStore.prerenderPhase === true
) {
const requestStore = workUnitStore
trackSynchronousPlatformIOAccessInDev(requestStore)
}
}
}
This diff is collapsed.
......@@ -7,6 +7,7 @@ import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.exte
import {
abortAndThrowOnSynchronousRequestDataAccess,
postponeWithTracking,
trackSynchronousRequestDataAccessInDev,
} from '../app-render/dynamic-rendering'
import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-loger'
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
......@@ -125,8 +126,8 @@ function createExoticDraftModeWithDevWarnings(
Object.defineProperty(promise, 'isEnabled', {
get() {
const expression = 'draftMode().isEnabled'
warnForSyncAccess(route, expression)
const expression = '`draftMode().isEnabled`'
syncIODev(route, expression)
return instance.isEnabled
},
set(newValue) {
......@@ -142,16 +143,16 @@ function createExoticDraftModeWithDevWarnings(
Object.defineProperty(promise, 'enable', {
value: function get() {
const expression = 'draftMode().enable()'
warnForSyncAccess(route, expression)
const expression = '`draftMode().enable()`'
syncIODev(route, expression)
return instance.enable.apply(instance, arguments as any)
},
})
Object.defineProperty(promise, 'disable', {
value: function get() {
const expression = 'draftMode().disable()'
warnForSyncAccess(route, expression)
const expression = '`draftMode().disable()`'
syncIODev(route, expression)
return instance.disable.apply(instance, arguments as any)
},
})
......@@ -190,21 +191,39 @@ class DraftMode {
}
}
function syncIODev(route: string | undefined, expression: string) {
const workUnitStore = workUnitAsyncStorage.getStore()
if (
workUnitStore &&
workUnitStore.type === 'request' &&
workUnitStore.prerenderPhase === true
) {
// When we're rendering dynamically in dev we need to advance out of the
// Prerender environment when we read Request data synchronously
const requestStore = workUnitStore
trackSynchronousRequestDataAccessInDev(requestStore)
}
// In all cases we warn normally
warnForSyncAccess(route, expression)
}
const noop = () => {}
const warnForSyncAccess = process.env.__NEXT_DISABLE_SYNC_DYNAMIC_API_WARNINGS
? noop
: createDedupedByCallsiteServerErrorLoggerDev(function getSyncAccessWarning(
route: undefined | string,
expression: string
) {
const prefix = route ? ` In route ${route} a ` : 'A '
return new Error(
`${prefix}\`draftMode()\` property was accessed directly with \`${expression}\`. ` +
`\`draftMode()\` should be awaited before using its value. ` +
`Learn more: https://nextjs.org/docs/messages/draft-mode-sync-access`
)
})
: createDedupedByCallsiteServerErrorLoggerDev(createDraftModeAccessError)
function createDraftModeAccessError(
route: string | undefined,
expression: string
) {
const prefix = route ? `Route "${route}" ` : 'This route '
return new Error(
`${prefix}used ${expression}. ` +
`\`draftMode()\` should be awaited before using its value. ` +
`Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`
)
}
function trackDynamicDraftMode(expression: string) {
const store = workAsyncStorage.getStore()
......
This diff is collapsed.
This diff is collapsed.
import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'
/**
* React annotates Promises with extra properties to make unwrapping them synchronous
* after they have resolved. We sometimes create promises that are compatible with this
* internal implementation detail when we want to construct a promise that is already resolved.
*
* @internal
*/
export function makeResolvedReactPromise<T>(value: T): Promise<T> {
const promise = Promise.resolve(value)
;(promise as any).status = 'fulfilled'
;(promise as any).value = value
return promise
}
// This regex will have fast negatives meaning valid identifiers may not pass
// this test. However this is only used during static generation to provide hints
// about why a page bailed out of some or all prerendering and we can use bracket notation
......@@ -72,6 +58,9 @@ export const wellKnownProperties = new Set([
// fallthrough
'status',
// React introspection
'displayName',
// Common tested properties
// fallthrough
'toJSON',
......
......@@ -28,20 +28,14 @@ describe('dynamic-data', () => {
// in dev we expect the entire page to be rendered at runtime
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
// we expect there to be no suspense boundary in fallback state
expect($('#boundary').html()).toBeNull()
} else if (process.env.__NEXT_EXPERIMENTAL_PPR) {
// in PPR we expect the shell to be rendered at build and the page to be rendered at runtime
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime')
// we expect there to be a suspense boundary in fallback state
expect($('#boundary').html()).not.toBeNull()
} else {
// in static generation we expect the entire page to be rendered at runtime
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
// we expect there to be no suspense boundary in fallback state
expect($('#boundary').html()).toBeNull()
}
expect($('#headers .fooheader').text()).toBe('foo header value')
......@@ -64,21 +58,15 @@ describe('dynamic-data', () => {
// in dev we expect the entire page to be rendered at runtime
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
// we expect there to be no suspense boundary in fallback state
expect($('#boundary').html()).toBeNull()
} else if (process.env.__NEXT_EXPERIMENTAL_PPR) {
// @TODO this should actually be build but there is a bug in how we do segment level dynamic in PPR at the moment
// see note in create-component-tree
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
// we expect there to be a suspense boundary in fallback state
expect($('#boundary').html()).toBeNull()
} else {
// in static generation we expect the entire page to be rendered at runtime
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
// we expect there to be no suspense boundary in fallback state
expect($('#boundary').html()).toBeNull()
}
expect($('#headers .fooheader').text()).toBe('foo header value')
......
......@@ -39,7 +39,6 @@ function createExpectError(cliOutput: string) {
}
function runTests(options: { withMinification: boolean }) {
const isTurbopack = !!process.env.TURBOPACK
const { withMinification } = options
describe(`Dynamic IO Errors - ${withMinification ? 'With Minification' : 'Without Minification'}`, () => {
describe('Sync Dynamic - With Fallback - Math.random()', () => {
......@@ -126,11 +125,6 @@ function runTests(options: { withMinification: boolean }) {
expectError(
'Error: Route "/" used `Math.random()` outside of `"use cache"` and without explicitly calling `await connection()` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-random'
)
expectError(
'Error: In Route "/" this parent component stack may help you locate where `Math.random()` was used.',
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
expectError('Error occurred prerendering page "/"')
expectError('Error: Route "/" could not be prerendered.')
expectError('exiting the build.')
......
......@@ -39,7 +39,6 @@ function createExpectError(cliOutput: string) {
}
function runTests(options: { withMinification: boolean }) {
const isTurbopack = !!process.env.TURBOPACK
const { withMinification } = options
describe(`Dynamic IO Errors - ${withMinification ? 'With Minification' : 'Without Minification'}`, () => {
describe('Sync Dynamic - With Fallback - client searchParams', () => {
......@@ -123,14 +122,7 @@ function runTests(options: { withMinification: boolean }) {
}
const expectError = createExpectError(next.cliOutput)
expectError(
'Error: Route "/" used `searchParams.foo`. `searchParams` is now a Promise and should be `awaited` before accessing search param values. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-params'
)
expectError(
'Error: In Route "/" this parent component stack may help you locate where `searchParams.foo` was used.',
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
expectError('Route "/" used `searchParams.foo`')
expectError('Error occurred prerendering page "/"')
expectError('Error: Route "/" could not be prerendered.')
expectError('exiting the build.')
......@@ -218,14 +210,7 @@ function runTests(options: { withMinification: boolean }) {
}
const expectError = createExpectError(next.cliOutput)
expectError(
'Error: Route "/" used `searchParams.foo`. `searchParams` is now a Promise and should be `awaited` before accessing search param values. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-params'
)
expectError(
'Error: In Route "/" this parent component stack may help you locate where `searchParams.foo` was used.',
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
expectError('Route "/" used `searchParams.foo`')
expectError('Error occurred prerendering page "/"')
expectError('Error: Route "/" could not be prerendered.')
expectError('exiting the build.')
......@@ -313,14 +298,7 @@ function runTests(options: { withMinification: boolean }) {
}
const expectError = createExpectError(next.cliOutput)
expectError(
"Error: Route \"/\" used cookies().get('token'). `cookies()` now returns a Promise and should be `awaited` before using it's value. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-headers"
)
expectError(
'Error: In Route "/" this parent component stack may help you locate where cookies().get(\'token\') was used.',
// Turbopack doesn't support disabling minification yet
withMinification || isTurbopack ? undefined : 'IndirectionTwo'
)
expectError('Route "/" used `cookies().get(\'token\')`')
expectError('Error occurred prerendering page "/"')
expectError('Route "/" could not be prerendered.')
expectError('exiting the build.')
......
export async function BuildID() {
const buildID = require('./lazy-id').buildID
await 1
return (
<dl>
<dt>Build ID</dt>
<dd id="id">{buildID}</dd>
</dl>
)
}
import { BuildID } from './build-id'
export default async function Page() {
return (
<>
<p>
This page requires a module lazily during rendering. The Module computes
a "static" id using the current time and a random number. If these APIs
are used while prerendering they would normally trigger a synchronous
dynamic bailout. However since these APIs are used in module scope they
are not semantically part of the render and should be usable like other
"static" values. We demonstrate this with this fixture by asserting that
this page still produces a static result and it does not warn for
reading current time and random in a prerender.
</p>
<BuildID />
</>
)
}
export function BuildID() {
const buildID = require('./lazy-id').buildID
return (
<dl>
<dt>Build ID</dt>
<dd id="id" suppressHydrationWarning={true}>
{buildID}
</dd>
</dl>
)
}
'use client'
import { BuildID } from './build-id'
export default function Page() {
return (
<>
<p>
This page requires a module lazily during rendering. The Module computes
a "static" id using the current time and a random number. If these APIs
are used while prerendering they would normally trigger a synchronous
dynamic bailout. However since these APIs are used in module scope they
are not semantically part of the render and should be usable like other
"static" values. We demonstrate this with this fixture by asserting that
this page still produces a static result and it does not warn for
reading current time and random in a prerender.
</p>
<BuildID />
</>
)
}
......@@ -5,7 +5,9 @@ export function BuildID() {
return (
<dl>
<dt>Build ID</dt>
<dd id="id">{buildID}</dd>
<dd id="id" suppressHydrationWarning={true}>
{buildID}
</dd>
</dl>
)
}
......@@ -6,15 +6,13 @@ import { type UnsafeUnwrappedSearchParams } from 'next/server'
import { IndirectionOne, IndirectionTwo, IndirectionThree } from './indirection'
type SearchParams = { foo: string | string[] | undefined }
export default async function Page(props: {
searchParams: Promise<SearchParams>
}) {
export default function Page(props: { searchParams: Promise<SearchParams> }) {
return (
<>
<p>
This page accesses searchParams synchronously but it does so late enough
in the render that all unfinished sub-trees have a defined Suspense
boundary. This is fine and doesn't need to error the build.
This page accesses searchParams synchronously and it does it early
enough that some sibling component trees are not finished and they do
not have a parent Suspense boundary above them.
</p>
<Suspense fallback={<Fallback />}>
<IndirectionOne>
......
......@@ -83,7 +83,7 @@ describe('dynamic-io', () => {
let $ = await next.render$('/cookies/exercise/async', {})
let cookieWarnings = next.cliOutput
.split('\n')
.filter((l) => l.includes('In route /cookies/exercise'))
.filter((l) => l.includes('Route "/cookies/exercise'))
expect(cookieWarnings).toHaveLength(0)
......@@ -143,7 +143,7 @@ describe('dynamic-io', () => {
let $ = await next.render$('/cookies/exercise/sync', {})
let cookieWarnings = next.cliOutput
.split('\n')
.filter((l) => l.includes('In route /cookies/exercise'))
.filter((l) => l.includes('Route "/cookies/exercise'))
if (!isNextDev) {
expect(cookieWarnings).toHaveLength(0)
......@@ -157,7 +157,9 @@ describe('dynamic-io', () => {
)
expect($('#for-of-x-sentinel-rand').text()).toContain('x-sentinel-rand')
if (isNextDev) {
expect(cookieWarnings[i++]).toContain('cookies were iterated over')
expect(cookieWarnings[i++]).toContain(
'`...cookies()` or similar iteration.'
)
}
// ...spread iteration
......@@ -167,13 +169,15 @@ describe('dynamic-io', () => {
)
expect($('#spread-x-sentinel-rand').text()).toContain('x-sentinel-rand')
if (isNextDev) {
expect(cookieWarnings[i++]).toContain('cookies were iterated over')
expect(cookieWarnings[i++]).toContain(
'`...cookies()` or similar iteration.'
)
}
// cookies().size
expect(parseInt($('#size-cookies').text())).toBeGreaterThanOrEqual(3)
if (isNextDev) {
expect(cookieWarnings[i++]).toContain('cookies().size')
expect(cookieWarnings[i++]).toContain('`cookies().size`')
}
// cookies().get('...') && cookies().getAll('...')
......@@ -181,10 +185,12 @@ describe('dynamic-io', () => {
expect($('#get-x-sentinel-path').text()).toContain('/cookies/exercise/sync')
expect($('#get-x-sentinel-rand').text()).toContain('x-sentinel-rand')
if (isNextDev) {
expect(cookieWarnings[i++]).toContain("cookies().get('x-sentinel')")
expect(cookieWarnings[i++]).toContain("cookies().get('x-sentinel-path')")
expect(cookieWarnings[i++]).toContain("`cookies().get('x-sentinel')`")
expect(cookieWarnings[i++]).toContain(
"`cookies().get('x-sentinel-path')`"
)
expect(cookieWarnings[i++]).toContain(
"cookies().getAll('x-sentinel-rand')"
"`cookies().getAll('x-sentinel-rand')`"
)
}
......@@ -192,9 +198,9 @@ describe('dynamic-io', () => {
expect($('#has-x-sentinel').text()).toContain('true')
expect($('#has-x-sentinel-foobar').text()).toContain('false')
if (isNextDev) {
expect(cookieWarnings[i++]).toContain("cookies().has('x-sentinel')")
expect(cookieWarnings[i++]).toContain("`cookies().has('x-sentinel')`")
expect(cookieWarnings[i++]).toContain(
"cookies().has('x-sentinel-foobar')"
"`cookies().has('x-sentinel-foobar')`"
)
}
......@@ -204,8 +210,10 @@ describe('dynamic-io', () => {
)
expect($('#set-value-x-sentinel').text()).toContain('hello')
if (isNextDev) {
expect(cookieWarnings[i++]).toContain("cookies().set('x-sentinel', ...)")
expect(cookieWarnings[i++]).toContain("cookies().get('x-sentinel')")
expect(cookieWarnings[i++]).toContain(
"`cookies().set('x-sentinel', ...)`"
)
expect(cookieWarnings[i++]).toContain("`cookies().get('x-sentinel')`")
}
// cookies().delete('...', '...')
......@@ -214,8 +222,8 @@ describe('dynamic-io', () => {
)
expect($('#delete-value-x-sentinel').text()).toContain('hello')
if (isNextDev) {
expect(cookieWarnings[i++]).toContain("cookies().delete('x-sentinel')")
expect(cookieWarnings[i++]).toContain("cookies().get('x-sentinel')")
expect(cookieWarnings[i++]).toContain("`cookies().delete('x-sentinel')`")
expect(cookieWarnings[i++]).toContain("`cookies().get('x-sentinel')`")
}
// cookies().clear()
......@@ -224,8 +232,8 @@ describe('dynamic-io', () => {
)
expect($('#clear-value-x-sentinel').text()).toContain('hello')
if (isNextDev) {
expect(cookieWarnings[i++]).toContain('cookies().clear()')
expect(cookieWarnings[i++]).toContain("cookies().get('x-sentinel')")
expect(cookieWarnings[i++]).toContain('`cookies().clear()`')
expect(cookieWarnings[i++]).toContain("`cookies().get('x-sentinel')`")
}
// cookies().toString()
......@@ -233,7 +241,9 @@ describe('dynamic-io', () => {
expect($('#toString').text()).toContain('x-sentinel-path')
expect($('#toString').text()).toContain('x-sentinel-rand=')
if (isNextDev) {
expect(cookieWarnings[i++]).toContain('cookies().toString()')
expect(cookieWarnings[i++]).toContain(
'`cookies().toString()` or implicit casting'
)
}
if (isNextDev) {
......
......@@ -13,7 +13,7 @@ describe('dynamic-io', () => {
}
it('should not have route specific errors', async () => {
expect(next.cliOutput).not.toMatch('Error: Route /')
expect(next.cliOutput).not.toMatch('Error: Route "/')
expect(next.cliOutput).not.toMatch('Error occurred prerendering page')
})
......
......@@ -25,18 +25,18 @@ describe('dynamic-io', () => {
}
it('should fully prerender pages that use draftMode', async () => {
expect(getLines('In route /draftmode')).toEqual([])
expect(getLines('Route "/draftmode')).toEqual([])
let $ = await next.render$('/draftmode/async', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#draft-mode').text()).toBe('false')
expect(getLines('In route /draftmode')).toEqual([])
expect(getLines('Route "/draftmode')).toEqual([])
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at buildtime')
expect($('#draft-mode').text()).toBe('false')
expect(getLines('In route /draftmode')).toEqual([])
expect(getLines('Route "/draftmode')).toEqual([])
}
$ = await next.render$('/draftmode/sync', {})
......@@ -44,16 +44,16 @@ describe('dynamic-io', () => {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#draft-mode').text()).toBe('false')
expect(getLines('In route /draftmode')).toEqual([
expect.stringContaining(
'a `draftMode()` property was accessed directly with `draftMode().isEnabled`.'
),
expect(getLines('Route "/draftmode')).toEqual([
expect.stringContaining('`draftMode().isEnabled`'),
// TODO need to figure out why deduping isn't working here
expect.stringContaining('`draftMode().isEnabled`'),
])
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at buildtime')
expect($('#draft-mode').text()).toBe('false')
expect(getLines('In route /draftmode')).toEqual([])
expect(getLines('Route "/draftmode')).toEqual([])
}
})
})
......@@ -83,7 +83,7 @@ describe('dynamic-io', () => {
let $ = await next.render$('/headers/exercise/async', {})
let cookieWarnings = next.cliOutput
.split('\n')
.filter((l) => l.includes('In route /headers/exercise'))
.filter((l) => l.includes('Route "/headers/exercise'))
expect(cookieWarnings).toHaveLength(0)
......@@ -162,7 +162,7 @@ describe('dynamic-io', () => {
let $ = await next.render$('/headers/exercise/sync', {})
let headerWarnings = next.cliOutput
.split('\n')
.filter((l) => l.includes('In route /headers/exercise'))
.filter((l) => l.includes('Route "/headers/exercise'))
if (!isNextDev) {
expect(headerWarnings).toHaveLength(0)
......@@ -176,9 +176,9 @@ describe('dynamic-io', () => {
expect($('#append-value-x-sentinel').text()).toContain('hello')
if (isNextDev) {
expect(headerWarnings[i++]).toContain(
"headers().append('x-sentinel', ...)"
"`headers().append('x-sentinel', ...)`"
)
expect(headerWarnings[i++]).toContain("headers().get('x-sentinel')")
expect(headerWarnings[i++]).toContain("`headers().get('x-sentinel')`")
}
// headers().delete('...')
......@@ -187,23 +187,23 @@ describe('dynamic-io', () => {
)
expect($('#delete-value-x-sentinel').text()).toContain('hello')
if (isNextDev) {
expect(headerWarnings[i++]).toContain("headers().delete('x-sentinel')")
expect(headerWarnings[i++]).toContain("headers().get('x-sentinel')")
expect(headerWarnings[i++]).toContain("`headers().delete('x-sentinel')`")
expect(headerWarnings[i++]).toContain("`headers().get('x-sentinel')`")
}
// headers().get('...')
expect($('#get-x-sentinel').text()).toContain('hello')
if (isNextDev) {
expect(headerWarnings[i++]).toContain("headers().get('x-sentinel')")
expect(headerWarnings[i++]).toContain("`headers().get('x-sentinel')`")
}
// cookies().has('...')
expect($('#has-x-sentinel').text()).toContain('true')
expect($('#has-x-sentinel-foobar').text()).toContain('false')
if (isNextDev) {
expect(headerWarnings[i++]).toContain("headers().has('x-sentinel')")
expect(headerWarnings[i++]).toContain("`headers().has('x-sentinel')`")
expect(headerWarnings[i++]).toContain(
"headers().has('x-sentinel-foobar')"
"`headers().has('x-sentinel-foobar')`"
)
}
......@@ -213,8 +213,10 @@ describe('dynamic-io', () => {
)
expect($('#set-value-x-sentinel').text()).toContain('hello')
if (isNextDev) {
expect(headerWarnings[i++]).toContain("headers().set('x-sentinel', ...)")
expect(headerWarnings[i++]).toContain("headers().get('x-sentinel')")
expect(headerWarnings[i++]).toContain(
"`headers().set('x-sentinel', ...)`"
)
expect(headerWarnings[i++]).toContain("`headers().get('x-sentinel')`")
}
// headers().getSetCookie()
......@@ -222,7 +224,7 @@ describe('dynamic-io', () => {
// not response headers and is not mutable.
expect($('#get-set-cookie').text()).toEqual('[]')
if (isNextDev) {
expect(headerWarnings[i++]).toContain('headers().getSetCookie()')
expect(headerWarnings[i++]).toContain('`headers().getSetCookie()`')
}
// headers().forEach(...)
......@@ -232,7 +234,7 @@ describe('dynamic-io', () => {
)
expect($('#for-each-x-sentinel-rand').length).toBe(1)
if (isNextDev) {
expect(headerWarnings[i++]).toContain('headers().forEach(...)')
expect(headerWarnings[i++]).toContain('`headers().forEach(...)`')
}
// headers().keys(...)
......@@ -240,7 +242,7 @@ describe('dynamic-io', () => {
expect($('#keys-x-sentinel-path').text()).toContain('x-sentinel-path')
expect($('#keys-x-sentinel-rand').text()).toContain('x-sentinel-rand')
if (isNextDev) {
expect(headerWarnings[i++]).toContain('headers().keys()')
expect(headerWarnings[i++]).toContain('`headers().keys()`')
}
// headers().values(...)
......@@ -250,7 +252,7 @@ describe('dynamic-io', () => {
)
expect($('[data-class="values"]').length).toBe(3)
if (isNextDev) {
expect(headerWarnings[i++]).toContain('headers().values()')
expect(headerWarnings[i++]).toContain('`headers().values()`')
}
// headers().entries(...)
......@@ -260,7 +262,7 @@ describe('dynamic-io', () => {
)
expect($('#entries-x-sentinel-rand').length).toBe(1)
if (isNextDev) {
expect(headerWarnings[i++]).toContain('headers().entries()')
expect(headerWarnings[i++]).toContain('`headers().entries()`')
}
// for...of headers()
......@@ -270,7 +272,9 @@ describe('dynamic-io', () => {
)
expect($('#for-of-x-sentinel-rand').length).toBe(1)
if (isNextDev) {
expect(headerWarnings[i++]).toContain('headers were iterated over.')
expect(headerWarnings[i++]).toContain(
'`...headers()` or similar iteration'
)
}
// ...headers()
......@@ -280,7 +284,9 @@ describe('dynamic-io', () => {
)
expect($('#spread-x-sentinel-rand').length).toBe(1)
if (isNextDev) {
expect(headerWarnings[i++]).toContain('headers were iterated over.')
expect(headerWarnings[i++]).toContain(
'`...headers()` or similar iteration'
)
}
if (isNextDev) {
......
......@@ -13,7 +13,7 @@ describe('dynamic-io', () => {
}
it('should not have route specific errors', async () => {
expect(next.cliOutput).not.toMatch('Error: Route /')
expect(next.cliOutput).not.toMatch('Error: Route "/')
expect(next.cliOutput).not.toMatch('Error occurred prerendering page')
})
......
......@@ -13,7 +13,7 @@ describe('dynamic-io', () => {
}
it('should not have route specific errors', async () => {
expect(next.cliOutput).not.toMatch('Error: Route /')
expect(next.cliOutput).not.toMatch('Error: Route "/')
expect(next.cliOutput).not.toMatch('Error occurred prerendering page')
})
......
......@@ -247,7 +247,7 @@ describe('dynamic-io', () => {
})
it('should prerender GET route handlers when accessing awaited params', async () => {
expect(getLines('In route /routes/[dyn]')).toEqual([])
expect(getLines('Route "/routes/[dyn]')).toEqual([])
let str = await next.render('/routes/1/async', {})
let json = JSON.parse(str)
......@@ -255,12 +255,12 @@ describe('dynamic-io', () => {
expect(json.value).toEqual('at runtime')
expect(json.type).toBe('dynamic params')
expect(json.param).toBe('1')
expect(getLines('In route /routes/[dyn]')).toEqual([])
expect(getLines('Route "/routes/[dyn]')).toEqual([])
} else {
expect(json.value).toEqual('at buildtime')
expect(json.type).toBe('dynamic params')
expect(json.param).toBe('1')
expect(getLines('In route /routes/[dyn]')).toEqual([])
expect(getLines('Route "/routes/[dyn]')).toEqual([])
}
str = await next.render('/routes/2/async', {})
......@@ -270,17 +270,17 @@ describe('dynamic-io', () => {
expect(json.value).toEqual('at runtime')
expect(json.type).toBe('dynamic params')
expect(json.param).toBe('2')
expect(getLines('In route /routes/[dyn]')).toEqual([])
expect(getLines('Route "/routes/[dyn]')).toEqual([])
} else {
expect(json.value).toEqual('at runtime')
expect(json.type).toBe('dynamic params')
expect(json.param).toBe('2')
expect(getLines('In route /routes/[dyn]')).toEqual([])
expect(getLines('Route "/routes/[dyn]')).toEqual([])
}
})
it('should prerender GET route handlers when accessing params without awaiting first', async () => {
expect(getLines('In route /routes/[dyn]')).toEqual([])
expect(getLines('Route "/routes/[dyn]')).toEqual([])
let str = await next.render('/routes/1/sync', {})
let json = JSON.parse(str)
......@@ -288,16 +288,14 @@ describe('dynamic-io', () => {
expect(json.value).toEqual('at runtime')
expect(json.type).toBe('dynamic params')
expect(json.param).toBe('1')
expect(getLines('In route /routes/[dyn]')).toEqual([
expect.stringContaining(
'a param property was accessed directly with `params.dyn`.'
),
expect(getLines('Route "/routes/[dyn]')).toEqual([
expect.stringContaining('`params.dyn`.'),
])
} else {
expect(json.value).toEqual('at buildtime')
expect(json.type).toBe('dynamic params')
expect(json.param).toBe('1')
expect(getLines('In route /routes/[dyn]')).toEqual([])
expect(getLines('Route "/routes/[dyn]')).toEqual([])
}
str = await next.render('/routes/2/sync', {})
......@@ -307,16 +305,14 @@ describe('dynamic-io', () => {
expect(json.value).toEqual('at runtime')
expect(json.type).toBe('dynamic params')
expect(json.param).toBe('2')
expect(getLines('In route /routes/[dyn]')).toEqual([
expect.stringContaining(
'a param property was accessed directly with `params.dyn`.'
),
expect(getLines('Route "/routes/[dyn]')).toEqual([
expect.stringContaining('`params.dyn`.'),
])
} else {
expect(json.value).toEqual('at runtime')
expect(json.type).toBe('dynamic params')
expect(json.param).toBe('2')
expect(getLines('In route /routes/[dyn]')).toEqual([])
expect(getLines('Route "/routes/[dyn]')).toEqual([])
}
})
})
......@@ -16,7 +16,7 @@ describe('dynamic-io', () => {
const itSkipTurbopack = isTurbopack ? it.skip : it
it('should not have route specific errors', async () => {
expect(next.cliOutput).not.toMatch('Error: Route /')
expect(next.cliOutput).not.toMatch('Error: Route "/')
expect(next.cliOutput).not.toMatch('Error occurred prerendering page')
})
......
......@@ -13,7 +13,7 @@ describe('dynamic-io', () => {
}
it('should not have route specific errors', async () => {
expect(next.cliOutput).not.toMatch('Error: Route /')
expect(next.cliOutput).not.toMatch('Error: Route "/')
expect(next.cliOutput).not.toMatch('Error occurred prerendering page')
})
......
......@@ -59,7 +59,10 @@ describe('ppr', () => {
if (isNextDev) {
it('should have the dynamic part', async () => {
let $ = await next.render$(pathname)
let dynamic = $('#container > #dynamic > #state')
// asserting this flushes in a single pass in dev is not reliable
// so we just assert that the nodes are somewhere in the document
// even if they aren't in position
let dynamic = $('#dynamic > #state')
expect(dynamic.length).toBe(1)
expect(dynamic.text()).toBe('Not Signed In')
......@@ -73,7 +76,7 @@ describe('ppr', () => {
},
}
)
dynamic = $('#container > #dynamic > #state')
dynamic = $('#dynamic > #state')
expect(dynamic.length).toBe(1)
expect(dynamic.text()).toBe('Signed In')
})
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment