Unverified Commit baf0b241 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

fix: rsc normalization fixes (#58145)

Co-authored-by: 's avatarZack Tanner <1939140+ztanner@users.noreply.github.com>
parent fe99b53d
...@@ -405,10 +405,10 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -405,10 +405,10 @@ export default abstract class Server<ServerOptions extends Options = Options> {
protected readonly localeNormalizer?: LocaleRouteNormalizer protected readonly localeNormalizer?: LocaleRouteNormalizer
protected readonly normalizers: { protected readonly normalizers: {
readonly postponed: PostponedPathnameNormalizer readonly postponed: PostponedPathnameNormalizer | undefined
readonly rsc: RSCPathnameNormalizer readonly rsc: RSCPathnameNormalizer | undefined
readonly prefetchRSC: PrefetchRSCPathnameNormalizer readonly prefetchRSC: PrefetchRSCPathnameNormalizer | undefined
readonly data: NextDataPathnameNormalizer readonly data: NextDataPathnameNormalizer | undefined
} }
public constructor(options: ServerOptions) { public constructor(options: ServerOptions) {
...@@ -475,14 +475,28 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -475,14 +475,28 @@ export default abstract class Server<ServerOptions extends Options = Options> {
this.enabledDirectories = this.getEnabledDirectories(dev) this.enabledDirectories = this.getEnabledDirectories(dev)
this.normalizers = { this.normalizers = {
postponed: new PostponedPathnameNormalizer( // We should normalize the pathname from the RSC prefix only in minimal
this.enabledDirectories.app && this.nextConfig.experimental.ppr // mode as otherwise that route is not exposed external to the server as
), // we instead only rely on the headers.
rsc: new RSCPathnameNormalizer(this.enabledDirectories.app), postponed:
prefetchRSC: new PrefetchRSCPathnameNormalizer( this.enabledDirectories.app &&
this.enabledDirectories.app this.nextConfig.experimental.ppr &&
), this.minimalMode
data: new NextDataPathnameNormalizer(this.buildId), ? new PostponedPathnameNormalizer()
: undefined,
rsc:
this.enabledDirectories.app && this.minimalMode
? new RSCPathnameNormalizer()
: undefined,
prefetchRSC:
this.enabledDirectories.app &&
this.nextConfig.experimental.ppr &&
this.minimalMode
? new PrefetchRSCPathnameNormalizer()
: undefined,
data: this.enabledDirectories.pages
? new NextDataPathnameNormalizer(this.buildId)
: undefined,
} }
this.nextFontManifest = this.getNextFontManifest() this.nextFontManifest = this.getNextFontManifest()
...@@ -567,7 +581,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -567,7 +581,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
private handleRSCRequest: RouteHandler = (req, _res, parsedUrl) => { private handleRSCRequest: RouteHandler = (req, _res, parsedUrl) => {
if (!parsedUrl.pathname) return false if (!parsedUrl.pathname) return false
if (this.normalizers.prefetchRSC.match(parsedUrl.pathname)) { if (this.normalizers.prefetchRSC?.match(parsedUrl.pathname)) {
parsedUrl.pathname = this.normalizers.prefetchRSC.normalize( parsedUrl.pathname = this.normalizers.prefetchRSC.normalize(
parsedUrl.pathname, parsedUrl.pathname,
true true
...@@ -578,7 +592,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -578,7 +592,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
req.headers[NEXT_ROUTER_PREFETCH_HEADER.toLowerCase()] = '1' req.headers[NEXT_ROUTER_PREFETCH_HEADER.toLowerCase()] = '1'
addRequestMeta(req, 'isRSCRequest', true) addRequestMeta(req, 'isRSCRequest', true)
addRequestMeta(req, 'isPrefetchRSCRequest', true) addRequestMeta(req, 'isPrefetchRSCRequest', true)
} else if (this.normalizers.rsc.match(parsedUrl.pathname)) { } else if (this.normalizers.rsc?.match(parsedUrl.pathname)) {
parsedUrl.pathname = this.normalizers.rsc.normalize( parsedUrl.pathname = this.normalizers.rsc.normalize(
parsedUrl.pathname, parsedUrl.pathname,
true true
...@@ -958,32 +972,18 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -958,32 +972,18 @@ export default abstract class Server<ServerOptions extends Options = Options> {
'http://localhost' 'http://localhost'
) )
if (this.normalizers.rsc.match(matchedPath)) {
matchedPath = this.normalizers.rsc.normalize(matchedPath, true)
} else if (this.normalizers.postponed.match(matchedPath)) {
matchedPath = this.normalizers.postponed.normalize(
matchedPath,
true
)
}
const { pathname: urlPathname } = new URL(req.url, 'http://localhost') const { pathname: urlPathname } = new URL(req.url, 'http://localhost')
// For ISR the URL is normalized to the prerenderPath so if // For ISR the URL is normalized to the prerenderPath so if
// it's a data request the URL path will be the data URL, // it's a data request the URL path will be the data URL,
// basePath is already stripped by this point // basePath is already stripped by this point
if ( if (this.normalizers.data?.match(urlPathname)) {
this.enabledDirectories.pages &&
this.normalizers.data.match(urlPathname)
) {
parsedUrl.query.__nextDataReq = '1' parsedUrl.query.__nextDataReq = '1'
} }
// In minimal mode, if PPR is enabled, then we should check to see if // In minimal mode, if PPR is enabled, then we should check to see if
// the matched path is a postponed path, and if it is, handle it. // the matched path is a postponed path, and if it is, handle it.
else if ( else if (
this.minimalMode && this.normalizers.postponed?.match(matchedPath) &&
this.renderOpts.experimental.ppr &&
this.normalizers.postponed.match(matchedPath) &&
req.method === 'POST' req.method === 'POST'
) { ) {
// Decode the postponed state from the request body, it will come as // Decode the postponed state from the request body, it will come as
...@@ -998,7 +998,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -998,7 +998,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
addRequestMeta(req, 'postponed', postponed) addRequestMeta(req, 'postponed', postponed)
} }
matchedPath = this.stripNextDataPath(matchedPath, false) matchedPath = this.normalize(matchedPath)
const normalizedUrlPath = this.stripNextDataPath(urlPathname) const normalizedUrlPath = this.stripNextDataPath(urlPathname)
// Perform locale detection and normalization. // Perform locale detection and normalization.
...@@ -1422,18 +1422,21 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1422,18 +1422,21 @@ export default abstract class Server<ServerOptions extends Options = Options> {
private normalize = (pathname: string) => { private normalize = (pathname: string) => {
const normalizers: Array<PathnameNormalizer> = [] const normalizers: Array<PathnameNormalizer> = []
if (this.enabledDirectories.pages) { if (this.normalizers.data) {
normalizers.push(this.normalizers.data) normalizers.push(this.normalizers.data)
} }
if (this.minimalMode && this.enabledDirectories.app) { if (this.normalizers.postponed) {
if (this.renderOpts.experimental.ppr) { normalizers.push(this.normalizers.postponed)
normalizers.push(this.normalizers.postponed) }
// We have to put the prefetch normalizer before the RSC normalizer
// because the RSC normalizer will match the prefetch RSC routes too. // We have to put the prefetch normalizer before the RSC normalizer
normalizers.push(this.normalizers.prefetchRSC) // because the RSC normalizer will match the prefetch RSC routes too.
} if (this.normalizers.prefetchRSC) {
normalizers.push(this.normalizers.prefetchRSC)
}
if (this.normalizers.rsc) {
normalizers.push(this.normalizers.rsc) normalizers.push(this.normalizers.rsc)
} }
......
import { BasePathPathnameNormalizer } from './base-path' import { BasePathPathnameNormalizer } from './base-path'
describe('BasePathPathnameNormalizer', () => { describe('BasePathPathnameNormalizer', () => {
describe('match', () => { it('should throw when provided with a blank basePath', () => {
it('should return false if there is no basePath', () => { expect(() => new BasePathPathnameNormalizer('')).toThrow()
let normalizer = new BasePathPathnameNormalizer('')
expect(normalizer.match('/')).toBe(false)
normalizer = new BasePathPathnameNormalizer('/')
expect(normalizer.match('/')).toBe(false)
})
it('should return false if the pathname does not start with the basePath', () => {
const normalizer = new BasePathPathnameNormalizer('/foo')
const pathnames = ['/bar', '/bar/foo', '/fooo/bar']
for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(false)
}
})
it('should return true if the pathname starts with the basePath', () => {
const normalizer = new BasePathPathnameNormalizer('/foo')
const pathnames = ['/foo', '/foo/bar', '/foo/bar/baz']
for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(true)
}
})
}) })
describe('normalize', () => { it('should throw when provided with a basePath of "/"', () => {
it('should return the same pathname if there is no basePath', () => { expect(() => new BasePathPathnameNormalizer('/')).toThrow()
let normalizer = new BasePathPathnameNormalizer('')
expect(normalizer.normalize('/foo')).toBe('/foo')
normalizer = new BasePathPathnameNormalizer('/')
expect(normalizer.normalize('/foo')).toBe('/foo')
})
it('should return the same pathname if we are not matched and the pathname does not start with the basePath', () => {
const normalizer = new BasePathPathnameNormalizer('/foo')
let pathnames = ['/bar', '/bar/foo', '/fooo/bar']
for (const pathname of pathnames) {
expect(normalizer.normalize(pathname)).toBe(pathname)
}
})
it('should strip the basePath from the pathname when it matches', () => {
const normalizer = new BasePathPathnameNormalizer('/foo')
const pathnames = ['/foo', '/foo/bar', '/foo/bar/baz']
for (const pathname of pathnames) {
expect(normalizer.normalize(pathname)).toBe(pathname.substring(4))
}
})
}) })
}) })
import type { PathnameNormalizer } from './pathname-normalizer' import type { PathnameNormalizer } from './pathname-normalizer'
export class BasePathPathnameNormalizer implements PathnameNormalizer { import { PrefixPathnameNormalizer } from './prefix'
private readonly basePath?: string
constructor(basePath: string) {
// A basePath of `/` is not a basePath.
if (!basePath || basePath === '/') return
this.basePath = basePath
}
public match(pathname: string) {
// If there's no basePath, we don't match.
if (!this.basePath) return false
// If the pathname doesn't start with the basePath, we don't match.
if (pathname !== this.basePath && !pathname.startsWith(this.basePath + '/'))
return false
return true export class BasePathPathnameNormalizer
} extends PrefixPathnameNormalizer
implements PathnameNormalizer
public normalize(pathname: string, matched?: boolean): string { {
// If there's no basePath, we don't need to normalize. constructor(basePath: string) {
if (!this.basePath) return pathname if (!basePath || basePath === '/') {
throw new Error('Invariant: basePath must be set and cannot be "/"')
// If we're not matched and we don't match, we don't need to normalize. }
if (!matched && !this.match(pathname)) return pathname
return pathname.substring(this.basePath.length) super(basePath)
} }
} }
import type { PathnameNormalizer } from './pathname-normalizer' import type { PathnameNormalizer } from './pathname-normalizer'
import { denormalizePagePath } from '../../../../shared/lib/page-path/denormalize-page-path'
import { PrefixPathnameNormalizer } from './prefix'
import { SuffixPathnameNormalizer } from './suffix'
export class NextDataPathnameNormalizer implements PathnameNormalizer { export class NextDataPathnameNormalizer implements PathnameNormalizer {
private readonly prefix: string private readonly prefix: PrefixPathnameNormalizer
private readonly suffix = new SuffixPathnameNormalizer('.json')
constructor(buildID: string) { constructor(buildID: string) {
if (!buildID) { if (!buildID) {
throw new Error('Invariant: buildID is required') throw new Error('Invariant: buildID is required')
} }
this.prefix = `/_next/data/${buildID}` this.prefix = new PrefixPathnameNormalizer(`/_next/data/${buildID}`)
} }
public match(pathname: string) { public match(pathname: string) {
// If the pathname doesn't start with the prefix, we don't match. return this.prefix.match(pathname) && this.suffix.match(pathname)
if (!pathname.startsWith(`${this.prefix}/`)) return false
// If the pathname ends with `.json`, we don't match.
if (!pathname.endsWith('.json')) return false
return true
} }
public normalize(pathname: string, matched?: boolean): string { public normalize(pathname: string, matched?: boolean): string {
// If we're not matched and we don't match, we don't need to normalize. // If we're not matched and we don't match, we don't need to normalize.
if (!matched && !this.match(pathname)) return pathname if (!matched && !this.match(pathname)) return pathname
// Remove the prefix and the `.json` extension. pathname = this.prefix.normalize(pathname, true)
pathname = pathname.substring( pathname = this.suffix.normalize(pathname, true)
this.prefix.length,
pathname.length - '.json'.length
)
// If the pathname is `/index`, we normalize it to `/`.
if (pathname === '/index') {
return '/'
}
return pathname return denormalizePagePath(pathname)
} }
} }
...@@ -2,25 +2,13 @@ import { PostponedPathnameNormalizer } from './postponed' ...@@ -2,25 +2,13 @@ import { PostponedPathnameNormalizer } from './postponed'
describe('PostponedPathnameNormalizer', () => { describe('PostponedPathnameNormalizer', () => {
describe('match', () => { describe('match', () => {
it('should not match if it is disabled', () => { it('should match', () => {
const pathnames = [ const pathnames = [
'/_next/postponed/resume/foo', '/_next/postponed/resume/foo',
'/_next/postponed/resume/bar', '/_next/postponed/resume/bar',
'/_next/postponed/resume/baz', '/_next/postponed/resume/baz',
] ]
const normalizer = new PostponedPathnameNormalizer(false) const normalizer = new PostponedPathnameNormalizer()
for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(false)
}
})
it('should match if it is enabled', () => {
const pathnames = [
'/_next/postponed/resume/foo',
'/_next/postponed/resume/bar',
'/_next/postponed/resume/baz',
]
const normalizer = new PostponedPathnameNormalizer(true)
for (const pathname of pathnames) { for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(true) expect(normalizer.match(pathname)).toBe(true)
} }
...@@ -28,7 +16,7 @@ describe('PostponedPathnameNormalizer', () => { ...@@ -28,7 +16,7 @@ describe('PostponedPathnameNormalizer', () => {
it('should not match for other pathnames', () => { it('should not match for other pathnames', () => {
const pathnames = ['/_next/foo', '/_next/bar', '/_next/baz'] const pathnames = ['/_next/foo', '/_next/bar', '/_next/baz']
const normalizer = new PostponedPathnameNormalizer(true) const normalizer = new PostponedPathnameNormalizer()
for (const pathname of pathnames) { for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(false) expect(normalizer.match(pathname)).toBe(false)
} }
...@@ -36,29 +24,17 @@ describe('PostponedPathnameNormalizer', () => { ...@@ -36,29 +24,17 @@ describe('PostponedPathnameNormalizer', () => {
}) })
describe('normalize', () => { describe('normalize', () => {
it('should not normalize if it is disabled', () => { it('should not normalize but not matched', () => {
const pathnames = [
'/_next/postponed/resume/foo',
'/_next/postponed/resume/bar',
'/_next/postponed/resume/baz',
]
const normalizer = new PostponedPathnameNormalizer(false)
for (const pathname of pathnames) {
expect(normalizer.normalize(pathname)).toBe(pathname)
}
})
it('should not normalize if it is enabled but not matched', () => {
const pathnames = ['/_next/foo', '/_next/bar', '/_next/baz'] const pathnames = ['/_next/foo', '/_next/bar', '/_next/baz']
const normalizer = new PostponedPathnameNormalizer(true) const normalizer = new PostponedPathnameNormalizer()
for (const pathname of pathnames) { for (const pathname of pathnames) {
expect(normalizer.normalize(pathname)).toBe(pathname) expect(normalizer.normalize(pathname)).toBe(pathname)
} }
}) })
it('should normalize if it is enabled and matched', () => { it('should normalize when matched', () => {
const pathnames = ['/foo', '/bar', '/baz'] const pathnames = ['/foo', '/bar', '/baz']
const normalizer = new PostponedPathnameNormalizer(true) const normalizer = new PostponedPathnameNormalizer()
for (const pathname of pathnames) { for (const pathname of pathnames) {
expect( expect(
normalizer.normalize(`/_next/postponed/resume${pathname}`, true) normalizer.normalize(`/_next/postponed/resume${pathname}`, true)
...@@ -67,7 +43,7 @@ describe('PostponedPathnameNormalizer', () => { ...@@ -67,7 +43,7 @@ describe('PostponedPathnameNormalizer', () => {
}) })
it('should normalize `/index` to `/`', () => { it('should normalize `/index` to `/`', () => {
const normalizer = new PostponedPathnameNormalizer(true) const normalizer = new PostponedPathnameNormalizer()
expect(normalizer.normalize('/_next/postponed/resume/index', true)).toBe( expect(normalizer.normalize('/_next/postponed/resume/index', true)).toBe(
'/' '/'
) )
......
import { denormalizePagePath } from '../../../../shared/lib/page-path/denormalize-page-path'
import type { PathnameNormalizer } from './pathname-normalizer' import type { PathnameNormalizer } from './pathname-normalizer'
const prefix = '/_next/postponed/resume' import { PrefixPathnameNormalizer } from './prefix'
export class PostponedPathnameNormalizer implements PathnameNormalizer {
constructor(private readonly ppr: boolean | undefined) {}
public match(pathname: string) {
// If PPR isn't enabled, we don't match.
if (!this.ppr) return false
// If the pathname doesn't start with the prefix, we don't match. const prefix = '/_next/postponed/resume'
if (!pathname.startsWith(prefix)) return false
return true export class PostponedPathnameNormalizer
extends PrefixPathnameNormalizer
implements PathnameNormalizer
{
constructor() {
super(prefix)
} }
public normalize(pathname: string, matched?: boolean): string { public normalize(pathname: string, matched?: boolean): string {
// If PPR isn't enabled, we don't need to normalize.
if (!this.ppr) return pathname
// If we're not matched and we don't match, we don't need to normalize. // If we're not matched and we don't match, we don't need to normalize.
if (!matched && !this.match(pathname)) return pathname if (!matched && !this.match(pathname)) return pathname
// Remove the prefix. // Remove the prefix.
pathname = pathname.substring(prefix.length) || '/' pathname = super.normalize(pathname, true)
// If the pathname is equal to `/index`, we normalize it to `/`.
if (pathname === '/index') return '/'
return pathname return denormalizePagePath(pathname)
} }
} }
import { PrefetchRSCPathnameNormalizer } from './prefetch-rsc'
describe('PrefetchRSCPathnameNormalizer', () => {
describe('match', () => {
it('should return false if the pathname does not end with `.prefetch.rsc`', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(true)
const pathnames = ['/foo', '/foo/bar', '/fooo/bar']
for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(false)
}
})
it('should return true if it matches', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(true)
const pathnames = [
'/foo.prefetch.rsc',
'/foo/bar.prefetch.rsc',
'/fooo/bar.prefetch.rsc',
]
for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(true)
}
})
it('should return false if it is disabled but ends with .prefetch.rsc', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(false)
const pathnames = [
'/foo.prefetch.rsc',
'/foo/bar.prefetch.rsc',
'/fooo/bar.prefetch.rsc',
]
for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(false)
}
})
it('should return false if it only ends in .rsc', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(false)
const pathnames = ['/foo.rsc', '/foo/bar.rsc', '/fooo/bar.rsc']
for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(false)
}
})
})
describe('normalize', () => {
it('should return the same pathname if we are not matched and the pathname does not end with `.prefetch.rsc`', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(true)
const pathnames = ['/foo', '/foo/bar', '/fooo/bar']
for (const pathname of pathnames) {
expect(normalizer.normalize(pathname)).toBe(pathname)
}
})
it('should strip the `.prefetch.rsc` extension from the pathname when it matches', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(true)
const pathnames = [
'/foo.prefetch.rsc',
'/foo/bar.prefetch.rsc',
'/fooo/bar.prefetch.rsc',
]
const expected = ['/foo', '/foo/bar', '/fooo/bar']
for (const pathname of pathnames) {
expect(normalizer.normalize(pathname)).toBe(
expected[pathnames.indexOf(pathname)]
)
}
})
it('should return the same pathname if it is disabled but ends with .prefetch.rsc', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(false)
const pathnames = [
'/foo.prefetch.rsc',
'/foo/bar.prefetch.rsc',
'/fooo/bar.prefetch.rsc',
]
for (const pathname of pathnames) {
expect(normalizer.normalize(pathname)).toBe(pathname)
}
})
})
})
...@@ -3,22 +3,11 @@ import type { PathnameNormalizer } from './pathname-normalizer' ...@@ -3,22 +3,11 @@ import type { PathnameNormalizer } from './pathname-normalizer'
import { RSC_PREFETCH_SUFFIX } from '../../../../lib/constants' import { RSC_PREFETCH_SUFFIX } from '../../../../lib/constants'
import { SuffixPathnameNormalizer } from './suffix' import { SuffixPathnameNormalizer } from './suffix'
export class PrefetchRSCPathnameNormalizer implements PathnameNormalizer { export class PrefetchRSCPathnameNormalizer
private readonly suffix = new SuffixPathnameNormalizer(RSC_PREFETCH_SUFFIX) extends SuffixPathnameNormalizer
implements PathnameNormalizer
constructor(private readonly hasAppDir: boolean) {} {
constructor() {
public match(pathname: string) { super(RSC_PREFETCH_SUFFIX)
// If there's no app directory, we don't match.
if (!this.hasAppDir) return false
return this.suffix.match(pathname)
}
public normalize(pathname: string, matched?: boolean): string {
// If there's no app directory, we don't need to normalize.
if (!this.hasAppDir) return pathname
return this.suffix.normalize(pathname, matched)
} }
} }
import { PrefixPathnameNormalizer } from './prefix'
describe('PrefixPathnameNormalizer', () => {
describe('match', () => {
it('should return false if the pathname does not start with the prefix', () => {
const normalizer = new PrefixPathnameNormalizer('/foo')
const pathnames = ['/bar', '/bar/foo', '/fooo/bar']
for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(false)
}
})
it('should return true if the pathname starts with the prefix', () => {
const normalizer = new PrefixPathnameNormalizer('/foo')
const pathnames = ['/foo', '/foo/bar', '/foo/bar/baz']
for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(true)
}
})
})
it('should throw if the prefix ends with a slash', () => {
expect(() => new PrefixPathnameNormalizer('/foo/')).toThrow()
expect(() => new PrefixPathnameNormalizer('/')).toThrow()
})
describe('normalize', () => {
it('should return the same pathname if we are not matched and the pathname does not start with the prefix', () => {
const normalizer = new PrefixPathnameNormalizer('/foo')
let pathnames = ['/bar', '/bar/foo', '/fooo/bar']
for (const pathname of pathnames) {
expect(normalizer.normalize(pathname)).toBe(pathname)
}
})
it('should strip the prefix from the pathname when it matches', () => {
const normalizer = new PrefixPathnameNormalizer('/foo')
const pathnames = ['/foo', '/foo/bar', '/foo/bar/baz']
for (const pathname of pathnames) {
expect(normalizer.normalize(pathname)).toBe(
pathname.substring(4) || '/'
)
}
})
})
})
import type { Normalizer } from '../normalizer'
export class PrefixPathnameNormalizer implements Normalizer {
constructor(private readonly prefix: string) {
if (prefix.endsWith('/')) {
throw new Error(
`PrefixPathnameNormalizer: prefix "${prefix}" should not end with a slash`
)
}
}
public match(pathname: string) {
// If the pathname doesn't start with the prefix, we don't match.
if (pathname !== this.prefix && !pathname.startsWith(this.prefix + '/')) {
return false
}
return true
}
public normalize(pathname: string, matched?: boolean): string {
// If we're not matched and we don't match, we don't need to normalize.
if (!matched && !this.match(pathname)) return pathname
if (pathname.length === this.prefix.length) {
return '/'
}
return pathname.substring(this.prefix.length)
}
}
...@@ -3,22 +3,11 @@ import type { PathnameNormalizer } from './pathname-normalizer' ...@@ -3,22 +3,11 @@ import type { PathnameNormalizer } from './pathname-normalizer'
import { RSC_SUFFIX } from '../../../../lib/constants' import { RSC_SUFFIX } from '../../../../lib/constants'
import { SuffixPathnameNormalizer } from './suffix' import { SuffixPathnameNormalizer } from './suffix'
export class RSCPathnameNormalizer implements PathnameNormalizer { export class RSCPathnameNormalizer
private readonly suffix = new SuffixPathnameNormalizer(RSC_SUFFIX) extends SuffixPathnameNormalizer
implements PathnameNormalizer
constructor(private readonly hasAppDir: boolean) {} {
constructor() {
public match(pathname: string) { super(RSC_SUFFIX)
// If there's no app directory, we don't match.
if (!this.hasAppDir) return false
return this.suffix.match(pathname)
}
public normalize(pathname: string, matched?: boolean): string {
// If there's no app directory, we don't need to normalize.
if (!this.hasAppDir) return pathname
return this.suffix.normalize(pathname, matched)
} }
} }
import { RSCPathnameNormalizer } from './rsc' import { SuffixPathnameNormalizer } from './suffix'
describe('RSCPathnameNormalizer', () => { describe('SuffixPathnameNormalizer', () => {
describe('match', () => { describe('match', () => {
it('should return false if the pathname does not end with `.rsc`', () => { it('should return false if the pathname does not end with `.rsc`', () => {
const normalizer = new RSCPathnameNormalizer(true) const normalizer = new SuffixPathnameNormalizer('.rsc')
const pathnames = ['/foo', '/foo/bar', '/fooo/bar'] const pathnames = ['/foo', '/foo/bar', '/fooo/bar']
for (const pathname of pathnames) { for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(false) expect(normalizer.match(pathname)).toBe(false)
...@@ -11,25 +11,17 @@ describe('RSCPathnameNormalizer', () => { ...@@ -11,25 +11,17 @@ describe('RSCPathnameNormalizer', () => {
}) })
it('should return true if it matches', () => { it('should return true if it matches', () => {
const normalizer = new RSCPathnameNormalizer(true) const normalizer = new SuffixPathnameNormalizer('.rsc')
const pathnames = ['/foo.rsc', '/foo/bar.rsc', '/fooo/bar.rsc'] const pathnames = ['/foo.rsc', '/foo/bar.rsc', '/fooo/bar.rsc']
for (const pathname of pathnames) { for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(true) expect(normalizer.match(pathname)).toBe(true)
} }
}) })
it('should return false if it is disabled but ends with .rsc', () => {
const normalizer = new RSCPathnameNormalizer(false)
const pathnames = ['/foo.rsc', '/foo/bar.rsc', '/fooo/bar.rsc']
for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(false)
}
})
}) })
describe('normalize', () => { describe('normalize', () => {
it('should return the same pathname if we are not matched and the pathname does not end with `.rsc`', () => { it('should return the same pathname if we are not matched and the pathname does not end with `.rsc`', () => {
const normalizer = new RSCPathnameNormalizer(true) const normalizer = new SuffixPathnameNormalizer('.rsc')
const pathnames = ['/foo', '/foo/bar', '/fooo/bar'] const pathnames = ['/foo', '/foo/bar', '/fooo/bar']
for (const pathname of pathnames) { for (const pathname of pathnames) {
expect(normalizer.normalize(pathname)).toBe(pathname) expect(normalizer.normalize(pathname)).toBe(pathname)
...@@ -37,7 +29,7 @@ describe('RSCPathnameNormalizer', () => { ...@@ -37,7 +29,7 @@ describe('RSCPathnameNormalizer', () => {
}) })
it('should strip the `.rsc` extension from the pathname when it matches', () => { it('should strip the `.rsc` extension from the pathname when it matches', () => {
const normalizer = new RSCPathnameNormalizer(true) const normalizer = new SuffixPathnameNormalizer('.rsc')
const pathnames = ['/foo.rsc', '/foo/bar.rsc', '/fooo/bar.rsc'] const pathnames = ['/foo.rsc', '/foo/bar.rsc', '/fooo/bar.rsc']
const expected = ['/foo', '/foo/bar', '/fooo/bar'] const expected = ['/foo', '/foo/bar', '/fooo/bar']
for (const pathname of pathnames) { for (const pathname of pathnames) {
...@@ -46,13 +38,5 @@ describe('RSCPathnameNormalizer', () => { ...@@ -46,13 +38,5 @@ describe('RSCPathnameNormalizer', () => {
) )
} }
}) })
it('should return the same pathname if it is disabled but ends with .rsc', () => {
const normalizer = new RSCPathnameNormalizer(false)
const pathnames = ['/foo.rsc', '/foo/bar.rsc', '/fooo/bar.rsc']
for (const pathname of pathnames) {
expect(normalizer.normalize(pathname)).toBe(pathname)
}
})
}) })
}) })
...@@ -371,9 +371,13 @@ export async function setupFsCheck(opts: { ...@@ -371,9 +371,13 @@ export async function setupFsCheck(opts: {
const normalizers = { const normalizers = {
// Because we can't know if the app directory is enabled or not at this // Because we can't know if the app directory is enabled or not at this
// stage, we assume that it is. // stage, we assume that it is.
rsc: new RSCPathnameNormalizer(true), rsc: new RSCPathnameNormalizer(),
prefetchRSC: new PrefetchRSCPathnameNormalizer(true), prefetchRSC: opts.config.experimental.ppr
postponed: new PostponedPathnameNormalizer(opts.config.experimental.ppr), ? new PrefetchRSCPathnameNormalizer()
: undefined,
postponed: opts.config.experimental.ppr
? new PostponedPathnameNormalizer()
: undefined,
} }
return { return {
...@@ -421,11 +425,11 @@ export async function setupFsCheck(opts: { ...@@ -421,11 +425,11 @@ export async function setupFsCheck(opts: {
// Simulate minimal mode requests by normalizing RSC and postponed // Simulate minimal mode requests by normalizing RSC and postponed
// requests. // requests.
if (opts.minimalMode) { if (opts.minimalMode) {
if (normalizers.prefetchRSC.match(itemPath)) { if (normalizers.prefetchRSC?.match(itemPath)) {
itemPath = normalizers.prefetchRSC.normalize(itemPath, true) itemPath = normalizers.prefetchRSC.normalize(itemPath, true)
} else if (normalizers.rsc.match(itemPath)) { } else if (normalizers.rsc.match(itemPath)) {
itemPath = normalizers.rsc.normalize(itemPath, true) itemPath = normalizers.rsc.normalize(itemPath, true)
} else if (normalizers.postponed.match(itemPath)) { } else if (normalizers.postponed?.match(itemPath)) {
itemPath = normalizers.postponed.normalize(itemPath, true) itemPath = normalizers.postponed.normalize(itemPath, true)
} }
} }
......
...@@ -294,11 +294,14 @@ export function getResolveRoutes( ...@@ -294,11 +294,14 @@ export function getResolveRoutes(
} }
const normalizers = { const normalizers = {
basePath: new BasePathPathnameNormalizer(config.basePath), basePath:
config.basePath && config.basePath !== '/'
? new BasePathPathnameNormalizer(config.basePath)
: undefined,
data: new NextDataPathnameNormalizer(fsChecker.buildId), data: new NextDataPathnameNormalizer(fsChecker.buildId),
postponed: new PostponedPathnameNormalizer( postponed: config.experimental.ppr
config.experimental.ppr === true ? new PostponedPathnameNormalizer()
), : undefined,
} }
async function handleRoute( async function handleRoute(
...@@ -371,8 +374,8 @@ export function getResolveRoutes( ...@@ -371,8 +374,8 @@ export function getResolveRoutes(
let normalized = parsedUrl.pathname let normalized = parsedUrl.pathname
// Remove the base path if it exists. // Remove the base path if it exists.
const hadBasePath = normalizers.basePath.match(parsedUrl.pathname) const hadBasePath = normalizers.basePath?.match(parsedUrl.pathname)
if (hadBasePath) { if (hadBasePath && normalizers.basePath) {
normalized = normalizers.basePath.normalize(normalized, true) normalized = normalizers.basePath.normalize(normalized, true)
} }
...@@ -381,7 +384,7 @@ export function getResolveRoutes( ...@@ -381,7 +384,7 @@ export function getResolveRoutes(
updated = true updated = true
parsedUrl.query.__nextDataReq = '1' parsedUrl.query.__nextDataReq = '1'
normalized = normalizers.data.normalize(normalized, true) normalized = normalizers.data.normalize(normalized, true)
} else if (normalizers.postponed.match(normalized)) { } else if (normalizers.postponed?.match(normalized)) {
updated = true updated = true
normalized = normalizers.postponed.normalize(normalized, true) normalized = normalizers.postponed.normalize(normalized, true)
} }
......
import { headers } from 'next/headers'
export default async function Page({ params }) {
const data = headers()
return (
<>
<p id="page">/dyn/[slug]</p>
<p id="params">{JSON.stringify(params)}</p>
<p id="now">{Date.now()}</p>
<p id="data">{data}</p>
</>
)
}
import glob from 'glob'
import fs from 'fs-extra'
import { join } from 'path'
import cheerio from 'cheerio'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import {
fetchViaHTTP,
findPort,
initNextServerScript,
killApp,
} from 'next-test-utils'
describe('required server files app router', () => {
let next: NextInstance
let server
let appPort
const setupNext = async ({
nextEnv,
minimalMode,
}: {
nextEnv?: boolean
minimalMode?: boolean
}) => {
// test build against environment with next support
process.env.NOW_BUILDER = nextEnv ? '1' : ''
next = await createNext({
files: {
app: new FileRef(join(__dirname, 'app')),
lib: new FileRef(join(__dirname, 'lib')),
'cache-handler.js': new FileRef(join(__dirname, 'cache-handler.js')),
'middleware.js': new FileRef(join(__dirname, 'middleware.js')),
'data.txt': new FileRef(join(__dirname, 'data.txt')),
'.env': new FileRef(join(__dirname, '.env')),
'.env.local': new FileRef(join(__dirname, '.env.local')),
'.env.production': new FileRef(join(__dirname, '.env.production')),
},
nextConfig: {
experimental: {
incrementalCacheHandlerPath: './cache-handler.js',
ppr: true,
},
eslint: {
ignoreDuringBuilds: true,
},
output: 'standalone',
},
})
await next.stop()
await fs.move(
join(next.testDir, '.next/standalone'),
join(next.testDir, 'standalone')
)
for (const file of await fs.readdir(next.testDir)) {
if (file !== 'standalone') {
await fs.remove(join(next.testDir, file))
console.log('removed', file)
}
}
const files = glob.sync('**/*', {
cwd: join(next.testDir, 'standalone/.next/server/pages'),
dot: true,
})
for (const file of files) {
if (file.endsWith('.json') || file.endsWith('.html')) {
await fs.remove(join(next.testDir, '.next/server', file))
}
}
const testServer = join(next.testDir, 'standalone/server.js')
await fs.writeFile(
testServer,
(
await fs.readFile(testServer, 'utf8')
).replace('port:', `minimalMode: ${minimalMode},port:`)
)
appPort = await findPort()
server = await initNextServerScript(
testServer,
/- Local:/,
{
...process.env,
PORT: appPort,
},
undefined,
{
cwd: next.testDir,
}
)
appPort = `http://127.0.0.1:${appPort}`
}
beforeAll(async () => {
await setupNext({ nextEnv: true, minimalMode: true })
})
afterAll(async () => {
await next.destroy()
if (server) await killApp(server)
})
it('should not fail caching', async () => {
expect(next.cliOutput).not.toContain('ERR_INVALID_URL')
})
it('should properly handle prerender for bot request', async () => {
const res = await fetchViaHTTP(appPort, '/isr/first', undefined, {
headers: {
'user-agent':
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'x-matched-path': '/isr/first',
},
})
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('#page').text()).toBe('/isr/[slug]')
const rscRes = await fetchViaHTTP(appPort, '/isr/first.rsc', undefined, {
headers: {
'user-agent':
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'x-matched-path': '/isr/first',
},
})
expect(rscRes.status).toBe(200)
})
it('should properly handle fallback for bot request', async () => {
const res = await fetchViaHTTP(appPort, '/isr/[slug]', undefined, {
headers: {
'user-agent':
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'x-now-route-matches': '1=second&nxtPslug=new',
'x-matched-path': '/isr/[slug]',
},
})
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect($('#page').text()).toBe('/isr/[slug]')
const rscRes = await fetchViaHTTP(appPort, '/isr/[slug].rsc', undefined, {
headers: {
'user-agent':
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'x-now-route-matches': '1=second&nxtPslug=new',
'x-matched-path': '/isr/[slug]',
},
})
expect(rscRes.status).toBe(200)
})
it('should send cache tags in minimal mode for ISR', async () => {
for (const [path, tags] of [
[
'/isr/first',
'isr-page,_N_T_/layout,_N_T_/isr/layout,_N_T_/isr/[slug]/layout,_N_T_/isr/[slug]/page,_N_T_/isr/first',
],
[
'/isr/second',
'isr-page,_N_T_/layout,_N_T_/isr/layout,_N_T_/isr/[slug]/layout,_N_T_/isr/[slug]/page,_N_T_/isr/second',
],
[
'/api/isr/first',
'isr-page,_N_T_/layout,_N_T_/api/layout,_N_T_/api/isr/layout,_N_T_/api/isr/[slug]/layout,_N_T_/api/isr/[slug]/route,_N_T_/api/isr/first',
],
[
'/api/isr/second',
'isr-page,_N_T_/layout,_N_T_/api/layout,_N_T_/api/isr/layout,_N_T_/api/isr/[slug]/layout,_N_T_/api/isr/[slug]/route,_N_T_/api/isr/second',
],
]) {
require('console').error('checking', { path, tags })
const res = await fetchViaHTTP(appPort, path, undefined, {
redirect: 'manual',
})
expect(res.status).toBe(200)
expect(res.headers.get('x-next-cache-tags')).toBe(tags)
}
})
it('should not send cache tags in minimal mode for SSR', async () => {
for (const path of [
'/ssr/first',
'/ssr/second',
'/api/ssr/first',
'/api/ssr/second',
]) {
const res = await fetchViaHTTP(appPort, path, undefined, {
redirect: 'manual',
})
expect(res.status).toBe(200)
expect(res.headers.get('x-next-cache-tags')).toBeFalsy()
}
})
it('should not send invalid soft tags to cache handler', async () => {
for (const path of [
'/ssr/first',
'/ssr/second',
'/api/ssr/first',
'/api/ssr/second',
]) {
const res = await fetchViaHTTP(
appPort,
path,
{ hello: 'world' },
{
redirect: 'manual',
}
)
expect(res.status).toBe(200)
expect(res.headers.get('x-next-cache-tags')).toBeFalsy()
}
})
it('should handle RSC requests', async () => {
const res = await fetchViaHTTP(appPort, '/dyn/first.rsc', undefined, {
headers: {
'x-matched-path': '/dyn/first',
},
})
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toEqual('text/x-component')
expect(res.headers.has('x-nextjs-postponed')).toBeFalse()
})
it('should handle prefetch RSC requests', async () => {
const res = await fetchViaHTTP(
appPort,
'/dyn/first.prefetch.rsc',
undefined,
{
headers: {
'x-matched-path': '/dyn/first',
},
}
)
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toEqual('text/x-component')
expect(res.headers.has('x-nextjs-postponed')).toBeTrue()
})
})
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