Unverified Commit 9f43bb55 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Simplify router state header tests

Drop the unit tests, which mostly tested implementation details. Type the valid router state fixture so it breaks when the router state shape changes, and remove the server log assertion, which can't be observed in deployment.
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent adacbfbe
import type { IncomingHttpHeaders } from 'http'
import {
isInvalidFlightRouterStateError,
parseRequestHeaders,
} from './parse-request-headers'
import { parseAndValidateFlightRouterState } from '../../app-render/parse-and-validate-flight-router-state'
jest.mock('../../app-render/parse-and-validate-flight-router-state', () => {
const actual = jest.requireActual(
'../../app-render/parse-and-validate-flight-router-state'
)
return {
...actual,
parseAndValidateFlightRouterState: jest.fn(
actual.parseAndValidateFlightRouterState
),
}
})
const parseSpy = jest.mocked(parseAndValidateFlightRouterState)
beforeEach(() => {
parseSpy.mockClear()
})
const validTree = encodeURIComponent(
JSON.stringify([
'',
{
children: [['slug', 'foo', 'd', null], { children: ['__PAGE__', {}] }],
},
])
)
// Next.js 15 encoded dynamic segments as a 3-tuple and sent a boolean
// `isRootLayout` flag at index 4.
const legacyTree = encodeURIComponent(
JSON.stringify([
'',
{
children: [
['slug', 'foo', 'd'],
{ children: ['__PAGE__', {}] },
null,
null,
],
},
null,
null,
true,
])
)
const options = { isRoutePPREnabled: false, previewModeId: undefined }
function rscHeaders(
stateTree: string | string[] | undefined,
extra: IncomingHttpHeaders = {}
): IncomingHttpHeaders {
return { rsc: '1', 'next-router-state-tree': stateTree, ...extra }
}
function getParseError(headers: IncomingHttpHeaders, opts = options) {
try {
parseRequestHeaders(headers, opts)
} catch (err) {
return err
}
throw new Error('Expected parseRequestHeaders to throw')
}
describe('parseRequestHeaders router state', () => {
it('parses a valid header once', () => {
expect(
parseRequestHeaders(rscHeaders(validTree), options).flightRouterState
).toEqual(JSON.parse(decodeURIComponent(validTree)))
expect(parseSpy).toHaveBeenCalledTimes(1)
})
it('accepts a missing header', () => {
expect(
parseRequestHeaders({ rsc: '1' }, options).flightRouterState
).toBeUndefined()
})
it.each([
[
'a header from an older Next.js version',
legacyTree,
'The router state header was sent but could not be parsed.',
],
[
'malformed JSON',
'%5B',
'The router state header was sent but could not be parsed.',
],
[
'a schema mismatch',
encodeURIComponent(JSON.stringify(['', ''])),
'The router state header was sent but could not be parsed.',
],
[
'a malformed URI encoding',
'%E0%A4%A',
'The router state header was sent but could not be parsed.',
],
[
'a header that is too large',
'a'.repeat(20 * 2000 + 1),
'The router state header was too large.',
],
[
'a header sent multiple times',
[validTree, validTree],
'Multiple router state headers were sent. This is not allowed.',
],
])('rejects %s as invalid client input', (_, stateTree, message) => {
const err = getParseError(rscHeaders(stateTree))
expect(isInvalidFlightRouterStateError(err)).toBe(true)
expect((err as Error).message).toBe(message)
expect(parseSpy).toHaveBeenCalledTimes(1)
})
it('ignores the header on non-RSC requests', () => {
expect(
parseRequestHeaders({ 'next-router-state-tree': legacyTree }, options)
.flightRouterState
).toBeUndefined()
expect(parseSpy).not.toHaveBeenCalled()
})
it('ignores the header on prefetches of PPR-enabled routes', () => {
const headers = rscHeaders(legacyTree, { 'next-router-prefetch': '1' })
expect(
parseRequestHeaders(headers, { ...options, isRoutePPREnabled: true })
.flightRouterState
).toBeUndefined()
expect(parseSpy).not.toHaveBeenCalled()
expect(isInvalidFlightRouterStateError(getParseError(headers))).toBe(true)
})
})
describe('isInvalidFlightRouterStateError', () => {
it('recognizes the error by its code, not its class', () => {
// Errors may be thrown and caught by different bundle layers, each with
// its own copy of the error class.
const err = Object.assign(new Error('x'), {
code: 'NEXT_INVALID_FLIGHT_ROUTER_STATE',
})
expect(isInvalidFlightRouterStateError(err)).toBe(true)
})
it.each([
['an ordinary error', new Error('The router state header was too large.')],
['an error with another code', Object.assign(new Error(), { code: 'X' })],
['a string', 'NEXT_INVALID_FLIGHT_ROUTER_STATE'],
['null', null],
['undefined', undefined],
])('is false for %s', (_, value) => {
expect(isInvalidFlightRouterStateError(value)).toBe(false)
})
})
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import type { FlightRouterState } from 'next/dist/shared/lib/app-router-types'
import { import {
computeCacheBustingSearchParam, computeCacheBustingSearchParam,
computeLegacyCacheBustingSearchParam, computeLegacyCacheBustingSearchParam,
} from 'next/dist/shared/lib/router/utils/cache-busting-search-param' } from 'next/dist/shared/lib/router/utils/cache-busting-search-param'
// Builds a router state tree for `/<prefix...>/<slug>`, where `<slug>` is a // Router state for `/<prefix...>/<slug>`, where `<slug>` is a dynamic
// dynamic `[slug]` segment. // `[slug]` segment. Typed so that it fails to compile when the router state
function createStateTree( // shape changes.
prefixSegments: string[], function createStateTree(prefixSegments: string[], slug: string): string {
slug: string, let tree: FlightRouterState = [
{ legacy }: { legacy: boolean } ['slug', slug, 'd', null],
): string { { children: ['__PAGE__', {}] },
// Next.js 15 encoded dynamic segments as a 3-tuple and sent a boolean ]
// `isRootLayout` flag at index 4. Tabs that are still running an older
// build send this shape after a deployment.
let tree: unknown[] = legacy
? [['slug', slug, 'd'], { children: ['__PAGE__', {}] }, null, null]
: [['slug', slug, 'd', null], { children: ['__PAGE__', {}] }]
for (const segment of [...prefixSegments].reverse()) { for (const segment of [...prefixSegments].reverse()) {
tree = [segment, { children: tree }] tree = [segment, { children: tree }]
} }
const root: FlightRouterState = ['', { children: tree }]
return encodeURIComponent(JSON.stringify(root))
}
const root = legacy // The same router state in the shape Next.js 15 sent: dynamic segments were a
? ['', { children: tree }, null, null, true] // 3-tuple and index 4 was a boolean `isRootLayout` flag. Tabs still running an
: ['', { children: tree }] // older build send this after a deployment. It intentionally doesn't match
// the current type, so it is left untyped.
function createLegacyStateTree(prefixSegments: string[], slug: string): string {
let tree: unknown[] = [
['slug', slug, 'd'],
{ children: ['__PAGE__', {}] },
null,
null,
]
for (const segment of [...prefixSegments].reverse()) {
tree = [segment, { children: tree }]
}
const root = ['', { children: tree }, null, null, true]
return encodeURIComponent(JSON.stringify(root)) return encodeURIComponent(JSON.stringify(root))
} }
...@@ -112,30 +122,23 @@ describe('app dir - validation', () => { ...@@ -112,30 +122,23 @@ describe('app dir - validation', () => {
const pathname = `/${[...prefixSegments, 'foo'].join('/')}` const pathname = `/${[...prefixSegments, 'foo'].join('/')}`
it('should reject a router state tree sent by an older Next.js version with a 400', async () => { it('should reject a router state tree sent by an older Next.js version with a 400', async () => {
const outputIndex = next.cliOutput.length
const res = await fetchWithRouterState( const res = await fetchWithRouterState(
next, next,
pathname, pathname,
createStateTree(prefixSegments, 'foo', { legacy: true }) createLegacyStateTree(prefixSegments, 'foo')
) )
expect(res.status).toBe(400) expect(res.status).toBe(400)
expect(res.headers.get('cache-control')).toBe( expect(res.headers.get('cache-control')).toBe(
'private, no-cache, no-store, max-age=0, must-revalidate' 'private, no-cache, no-store, max-age=0, must-revalidate'
) )
expect(await res.text()).toBe('Bad Request') expect(await res.text()).toBe('Bad Request')
// Invalid client input is not a server error.
expect(next.cliOutput.slice(outputIndex)).not.toContain(
'The router state header was sent but could not be parsed'
)
}) })
it('should accept a valid router state tree', async () => { it('should accept a valid router state tree', async () => {
const res = await fetchWithRouterState( const res = await fetchWithRouterState(
next, next,
pathname, pathname,
createStateTree(prefixSegments, 'foo', { legacy: false }) createStateTree(prefixSegments, 'foo')
) )
expect(res.status).toBe(200) expect(res.status).toBe(200)
}) })
...@@ -150,7 +153,7 @@ describe('app dir - validation', () => { ...@@ -150,7 +153,7 @@ describe('app dir - validation', () => {
const res = await fetchWithRouterState( const res = await fetchWithRouterState(
next, next,
'/foo', '/foo',
createStateTree([], 'foo', { legacy: true }), createLegacyStateTree([], 'foo'),
{ rsc: false } { rsc: false }
) )
expect(res.status).toBe(200) expect(res.status).toBe(200)
......
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