Commit 62e08a5f authored by Janka Uryga's avatar Janka Uryga

fix params in instant validation

parent a9a8e272
...@@ -6436,11 +6436,20 @@ async function validateInstantConfigInBuildWithSample( ...@@ -6436,11 +6436,20 @@ async function validateInstantConfigInBuildWithSample(
) )
const sampleParams = sample.params ?? {} const sampleParams = sample.params ?? {}
/** The actual params to use for this render, possibly with placeholders (fallbacks) */
const interpolatedParams: Params = {}
let fallbackRouteParams: OpaqueFallbackRouteParams | null = null let fallbackRouteParams: OpaqueFallbackRouteParams | null = null
if (allPossibleFallbackRouteParams) { if (allPossibleFallbackRouteParams) {
const fallbackRouteParamsMut = new Map() const fallbackRouteParamsMut = new Map()
for (const [paramKey, value] of allPossibleFallbackRouteParams) { for (const [paramKey, value] of allPossibleFallbackRouteParams) {
if (!(paramKey in sampleParams)) { if (paramKey in sampleParams) {
interpolatedParams[paramKey] = sampleParams[paramKey]
} else {
// NOTE: fallback params logic in `param.ts` relies on the param key being present,
// so we need to set it to something. In prerenders, this seems to be a placeholder `[paramKey]`,
// but the value doesn't really matter, so here we'll just use the fallback value instead.
interpolatedParams[paramKey] = value
fallbackRouteParamsMut.set(paramKey, value) fallbackRouteParamsMut.set(paramKey, value)
} }
} }
...@@ -6448,7 +6457,7 @@ async function validateInstantConfigInBuildWithSample( ...@@ -6448,7 +6457,7 @@ async function validateInstantConfigInBuildWithSample(
} }
const getDynamicParamFromSegment = makeGetDynamicParamFromSegment( const getDynamicParamFromSegment = makeGetDynamicParamFromSegment(
sampleParams, interpolatedParams,
fallbackRouteParams, fallbackRouteParams,
false false
) )
...@@ -6507,7 +6516,7 @@ async function validateInstantConfigInBuildWithSample( ...@@ -6507,7 +6516,7 @@ async function validateInstantConfigInBuildWithSample(
workStore, workStore,
parsedRequestHeaders: outerCtx.parsedRequestHeaders, parsedRequestHeaders: outerCtx.parsedRequestHeaders,
getDynamicParamFromSegment, getDynamicParamFromSegment,
interpolatedParams: sampleParams, interpolatedParams,
query: sampleQuery, query: sampleQuery,
isPrefetch: false, isPrefetch: false,
isPossibleServerAction: false, isPossibleServerAction: false,
...@@ -6561,6 +6570,7 @@ async function validateInstantConfigInBuildWithSample( ...@@ -6561,6 +6570,7 @@ async function validateInstantConfigInBuildWithSample(
userspaceMutableCookies: unusedMutableCookies, userspaceMutableCookies: unusedMutableCookies,
draftMode, draftMode,
rootParams: sampleRootParams, rootParams: sampleRootParams,
fallbackParams: fallbackRouteParams,
validationSamples, validationSamples,
validationSampleTracking: createValidationSampleTracking(), validationSampleTracking: createValidationSampleTracking(),
// These will be set when rendering // These will be set when rendering
......
...@@ -257,6 +257,11 @@ export function createExhaustiveParamsProxy<TParams extends Params>( ...@@ -257,6 +257,11 @@ export function createExhaustiveParamsProxy<TParams extends Params>(
declaredParamNames: Set<string>, declaredParamNames: Set<string>,
route: string route: string
): TParams { ): TParams {
// If all params for this route have a sample, there's no need to instrument the params object.
if (areAllParamsDeclared(underlyingParams, declaredParamNames)) {
return underlyingParams
}
return new Proxy(underlyingParams, { return new Proxy(underlyingParams, {
get(target, prop, receiver) { get(target, prop, receiver) {
if ( if (
...@@ -282,6 +287,18 @@ export function createExhaustiveParamsProxy<TParams extends Params>( ...@@ -282,6 +287,18 @@ export function createExhaustiveParamsProxy<TParams extends Params>(
}) })
} }
function areAllParamsDeclared(
underlyingParams: Params,
declaredParamNames: Set<string>
): boolean {
for (const paramName in underlyingParams) {
if (!declaredParamNames.has(paramName)) {
return false
}
}
return true
}
/** /**
* Creates searchParams wrapped with an exhaustive proxy. * Creates searchParams wrapped with an exhaustive proxy.
* Accessing a searchParam not declared in the sample will throw an error. * Accessing a searchParam not declared in the sample will throw an error.
......
...@@ -266,28 +266,31 @@ export function createServerParamsForServerSegment( ...@@ -266,28 +266,31 @@ export function createServerParamsForServerSegment(
workUnitStore, workUnitStore,
isRuntimePrefetchable isRuntimePrefetchable
) )
} else if ( } else {
workUnitStore.asyncApiPromises && if (
workUnitStore.validationSamples workUnitStore.asyncApiPromises &&
) { hasFallbackRouteParams(
return createServerParamsInInstantValidation( underlyingParams,
underlyingParams, workUnitStore.fallbackParams
workStore, )
workUnitStore.validationSamples, ) {
workUnitStore.asyncApiPromises, const parentPromise = isRuntimePrefetchable
isRuntimePrefetchable
)
} else if (
workUnitStore.asyncApiPromises &&
hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)
) {
return (
isRuntimePrefetchable
? workUnitStore.asyncApiPromises.earlySharedParamsParent ? workUnitStore.asyncApiPromises.earlySharedParamsParent
: workUnitStore.asyncApiPromises.sharedParamsParent : workUnitStore.asyncApiPromises.sharedParamsParent
).then(() => underlyingParams)
} else { if (workUnitStore.validationSamples) {
return createRenderParamsInProd(underlyingParams) const proxiedUnderlying = createServerParamsInInstantValidation(
underlyingParams,
workStore,
workUnitStore.validationSamples
)
return parentPromise.then(() => proxiedUnderlying)
} else {
return parentPromise.then(() => underlyingParams)
}
} else {
return createRenderParamsInProd(underlyingParams)
}
} }
default: default:
workUnitStore satisfies never workUnitStore satisfies never
...@@ -464,23 +467,16 @@ function hasFallbackRouteParams( ...@@ -464,23 +467,16 @@ function hasFallbackRouteParams(
function createServerParamsInInstantValidation( function createServerParamsInInstantValidation(
underlyingParams: Params, underlyingParams: Params,
workStore: WorkStore, workStore: WorkStore,
validationSamples: NonNullable<RequestStore['validationSamples']>, validationSamples: NonNullable<RequestStore['validationSamples']>
asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>, ): Params {
isRuntimePrefetchable: boolean
): Promise<Params> {
const { createExhaustiveParamsProxy } = const { createExhaustiveParamsProxy } =
require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples') require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')
const declaredParams = new Set(Object.keys(validationSamples.params ?? {})) const declaredParams = new Set(Object.keys(validationSamples.params ?? {}))
const proxiedUnderlying = createExhaustiveParamsProxy( return createExhaustiveParamsProxy(
underlyingParams, underlyingParams,
declaredParams, declaredParams,
workStore.route workStore.route
) )
return (
isRuntimePrefetchable
? asyncApiPromises.earlySharedParamsParent
: asyncApiPromises.sharedParamsParent
).then(() => proxiedUnderlying)
} }
function createClientParamsInInstantValidation( function createClientParamsInInstantValidation(
......
import type { Instant } from 'next'
import { ensureThrows } from '../../../../../../ensure-error'
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [
{
params: {
one: '123',
// two: <missing>
},
},
],
}
export default async function Page({
params,
}: {
params: Promise<Record<string, string>>
}) {
return (
<main>
<p>
This page reads a param that is not declared in the sample via iterating
over its keys and values, so it should fail validation with an
exhaustiveness error.
</p>
<TestParams params={params} />
</main>
)
}
async function TestParams({
params,
}: {
params: Promise<Record<string, string>>
}) {
const p = await params
// We're not allowed to access the values of params that aren't in the samples.
ensureThrows(() => ({ ...p }))
return null
}
...@@ -43,15 +43,21 @@ async function TestParams({ ...@@ -43,15 +43,21 @@ async function TestParams({
assert.equal('three' in p, false) assert.equal('three' in p, false)
assert.equal(p.three, undefined) assert.equal(p.three, undefined)
// We're not allowed to access params not in the samples. // We're allowed to look at the keys of the params object even if it's missing some values.
ensureThrows(() => p.two) assert.equal(
'two' in p,
true,
`Expected \`in\` to work for params without samples'`
)
// We're allowed to look at the keys of the params object even if it's missing some values.
assert.deepEqual(
Object.keys(p),
['one', 'two'],
`Expected proxied params to contain 'one' and 'two'`
)
// TODO: test `in` and iteration // We're not allowed to access the values of params that aren't in the samples.
// assert.deepStrictEqual( ensureThrows(() => p.two)
// { ...p },
// { one: '123', two: '456' },
// `Unexpected value when iterating over params object`
// )
return null return null
} }
import type { Instant } from 'next'
import assert from 'node:assert/strict'
import { ensureThrows } from '../../../../../../ensure-error'
export const unstable_instant: Instant = {
prefetch: 'runtime',
samples: [
{
params: {
// one: <missing>,
// two: <missing>
},
},
],
}
export default async function Page({
params,
}: {
params: Promise<Record<string, string>>
}) {
return (
<main>
<p>
This page reads a param that is not declared in the sample, so it should
fail validation with an exhaustiveness error.
</p>
<TestParams params={params} />
</main>
)
}
async function TestParams({
params,
}: {
params: Promise<Record<string, string>>
}) {
const p = await params
// We're allowed to access names that don't correspond to a param.
assert.equal('three' in p, false)
assert.equal(p.three, undefined)
// We're allowed to look at the keys of the params object even if it's missing some values.
assert.equal(
'one' in p,
true,
`Expected \`in\` to work for params without samples'`
)
assert.equal(
'two' in p,
true,
`Expected \`in\` to work for params without samples'`
)
// We're allowed to look at the keys of the params object even if it's missing some values.
assert.deepEqual(
Object.keys(p),
['one', 'two'],
`Expected proxied params to contain 'one' and 'two'`
)
// We're not allowed to access the values of params that aren't in the samples.
ensureThrows(() => p.one)
return null
}
import type { Instant } from 'next'
export const unstable_instant: Instant = {
prefetch: 'static',
samples: [{}],
}
export default async function Page({
params,
}: {
params: Promise<Record<string, string>>
}) {
return (
<main>
<p>
When validated in build, params should hang in the static stage when no
samples are provided
</p>
<TestParams params={params} />
</main>
)
}
async function TestParams({
params,
}: {
params: Promise<Record<string, string>>
}) {
await params
return null
}
import type { Instant } from 'next'
import assert from 'node:assert/strict'
export const unstable_instant: Instant = {
prefetch: 'static',
samples: [{}],
}
export default async function Page({
params,
}: {
params: Promise<Record<string, string>>
}) {
return (
<main>
<p>
When validated in build, awaiting params on a page with no params should
not block.
</p>
<TestParams params={params} />
</main>
)
}
async function TestParams({
params,
}: {
params: Promise<Record<string, string>>
}) {
const p = await params
assert.deepStrictEqual(p, {}, `Unexpected value in params object`)
return null
}
...@@ -551,23 +551,23 @@ describe('instant-validation-build', () => { ...@@ -551,23 +551,23 @@ describe('instant-validation-build', () => {
expectNoBuildValidationErrors(result) expectNoBuildValidationErrors(result)
}) })
it('error - reading a param not present in samples', async () => { it('error - reading a param not present in samples when a different param is provided', async () => {
const result = await prerender( const result = await prerender(
'/(default)/params/invalid-param-not-provided/[one]/[two]' '/(default)/params/invalid-param-not-provided/[one]/[two]'
) )
expect(extractBuildValidationError(result.cliOutput)) expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(` .toMatchInlineSnapshot(`
"Error: Route "/params/invalid-param-not-provided/[one]/[two]" accessed param "two" which is not defined in the \`samples\` of \`unstable_instant\`. Add it to the sample's \`params\` object. "Error: Route "/params/invalid-param-not-provided/[one]/[two]" accessed param "two" which is not defined in the \`samples\` of \`unstable_instant\`. Add it to the sample's \`params\` object.
at <unknown> (app/(default)/params/invalid-param-not-provided/[one]/[two]/page.tsx:47:24) at <unknown> (app/(default)/params/invalid-param-not-provided/[one]/[two]/page.tsx:60:24)
at <unknown> (ensure-error.ts:11:5) at <unknown> (ensure-error.ts:11:5)
at a (app/(default)/params/invalid-param-not-provided/[one]/[two]/page.tsx:47:3) at a (app/(default)/params/invalid-param-not-provided/[one]/[two]/page.tsx:60:3)
45 | 58 |
46 | // We're not allowed to access params not in the samples. 59 | // We're not allowed to access the values of params that aren't in the samples.
> 47 | ensureThrows(() => p.two) > 60 | ensureThrows(() => p.two)
| ^ | ^
48 | 61 |
49 | // TODO: test \`in\` and iteration 62 | return null
50 | // assert.deepStrictEqual( { 63 | } {
digest: 'INSTANT_VALIDATION_ERROR' digest: 'INSTANT_VALIDATION_ERROR'
} }
Build-time instant validation failed for route "/params/invalid-param-not-provided/[one]/[two]". Build-time instant validation failed for route "/params/invalid-param-not-provided/[one]/[two]".
...@@ -577,6 +577,58 @@ describe('instant-validation-build', () => { ...@@ -577,6 +577,58 @@ describe('instant-validation-build', () => {
expect(result.exitCode).toBe(1) expect(result.exitCode).toBe(1)
}) })
it('error - reading a param not present in samples when no other params are provided', async () => {
const result = await prerender(
'/(default)/params/invalid-params-not-provided/[one]/[two]'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/params/invalid-params-not-provided/[one]/[two]" accessed param "one" which is not defined in the \`samples\` of \`unstable_instant\`. Add it to the sample's \`params\` object.
at <unknown> (app/(default)/params/invalid-params-not-provided/[one]/[two]/page.tsx:63:24)
at <unknown> (ensure-error.ts:11:5)
at a (app/(default)/params/invalid-params-not-provided/[one]/[two]/page.tsx:63:3)
61 |
62 | // We're not allowed to access the values of params that aren't in the samples.
> 63 | ensureThrows(() => p.one)
| ^
64 |
65 | return null
66 | } {
digest: 'INSTANT_VALIDATION_ERROR'
}
Build-time instant validation failed for route "/params/invalid-params-not-provided/[one]/[two]".
Stopping prerender due to instant validation errors."
`)
expect(result.cliOutput).not.toContain('AssertionError')
expect(result.exitCode).toBe(1)
})
it('error - reading a param not present in samples via iteration', async () => {
const result = await prerender(
'/(default)/params/invalid-param-not-provided-iter/[one]/[two]'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/params/invalid-param-not-provided-iter/[one]/[two]" accessed param "two" which is not defined in the \`samples\` of \`unstable_instant\`. Add it to the sample's \`params\` object.
at <unknown> (app/(default)/params/invalid-param-not-provided-iter/[one]/[two]/page.tsx:41:23)
at <unknown> (ensure-error.ts:11:5)
at a (app/(default)/params/invalid-param-not-provided-iter/[one]/[two]/page.tsx:41:3)
39 |
40 | // We're not allowed to access the values of params that aren't in the samples.
> 41 | ensureThrows(() => ({ ...p }))
| ^
42 |
43 | return null
44 | } {
digest: 'INSTANT_VALIDATION_ERROR'
}
Build-time instant validation failed for route "/params/invalid-param-not-provided-iter/[one]/[two]".
Stopping prerender due to instant validation errors."
`)
expect(result.cliOutput).not.toContain('AssertionError')
expect(result.exitCode).toBe(1)
})
it('error - reading a param not present in samples and catching the error', async () => { it('error - reading a param not present in samples and catching the error', async () => {
const result = await prerender( const result = await prerender(
'/(default)/params/invalid-param-not-provided-caught/[one]/[two]' '/(default)/params/invalid-param-not-provided-caught/[one]/[two]'
...@@ -603,6 +655,27 @@ describe('instant-validation-build', () => { ...@@ -603,6 +655,27 @@ describe('instant-validation-build', () => {
expect(result.exitCode).toBe(1) expect(result.exitCode).toBe(1)
}) })
it('valid - awaiting params in a segment with no params is allowed', async () => {
const result = await prerender('/(default)/params/valid-no-params')
expect(result.cliOutput).not.toContain('AssertionError')
expectNoBuildValidationErrors(result)
})
it('invalid - awaiting params without suspense with no samples fails validation', async () => {
const result = await prerender(
'/(default)/params/invalid-params-without-samples-hangs/[slug]'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/params/invalid-params-without-samples-hangs/[slug]": Runtime data such as \`cookies()\`, \`headers()\`, \`params\`, or \`searchParams\` was accessed outside of \`<Suspense>\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route
at main (<anonymous>)
at body (<anonymous>)
at html (<anonymous>)
Build-time instant validation failed for route "/params/invalid-params-without-samples-hangs/[slug]".
Stopping prerender due to instant validation errors."
`)
})
it('useParams() receives params from samples', async () => { it('useParams() receives params from samples', async () => {
const result = await prerender( const result = await prerender(
'/(default)/params/valid-use-params/[one]/[two]' '/(default)/params/valid-use-params/[one]/[two]'
......
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