Unverified Commit aefa6f15 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Turbopack Build: Fix underscore path tests (#79778)

## What?

Implements handling for `%5F` to `_` conversion to handle pathnames in
App Router that want to bypass the underscore ignore folder.

Implementing this was a bit of a hassle not on the Turbopack side but
there's an additional layer of route handling before the compiler that
turns the filesystem paths into routable routes. Turns out there was
some additional places where the normalization needs to apply.

For now implemented it so that it special cases Turbopack handling,
might change the webpack implementation in the future to output the
files into the same path that Turbopack outputs it at. This is only
relevant for dev, production is handled the same already.
parent 08ea8de2
......@@ -55,9 +55,7 @@
},
"env": {
// Enable the following environment variables to use turbopack instead of webpack:
// "TURBOPACK": "1",
// "TURBOPACK_DEV": "1",
// "TURBOPACK_BUILD": "1",
// "IS_TURBOPACK_TEST": "1",
"NEXT_PRIVATE_LOCAL_WEBPACK": "1",
"NEXT_PRIVATE_SKIP_CANARY_CHECK": "1",
"NEXT_TELEMETRY_DISABLED": "1"
......
......@@ -26,6 +26,12 @@ use crate::{
next_import_map::get_next_package,
};
// Next.js ignores underscores for routes but you can use %5f to still serve an underscored
// route.
fn normalize_underscore(string: &str) -> String {
string.replace("%5F", "_")
}
/// A final route in the app directory.
#[turbo_tasks::value]
#[derive(Default, Debug, Clone)]
......@@ -977,7 +983,7 @@ async fn directory_tree_to_loader_tree_internal(
// When constructing the app_page fails (e. g. due to limitations of the order),
// we only want to emit the error when there are actual pages below that
// directory.
if let Err(e) = child_app_page.push_str(subdir_name) {
if let Err(e) = child_app_page.push_str(&normalize_underscore(subdir_name)) {
illegal_path_error = Some(e);
}
......@@ -1394,7 +1400,7 @@ async fn directory_tree_to_entrypoints_internal_untraced(
// When constructing the app_page fails (e. g. due to limitations of the order),
// we only want to emit the error when there are actual pages below that
// directory.
if let Err(e) = child_app_page.push_str(subdir_name) {
if let Err(e) = child_app_page.push_str(&normalize_underscore(subdir_name)) {
illegal_path = Some(e);
}
......
......@@ -310,11 +310,23 @@ export default class DevServer extends Server {
})
)
// TODO: Improve passing of "is running with Turbopack"
const isTurbopack = !!process.env.TURBOPACK
matchers.push(
new DevAppPageRouteMatcherProvider(appDir, extensions, fileReader)
new DevAppPageRouteMatcherProvider(
appDir,
extensions,
fileReader,
isTurbopack
)
)
matchers.push(
new DevAppRouteRouteMatcherProvider(appDir, extensions, fileReader)
new DevAppRouteRouteMatcherProvider(
appDir,
extensions,
fileReader,
isTurbopack
)
)
}
......
......@@ -510,7 +510,12 @@ async function startWatcher(opts: SetupOpts) {
if (!appPaths[pageName]) {
appPaths[pageName] = []
}
appPaths[pageName].push(originalPageName)
appPaths[pageName].push(
opts.turbo
? // Turbopack outputs the correct path which is normalized with the `_`.
originalPageName.replace(/%5F/g, '_')
: originalPageName
)
if (useFileSystemPublicRoutes) {
appFiles.add(pageName)
......
......@@ -2,6 +2,7 @@ import { Normalizers } from '../../normalizers'
import type { Normalizer } from '../../normalizer'
import { PrefixingNormalizer } from '../../prefixing-normalizer'
import { normalizePagePath } from '../../../../shared/lib/page-path/normalize-page-path'
import { UnderscoreNormalizer } from '../../underscore-normalizer'
export class AppBundlePathNormalizer extends PrefixingNormalizer {
constructor() {
......@@ -14,13 +15,19 @@ export class AppBundlePathNormalizer extends PrefixingNormalizer {
}
export class DevAppBundlePathNormalizer extends Normalizers {
constructor(pageNormalizer: Normalizer) {
super([
constructor(pageNormalizer: Normalizer, isTurbopack: boolean) {
const normalizers = [
// This should normalize the filename to a page.
pageNormalizer,
// Normalize the app page to a pathname.
new AppBundlePathNormalizer(),
])
]
// %5F to _ replacement should only happen with Turbopack.
if (isTurbopack) {
normalizers.unshift(new UnderscoreNormalizer())
}
super(normalizers)
}
public normalize(filename: string): string {
......
import { PAGE_TYPES } from '../../../../lib/page-types'
import { AbsoluteFilenameNormalizer } from '../../absolute-filename-normalizer'
import { Normalizers } from '../../normalizers'
/**
* DevAppPageNormalizer is a normalizer that is used to normalize a pathname
* to a page in the `app` directory.
*/
export class DevAppPageNormalizer extends AbsoluteFilenameNormalizer {
class DevAppPageNormalizerInternal extends AbsoluteFilenameNormalizer {
constructor(appDir: string, extensions: ReadonlyArray<string>) {
super(appDir, extensions, PAGE_TYPES.APP)
}
}
export class DevAppPageNormalizer extends Normalizers {
constructor(
appDir: string,
extensions: ReadonlyArray<string>,
_isTurbopack: boolean
) {
const normalizer = new DevAppPageNormalizerInternal(appDir, extensions)
super(
// %5F to _ replacement should only happen with Turbopack.
// TODO: enable when page matcher `/_` check is moved: https://github.com/vercel/next.js/blob/8eda00bf5999e43e8f0211bd72c981d5ce292e8b/packages/next/src/server/route-matcher-providers/dev/dev-app-route-route-matcher-provider.ts#L48
// isTurbopack
// ? [
// // The page should have the `%5F` characters replaced with `_` characters.
// new UnderscoreNormalizer(),
// normalizer,
// ]
// : [normalizer]
[normalizer]
)
}
}
......@@ -26,9 +26,13 @@ export class DevAppNormalizers {
public readonly pathname: DevAppPathnameNormalizer
public readonly bundlePath: DevAppBundlePathNormalizer
constructor(appDir: string, extensions: ReadonlyArray<string>) {
this.page = new DevAppPageNormalizer(appDir, extensions)
constructor(
appDir: string,
extensions: ReadonlyArray<string>,
isTurbopack: boolean
) {
this.page = new DevAppPageNormalizer(appDir, extensions, isTurbopack)
this.pathname = new DevAppPathnameNormalizer(this.page)
this.bundlePath = new DevAppBundlePathNormalizer(this.page)
this.bundlePath = new DevAppBundlePathNormalizer(this.page, isTurbopack)
}
}
......@@ -3,87 +3,108 @@ import { RouteKind } from '../../route-kind'
import { DevAppPageRouteMatcherProvider } from './dev-app-page-route-matcher-provider'
import type { FileReader } from './helpers/file-reader/file-reader'
describe('DevAppPageRouteMatcher', () => {
const dir = '<root>'
const extensions = ['ts', 'tsx', 'js', 'jsx']
describe.each(['webpack', 'turbopack'])(
'DevAppPageRouteMatcher %s',
(bundler) => {
const isTurbopack = bundler === 'turbopack'
const dir = '<root>'
const extensions = ['ts', 'tsx', 'js', 'jsx']
it('returns no routes with an empty filesystem', async () => {
const reader: FileReader = { read: jest.fn(() => []) }
const provider = new DevAppPageRouteMatcherProvider(dir, extensions, reader)
const matchers = await provider.matchers()
expect(matchers).toHaveLength(0)
expect(reader.read).toHaveBeenCalledWith(dir)
})
it('returns no routes with an empty filesystem', async () => {
const reader: FileReader = { read: jest.fn(() => []) }
const provider = new DevAppPageRouteMatcherProvider(
dir,
extensions,
reader,
isTurbopack
)
const matchers = await provider.matchers()
expect(matchers).toHaveLength(0)
expect(reader.read).toHaveBeenCalledWith(dir)
})
describe('filename matching', () => {
it.each<{
files: ReadonlyArray<string>
route: AppPageRouteDefinition
}>([
{
files: [`${dir}/(marketing)/about/page.ts`],
route: {
kind: RouteKind.APP_PAGE,
pathname: '/about',
filename: `${dir}/(marketing)/about/page.ts`,
page: '/(marketing)/about/page',
bundlePath: 'app/(marketing)/about/page',
appPaths: ['/(marketing)/about/page'],
describe('filename matching', () => {
it.each<{
files: ReadonlyArray<string>
route: AppPageRouteDefinition
}>([
{
files: [`${dir}/(marketing)/about/page.ts`],
route: {
kind: RouteKind.APP_PAGE,
pathname: '/about',
filename: `${dir}/(marketing)/about/page.ts`,
page: '/(marketing)/about/page',
bundlePath: 'app/(marketing)/about/page',
appPaths: ['/(marketing)/about/page'],
},
},
},
{
files: [`${dir}/(marketing)/about/page.ts`],
route: {
kind: RouteKind.APP_PAGE,
pathname: '/about',
filename: `${dir}/(marketing)/about/page.ts`,
page: '/(marketing)/about/page',
bundlePath: 'app/(marketing)/about/page',
appPaths: ['/(marketing)/about/page'],
{
files: [`${dir}/(marketing)/about/page.ts`],
route: {
kind: RouteKind.APP_PAGE,
pathname: '/about',
filename: `${dir}/(marketing)/about/page.ts`,
page: '/(marketing)/about/page',
bundlePath: 'app/(marketing)/about/page',
appPaths: ['/(marketing)/about/page'],
},
},
},
{
files: [`${dir}/some/other/page.ts`],
route: {
kind: RouteKind.APP_PAGE,
pathname: '/some/other',
filename: `${dir}/some/other/page.ts`,
page: '/some/other/page',
bundlePath: 'app/some/other/page',
appPaths: ['/some/other/page'],
{
files: [`${dir}/some/other/page.ts`],
route: {
kind: RouteKind.APP_PAGE,
pathname: '/some/other',
filename: `${dir}/some/other/page.ts`,
page: '/some/other/page',
bundlePath: 'app/some/other/page',
appPaths: ['/some/other/page'],
},
},
},
{
files: [`${dir}/page.ts`],
route: {
kind: RouteKind.APP_PAGE,
pathname: '/',
filename: `${dir}/page.ts`,
page: '/page',
bundlePath: 'app/page',
appPaths: ['/page'],
{
files: [`${dir}/page.ts`],
route: {
kind: RouteKind.APP_PAGE,
pathname: '/',
filename: `${dir}/page.ts`,
page: '/page',
bundlePath: 'app/page',
appPaths: ['/page'],
},
},
},
])(
"matches the '$route.page' route specified with the provided files",
async ({ files, route }) => {
const reader: FileReader = {
read: jest.fn(() => [
...extensions.map((ext) => `${dir}/some/route.${ext}`),
...extensions.map((ext) => `${dir}/api/other.${ext}`),
...files,
]),
{
files: [`${dir}/%5Fnotignored/page.ts`],
route: {
kind: RouteKind.APP_PAGE,
pathname: '/_notignored',
filename: `${dir}/%5Fnotignored/page.ts`,
page: `/${isTurbopack ? '_' : '%5F'}notignored/page`,
bundlePath: `app/${isTurbopack ? '_' : '%5F'}notignored/page`,
appPaths: [`/${isTurbopack ? '_' : '%5F'}notignored/page`],
},
},
])(
"matches the '$route.page' route specified with the provided files",
async ({ files, route }) => {
const reader: FileReader = {
read: jest.fn(() => [
...extensions.map((ext) => `${dir}/some/route.${ext}`),
...extensions.map((ext) => `${dir}/api/other.${ext}`),
...files,
]),
}
const provider = new DevAppPageRouteMatcherProvider(
dir,
extensions,
reader,
isTurbopack
)
const matchers = await provider.matchers()
expect(matchers).toHaveLength(1)
expect(reader.read).toHaveBeenCalledWith(dir)
expect(matchers[0].definition).toEqual(route)
}
const provider = new DevAppPageRouteMatcherProvider(
dir,
extensions,
reader
)
const matchers = await provider.matchers()
expect(matchers).toHaveLength(1)
expect(reader.read).toHaveBeenCalledWith(dir)
expect(matchers[0].definition).toEqual(route)
}
)
})
})
)
})
}
)
......@@ -9,21 +9,24 @@ import { normalizeCatchAllRoutes } from '../../../build/normalize-catchall-route
export class DevAppPageRouteMatcherProvider extends FileCacheRouteMatcherProvider<AppPageRouteMatcher> {
private readonly expression: RegExp
private readonly normalizers: DevAppNormalizers
private readonly isTurbopack: boolean
constructor(
appDir: string,
extensions: ReadonlyArray<string>,
reader: FileReader
reader: FileReader,
isTurbopack: boolean
) {
super(appDir, reader)
this.normalizers = new DevAppNormalizers(appDir, extensions)
this.normalizers = new DevAppNormalizers(appDir, extensions, isTurbopack)
// Match any page file that ends with `/page.${extension}` or `/default.${extension}` under the app
// directory.
this.expression = new RegExp(
`[/\\\\](page|default)\\.(?:${extensions.join('|')})$`
)
this.isTurbopack = isTurbopack
}
protected async transform(
......@@ -41,11 +44,19 @@ export class DevAppPageRouteMatcherProvider extends FileCacheRouteMatcherProvide
// If the file isn't a match for this matcher, then skip it.
if (!this.expression.test(filename)) continue
const page = this.normalizers.page.normalize(filename)
let page = this.normalizers.page.normalize(filename)
// Validate that this is not an ignored page.
if (page.includes('/_')) continue
// Turbopack uses the correct page name with the underscore normalized.
// TODO: Move implementation to packages/next/src/server/normalizers/built/app/app-page-normalizer.ts.
// The `includes('/_')` check above needs to be moved for that to work as otherwise `%5Fsegmentname`
// will result in `_segmentname` which hits that includes check and be skipped.
if (this.isTurbopack) {
page = page.replace(/%5F/g, '_')
}
// This is a valid file that we want to create a matcher for.
routeFilenames.push(filename)
......
......@@ -3,63 +3,85 @@ import { RouteKind } from '../../route-kind'
import { DevAppRouteRouteMatcherProvider } from './dev-app-route-route-matcher-provider'
import type { FileReader } from './helpers/file-reader/file-reader'
describe('DevAppRouteRouteMatcher', () => {
const dir = '<root>'
const extensions = ['ts', 'tsx', 'js', 'jsx']
describe.each(['webpack', 'turbopack'])(
'DevAppRouteRouteMatcher %s',
(bundler) => {
const isTurbopack = bundler === 'turbopack'
const dir = '<root>'
const extensions = ['ts', 'tsx', 'js', 'jsx']
it('returns no routes with an empty filesystem', async () => {
const reader: FileReader = { read: jest.fn(() => []) }
const matcher = new DevAppRouteRouteMatcherProvider(dir, extensions, reader)
const matchers = await matcher.matchers()
expect(matchers).toHaveLength(0)
expect(reader.read).toHaveBeenCalledWith(dir)
})
it('returns no routes with an empty filesystem', async () => {
const reader: FileReader = { read: jest.fn(() => []) }
const matcher = new DevAppRouteRouteMatcherProvider(
dir,
extensions,
reader,
isTurbopack
)
const matchers = await matcher.matchers()
expect(matchers).toHaveLength(0)
expect(reader.read).toHaveBeenCalledWith(dir)
})
describe('filename matching', () => {
it.each<{
files: ReadonlyArray<string>
route: AppRouteRouteDefinition
}>([
{
files: [`${dir}/some/other/route.ts`],
route: {
kind: RouteKind.APP_ROUTE,
pathname: '/some/other',
filename: `${dir}/some/other/route.ts`,
page: '/some/other/route',
bundlePath: 'app/some/other/route',
describe('filename matching', () => {
it.each<{
files: ReadonlyArray<string>
route: AppRouteRouteDefinition
}>([
{
files: [`${dir}/some/other/route.ts`],
route: {
kind: RouteKind.APP_ROUTE,
pathname: '/some/other',
filename: `${dir}/some/other/route.ts`,
page: '/some/other/route',
bundlePath: 'app/some/other/route',
},
},
},
{
files: [`${dir}/route.ts`],
route: {
kind: RouteKind.APP_ROUTE,
pathname: '/',
filename: `${dir}/route.ts`,
page: '/route',
bundlePath: 'app/route',
{
files: [`${dir}/route.ts`],
route: {
kind: RouteKind.APP_ROUTE,
pathname: '/',
filename: `${dir}/route.ts`,
page: '/route',
bundlePath: 'app/route',
},
},
},
])(
"matches the '$route.page' route specified with the provided files",
async ({ files, route }) => {
const reader: FileReader = {
read: jest.fn(() => [
...extensions.map((ext) => `${dir}/some/page.${ext}`),
...extensions.map((ext) => `${dir}/api/other.${ext}`),
...files,
]),
{
files: [`${dir}/%5Fnotignored/route.ts`],
route: {
kind: RouteKind.APP_ROUTE,
pathname: '/_notignored',
filename: `${dir}/%5Fnotignored/route.ts`,
page: `/${isTurbopack ? '_' : '%5F'}notignored/route`,
bundlePath: `app/${isTurbopack ? '_' : '%5F'}notignored/route`,
},
},
])(
"matches the '$route.page' route specified with the provided files",
async ({ files, route }) => {
console.log({ files })
const reader: FileReader = {
read: jest.fn(() => [
...extensions.map((ext) => `${dir}/some/page.${ext}`),
...extensions.map((ext) => `${dir}/api/other.${ext}`),
...files,
]),
}
const matcher = new DevAppRouteRouteMatcherProvider(
dir,
extensions,
reader,
isTurbopack
)
const matchers = await matcher.matchers()
expect(matchers).toHaveLength(1)
expect(reader.read).toHaveBeenCalledWith(dir)
expect(matchers[0].definition).toEqual(route)
}
const matcher = new DevAppRouteRouteMatcherProvider(
dir,
extensions,
reader
)
const matchers = await matcher.matchers()
expect(matchers).toHaveLength(1)
expect(reader.read).toHaveBeenCalledWith(dir)
expect(matchers[0].definition).toEqual(route)
}
)
})
})
)
})
}
)
......@@ -19,16 +19,19 @@ export class DevAppRouteRouteMatcherProvider extends FileCacheRouteMatcherProvid
bundlePath: Normalizer
}
private readonly appDir: string
private readonly isTurbopack: boolean
constructor(
appDir: string,
extensions: ReadonlyArray<string>,
reader: FileReader
reader: FileReader,
isTurbopack: boolean
) {
super(appDir, reader)
this.appDir = appDir
this.normalizers = new DevAppNormalizers(appDir, extensions)
this.isTurbopack = isTurbopack
this.normalizers = new DevAppNormalizers(appDir, extensions, isTurbopack)
}
protected async transform(
......@@ -36,7 +39,7 @@ export class DevAppRouteRouteMatcherProvider extends FileCacheRouteMatcherProvid
): Promise<ReadonlyArray<AppRouteRouteMatcher>> {
const matchers: Array<AppRouteRouteMatcher> = []
for (const filename of files) {
const page = this.normalizers.page.normalize(filename)
let page = this.normalizers.page.normalize(filename)
// If the file isn't a match for this matcher, then skip it.
if (!isAppRouteRoute(page)) continue
......@@ -44,6 +47,14 @@ export class DevAppRouteRouteMatcherProvider extends FileCacheRouteMatcherProvid
// Validate that this is not an ignored page.
if (page.includes('/_')) continue
// Turbopack uses the correct page name with the underscore normalized.
// TODO: Move implementation to packages/next/src/server/normalizers/built/app/app-page-normalizer.ts.
// The `includes('/_')` check above needs to be moved for that to work as otherwise `%5Fsegmentname`
// will result in `_segmentname` which hits that includes check and be skipped.
if (this.isTurbopack) {
page = page.replace(/%5F/g, '_')
}
const pathname = this.normalizers.pathname.normalize(filename)
const bundlePath = this.normalizers.bundlePath.normalize(filename)
const ext = path.extname(filename).slice(1)
......
......@@ -33,12 +33,12 @@
"runtimeError": false
},
"test/e2e/app-dir/_allow-underscored-root-directory/_allow-underscored-root-directory.test.ts": {
"passed": [],
"failed": [
"passed": [
"_allow-underscored-root-directory should not serve app path with underscore",
"_allow-underscored-root-directory should pages path with a underscore at the root",
"_allow-underscored-root-directory should serve app path with %5F"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
......@@ -5810,12 +5810,12 @@
"runtimeError": false
},
"test/e2e/app-dir/underscore-ignore-app-paths/underscore-ignore-app-paths.test.ts": {
"passed": [],
"failed": [
"passed": [
"underscore-ignore-app-paths should not serve app path with underscore",
"underscore-ignore-app-paths should serve app path with %5F",
"underscore-ignore-app-paths should serve pages path with underscore"
],
"failed": [],
"pending": [],
"flakey": [],
"runtimeError": false
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