vinext 0.0.37 → 0.0.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -20
- package/dist/build/nitro-route-rules.d.ts +50 -0
- package/dist/build/nitro-route-rules.js +81 -0
- package/dist/build/nitro-route-rules.js.map +1 -0
- package/dist/build/precompress.d.ts +17 -0
- package/dist/build/precompress.js +102 -0
- package/dist/build/precompress.js.map +1 -0
- package/dist/build/prerender.d.ts +27 -22
- package/dist/build/prerender.js +17 -17
- package/dist/build/prerender.js.map +1 -1
- package/dist/build/report.d.ts +3 -4
- package/dist/build/report.js.map +1 -1
- package/dist/build/run-prerender.d.ts +3 -4
- package/dist/build/run-prerender.js.map +1 -1
- package/dist/build/standalone.d.ts +32 -0
- package/dist/build/standalone.js +199 -0
- package/dist/build/standalone.js.map +1 -0
- package/dist/build/static-export.d.ts +17 -29
- package/dist/build/static-export.js.map +1 -1
- package/dist/cache.d.ts +2 -0
- package/dist/cache.js +2 -0
- package/dist/check.d.ts +4 -4
- package/dist/check.js +1 -1
- package/dist/check.js.map +1 -1
- package/dist/cli.js +37 -26
- package/dist/cli.js.map +1 -1
- package/dist/client/empty-module.d.ts +1 -0
- package/dist/client/empty-module.js +1 -0
- package/dist/client/entry.js +2 -0
- package/dist/client/entry.js.map +1 -1
- package/dist/client/instrumentation-client-state.d.ts +10 -0
- package/dist/client/instrumentation-client-state.js +19 -0
- package/dist/client/instrumentation-client-state.js.map +1 -0
- package/dist/client/instrumentation-client.d.ts +8 -0
- package/dist/client/instrumentation-client.js +8 -0
- package/dist/client/instrumentation-client.js.map +1 -0
- package/dist/client/vinext-next-data.d.ts +5 -8
- package/dist/cloudflare/index.js +1 -1
- package/dist/cloudflare/kv-cache-handler.d.ts +5 -3
- package/dist/cloudflare/kv-cache-handler.js +1 -1
- package/dist/cloudflare/kv-cache-handler.js.map +1 -1
- package/dist/cloudflare/tpr.d.ts +35 -27
- package/dist/cloudflare/tpr.js +37 -15
- package/dist/cloudflare/tpr.js.map +1 -1
- package/dist/config/config-matchers.d.ts +2 -2
- package/dist/config/config-matchers.js +1 -1
- package/dist/config/config-matchers.js.map +1 -1
- package/dist/config/dotenv.d.ts +4 -4
- package/dist/config/dotenv.js.map +1 -1
- package/dist/config/next-config.d.ts +40 -61
- package/dist/config/next-config.js +5 -4
- package/dist/config/next-config.js.map +1 -1
- package/dist/deploy.d.ts +25 -41
- package/dist/deploy.js +10 -4
- package/dist/deploy.js.map +1 -1
- package/dist/entries/app-rsc-entry.d.ts +6 -10
- package/dist/entries/app-rsc-entry.js +31 -28
- package/dist/entries/app-rsc-entry.js.map +1 -1
- package/dist/entries/pages-client-entry.js +2 -0
- package/dist/entries/pages-client-entry.js.map +1 -1
- package/dist/entries/pages-server-entry.js +42 -263
- package/dist/entries/pages-server-entry.js.map +1 -1
- package/dist/entries/runtime-entry-module.d.ts +13 -1
- package/dist/entries/runtime-entry-module.js +18 -4
- package/dist/entries/runtime-entry-module.js.map +1 -1
- package/dist/index.d.ts +33 -41
- package/dist/index.js +263 -777
- package/dist/index.js.map +1 -1
- package/dist/init.d.ts +14 -26
- package/dist/init.js +8 -2
- package/dist/init.js.map +1 -1
- package/dist/plugins/client-reference-dedup.js.map +1 -1
- package/dist/plugins/fix-use-server-closure-collision.d.ts +29 -0
- package/dist/plugins/fix-use-server-closure-collision.js +204 -0
- package/dist/plugins/fix-use-server-closure-collision.js.map +1 -0
- package/dist/plugins/fonts.d.ts +56 -0
- package/dist/plugins/fonts.js +531 -0
- package/dist/plugins/fonts.js.map +1 -0
- package/dist/plugins/instrumentation-client.d.ts +7 -0
- package/dist/plugins/instrumentation-client.js +29 -0
- package/dist/plugins/instrumentation-client.js.map +1 -0
- package/dist/plugins/og-assets.d.ts +26 -0
- package/dist/plugins/og-assets.js +118 -0
- package/dist/plugins/og-assets.js.map +1 -0
- package/dist/plugins/optimize-imports.d.ts +2 -2
- package/dist/plugins/optimize-imports.js +4 -4
- package/dist/plugins/optimize-imports.js.map +1 -1
- package/dist/plugins/server-externals-manifest.d.ts +27 -0
- package/dist/plugins/server-externals-manifest.js +76 -0
- package/dist/plugins/server-externals-manifest.js.map +1 -0
- package/dist/routing/app-router.d.ts +29 -55
- package/dist/routing/app-router.js.map +1 -1
- package/dist/routing/file-matcher.d.ts +2 -2
- package/dist/routing/file-matcher.js.map +1 -1
- package/dist/routing/pages-router.d.ts +6 -11
- package/dist/routing/pages-router.js.map +1 -1
- package/dist/routing/route-trie.d.ts +2 -2
- package/dist/routing/route-trie.js.map +1 -1
- package/dist/server/api-handler.js +6 -23
- package/dist/server/api-handler.js.map +1 -1
- package/dist/server/app-browser-entry.js +274 -39
- package/dist/server/app-browser-entry.js.map +1 -1
- package/dist/server/app-browser-stream.d.ts +6 -6
- package/dist/server/app-browser-stream.js.map +1 -1
- package/dist/server/app-page-boundary-render.d.ts +8 -8
- package/dist/server/app-page-boundary-render.js +2 -2
- package/dist/server/app-page-boundary-render.js.map +1 -1
- package/dist/server/app-page-boundary.d.ts +13 -11
- package/dist/server/app-page-boundary.js +1 -1
- package/dist/server/app-page-boundary.js.map +1 -1
- package/dist/server/app-page-cache.d.ts +10 -10
- package/dist/server/app-page-cache.js.map +1 -1
- package/dist/server/app-page-execution.d.ts +10 -10
- package/dist/server/app-page-execution.js.map +1 -1
- package/dist/server/app-page-probe.d.ts +2 -2
- package/dist/server/app-page-probe.js.map +1 -1
- package/dist/server/app-page-render.d.ts +4 -4
- package/dist/server/app-page-render.js.map +1 -1
- package/dist/server/app-page-request.d.ts +12 -12
- package/dist/server/app-page-request.js.map +1 -1
- package/dist/server/app-page-response.d.ts +18 -18
- package/dist/server/app-page-response.js.map +1 -1
- package/dist/server/app-page-stream.d.ts +18 -18
- package/dist/server/app-page-stream.js.map +1 -1
- package/dist/server/app-route-handler-cache.d.ts +2 -2
- package/dist/server/app-route-handler-cache.js.map +1 -1
- package/dist/server/app-route-handler-execution.d.ts +6 -6
- package/dist/server/app-route-handler-execution.js.map +1 -1
- package/dist/server/app-route-handler-policy.d.ts +8 -8
- package/dist/server/app-route-handler-policy.js.map +1 -1
- package/dist/server/app-route-handler-response.d.ts +6 -6
- package/dist/server/app-route-handler-response.js.map +1 -1
- package/dist/server/app-route-handler-runtime.d.ts +4 -4
- package/dist/server/app-route-handler-runtime.js.map +1 -1
- package/dist/server/app-ssr-entry.d.ts +4 -4
- package/dist/server/app-ssr-entry.js.map +1 -1
- package/dist/server/app-ssr-stream.d.ts +2 -2
- package/dist/server/app-ssr-stream.js +1 -3
- package/dist/server/app-ssr-stream.js.map +1 -1
- package/dist/server/dev-module-runner.d.ts +2 -2
- package/dist/server/dev-module-runner.js.map +1 -1
- package/dist/server/dev-server.js +8 -8
- package/dist/server/dev-server.js.map +1 -1
- package/dist/server/image-optimization.d.ts +7 -12
- package/dist/server/image-optimization.js.map +1 -1
- package/dist/server/instrumentation.d.ts +13 -13
- package/dist/server/instrumentation.js +16 -7
- package/dist/server/instrumentation.js.map +1 -1
- package/dist/server/isr-cache.d.ts +2 -2
- package/dist/server/isr-cache.js.map +1 -1
- package/dist/server/metadata-routes.d.ts +14 -19
- package/dist/server/metadata-routes.js.map +1 -1
- package/dist/server/middleware.d.ts +10 -16
- package/dist/server/middleware.js +15 -8
- package/dist/server/middleware.js.map +1 -1
- package/dist/server/pages-api-route.d.ts +23 -0
- package/dist/server/pages-api-route.js +40 -0
- package/dist/server/pages-api-route.js.map +1 -0
- package/dist/server/pages-i18n.d.ts +4 -4
- package/dist/server/pages-i18n.js.map +1 -1
- package/dist/server/pages-media-type.d.ts +16 -0
- package/dist/server/pages-media-type.js +25 -0
- package/dist/server/pages-media-type.js.map +1 -0
- package/dist/server/pages-node-compat.d.ts +45 -0
- package/dist/server/pages-node-compat.js +148 -0
- package/dist/server/pages-node-compat.js.map +1 -0
- package/dist/server/pages-page-data.d.ts +22 -22
- package/dist/server/pages-page-data.js.map +1 -1
- package/dist/server/pages-page-response.d.ts +8 -8
- package/dist/server/pages-page-response.js.map +1 -1
- package/dist/server/prod-server.d.ts +20 -15
- package/dist/server/prod-server.js +171 -53
- package/dist/server/prod-server.js.map +1 -1
- package/dist/server/seed-cache.js.map +1 -1
- package/dist/server/static-file-cache.d.ts +57 -0
- package/dist/server/static-file-cache.js +219 -0
- package/dist/server/static-file-cache.js.map +1 -0
- package/dist/shims/app.d.ts +2 -2
- package/dist/shims/cache-for-request.d.ts +58 -0
- package/dist/shims/cache-for-request.js +74 -0
- package/dist/shims/cache-for-request.js.map +1 -0
- package/dist/shims/cache-runtime.d.ts +6 -9
- package/dist/shims/cache-runtime.js.map +1 -1
- package/dist/shims/cache.d.ts +28 -31
- package/dist/shims/cache.js.map +1 -1
- package/dist/shims/config.d.ts +2 -2
- package/dist/shims/config.js.map +1 -1
- package/dist/shims/dynamic.d.ts +2 -2
- package/dist/shims/dynamic.js +30 -17
- package/dist/shims/dynamic.js.map +1 -1
- package/dist/shims/error-boundary.d.ts +7 -7
- package/dist/shims/error-boundary.js.map +1 -1
- package/dist/shims/error.d.ts +2 -2
- package/dist/shims/error.js.map +1 -1
- package/dist/shims/fetch-cache.d.ts +4 -4
- package/dist/shims/fetch-cache.js.map +1 -1
- package/dist/shims/font-google-base.d.ts +4 -4
- package/dist/shims/font-google-base.js.map +1 -1
- package/dist/shims/font-local.d.ts +6 -6
- package/dist/shims/font-local.js.map +1 -1
- package/dist/shims/form.d.ts +4 -8
- package/dist/shims/form.js +4 -6
- package/dist/shims/form.js.map +1 -1
- package/dist/shims/head-state.d.ts +2 -2
- package/dist/shims/head-state.js.map +1 -1
- package/dist/shims/head.d.ts +2 -2
- package/dist/shims/head.js +18 -20
- package/dist/shims/head.js.map +1 -1
- package/dist/shims/headers.d.ts +4 -4
- package/dist/shims/headers.js +1 -1
- package/dist/shims/headers.js.map +1 -1
- package/dist/shims/i18n-context.d.ts +2 -2
- package/dist/shims/i18n-context.js.map +1 -1
- package/dist/shims/i18n-state.d.ts +2 -2
- package/dist/shims/i18n-state.js.map +1 -1
- package/dist/shims/image-config.d.ts +2 -2
- package/dist/shims/image-config.js.map +1 -1
- package/dist/shims/image.d.ts +5 -6
- package/dist/shims/image.js +24 -8
- package/dist/shims/image.js.map +1 -1
- package/dist/shims/internal/app-router-context.d.ts +6 -6
- package/dist/shims/internal/app-router-context.js.map +1 -1
- package/dist/shims/internal/utils.d.ts +2 -2
- package/dist/shims/internal/utils.js.map +1 -1
- package/dist/shims/layout-segment-context.d.ts +12 -5
- package/dist/shims/layout-segment-context.js +18 -7
- package/dist/shims/layout-segment-context.js.map +1 -1
- package/dist/shims/legacy-image.d.ts +5 -8
- package/dist/shims/legacy-image.js.map +1 -1
- package/dist/shims/link.d.ts +21 -31
- package/dist/shims/link.js +4 -56
- package/dist/shims/link.js.map +1 -1
- package/dist/shims/metadata.d.ts +23 -31
- package/dist/shims/metadata.js.map +1 -1
- package/dist/shims/navigation-state.d.ts +2 -2
- package/dist/shims/navigation-state.js.map +1 -1
- package/dist/shims/navigation.d.ts +102 -17
- package/dist/shims/navigation.js +361 -113
- package/dist/shims/navigation.js.map +1 -1
- package/dist/shims/request-context.d.ts +2 -2
- package/dist/shims/request-context.js.map +1 -1
- package/dist/shims/router-state.d.ts +4 -4
- package/dist/shims/router-state.js.map +1 -1
- package/dist/shims/router.d.ts +28 -47
- package/dist/shims/router.js.map +1 -1
- package/dist/shims/script.d.ts +16 -31
- package/dist/shims/script.js.map +1 -1
- package/dist/shims/server.d.ts +11 -10
- package/dist/shims/server.js +3 -0
- package/dist/shims/server.js.map +1 -1
- package/dist/shims/unified-request-context.d.ts +4 -4
- package/dist/shims/unified-request-context.js +1 -0
- package/dist/shims/unified-request-context.js.map +1 -1
- package/dist/shims/web-vitals.d.ts +2 -2
- package/dist/shims/web-vitals.js.map +1 -1
- package/dist/utils/lazy-chunks.d.ts +34 -0
- package/dist/utils/lazy-chunks.js +50 -0
- package/dist/utils/lazy-chunks.js.map +1 -0
- package/dist/utils/vinext-root.d.ts +24 -0
- package/dist/utils/vinext-root.js +31 -0
- package/dist/utils/vinext-root.js.map +1 -0
- package/package.json +8 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-externals-manifest.js","names":[],"sources":["../../src/plugins/server-externals-manifest.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { Plugin } from \"vite\";\n\n/**\n * Extract the npm package name from a bare module specifier.\n *\n * Returns null for:\n * - Relative imports (\"./foo\", \"../bar\")\n * - Absolute paths (\"/abs/path\")\n * - Node built-ins (\"node:fs\")\n * - Package self-references (\"#imports\")\n */\nfunction packageNameFromSpecifier(specifier: string): string | null {\n if (\n specifier.startsWith(\".\") ||\n specifier.startsWith(\"/\") ||\n specifier.startsWith(\"node:\") ||\n specifier.startsWith(\"#\")\n ) {\n return null;\n }\n\n if (specifier.startsWith(\"@\")) {\n const parts = specifier.split(\"/\");\n if (parts.length >= 2) {\n return `${parts[0]}/${parts[1]}`;\n }\n return null;\n }\n\n return specifier.split(\"/\")[0] || null;\n}\n\n/**\n * vinext:server-externals-manifest\n *\n * A `writeBundle` plugin that collects the packages left external by the\n * SSR/RSC bundler and writes them to `<outDir>/vinext-externals.json`.\n *\n * With `noExternal: true`, Vite bundles almost everything — only packages\n * explicitly listed in `ssr.external` / `resolve.external` remain as live\n * imports in the server bundle. Those packages are exactly what a standalone\n * deployment needs in `node_modules/`.\n *\n * Using the bundler's own import graph (`chunk.imports` + `chunk.dynamicImports`)\n * is authoritative: no text parsing, no regex, no guessing.\n *\n * The written JSON is an array of package-name strings, e.g.:\n * [\"react\", \"react-dom\", \"react-dom/server\"]\n *\n * `emitStandaloneOutput` reads this file and uses it as the seed list for the\n * BFS `node_modules/` copy, replacing the old regex-scan approach.\n */\nexport function createServerExternalsManifestPlugin(): Plugin {\n // Accumulate external specifiers across all server environments (rsc + ssr).\n // Both environments run writeBundle; we merge their results so Pages Router\n // builds (ssr only) and App Router builds (rsc + ssr) both produce a\n // complete manifest.\n const externals = new Set<string>();\n let outDir: string | null = null;\n\n return {\n name: \"vinext:server-externals-manifest\",\n apply: \"build\",\n enforce: \"post\",\n\n writeBundle: {\n sequential: true,\n order: \"post\",\n handler(options, bundle) {\n const envName = this.environment?.name;\n // Only collect from server environments (rsc = App Router RSC build,\n // ssr = Pages Router SSR build or App Router SSR build).\n if (envName !== \"rsc\" && envName !== \"ssr\") return;\n\n const dir = options.dir;\n if (!dir) return;\n\n // Use the first server env's outDir parent as the canonical server dir.\n // For Pages Router: options.dir IS dist/server.\n // For App Router RSC: options.dir is dist/server.\n // For App Router SSR: options.dir is dist/server/ssr.\n // We always want dist/server as the manifest location.\n if (!outDir) {\n // The server bundle outputs to dist/server for all environments except\n // App Router SSR, which outputs to dist/server/ssr. We always want\n // dist/server as the manifest location. Rather than hard-coding \"ssr\",\n // treat any sub-directory of dist/server (basename !== \"server\") as a\n // sub-env and walk up one level. This handles any future sub-directory\n // environments (e.g. \"edge\") without code changes.\n // Note: using basename rather than a walk-up avoids misfiring when a\n // user's project path contains a \"server\" segment above the dist output\n // (e.g. /home/user/server/my-app/).\n outDir = path.basename(dir) === \"server\" ? dir : path.dirname(dir);\n }\n\n for (const item of Object.values(bundle)) {\n if (item.type !== \"chunk\") continue;\n // In Rollup output, item.imports normally contains filenames of other\n // chunks in the bundle. But externalized packages remain as bare npm\n // specifiers (e.g. \"react\", \"@mdx-js/react\") since they were never\n // bundled into chunk files. packageNameFromSpecifier filters out chunk\n // filenames (relative/absolute paths) and extracts the package name from\n // bare specifiers — which is exactly what the standalone BFS needs.\n for (const specifier of [...item.imports, ...item.dynamicImports]) {\n const pkg = packageNameFromSpecifier(specifier);\n if (pkg) externals.add(pkg);\n }\n }\n\n // After the last expected writeBundle call, flush to disk.\n // We flush on every call since we don't know ahead of time how many\n // environments will fire — overwriting with the accumulated set is safe.\n if (outDir && fs.existsSync(outDir)) {\n const manifestPath = path.join(outDir, \"vinext-externals.json\");\n fs.writeFileSync(manifestPath, JSON.stringify([...externals], null, 2) + \"\\n\", \"utf-8\");\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+1,20 @@
|
|
|
1
1
|
import { ValidFileMatcher } from "./file-matcher.js";
|
|
2
2
|
|
|
3
3
|
//#region src/routing/app-router.d.ts
|
|
4
|
-
|
|
5
|
-
/** The interception convention: "." | ".." | "../.." | "..." */
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
targetPattern: string;
|
|
9
|
-
/** Absolute path to the intercepting page component */
|
|
10
|
-
pagePath: string;
|
|
11
|
-
/** Parameter names for dynamic segments */
|
|
4
|
+
type InterceptingRoute = {
|
|
5
|
+
/** The interception convention: "." | ".." | "../.." | "..." */convention: string; /** The URL pattern this intercepts (e.g. "/photos/:id") */
|
|
6
|
+
targetPattern: string; /** Absolute path to the intercepting page component */
|
|
7
|
+
pagePath: string; /** Parameter names for dynamic segments */
|
|
12
8
|
params: string[];
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
/** Slot name (e.g. "team" from @team) */
|
|
16
|
-
|
|
17
|
-
/** Absolute path to the
|
|
18
|
-
|
|
19
|
-
/** Absolute path to the slot's
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
defaultPath: string | null;
|
|
23
|
-
/** Absolute path to the slot's layout component (wraps slot content) */
|
|
24
|
-
layoutPath: string | null;
|
|
25
|
-
/** Absolute path to the slot's loading component */
|
|
26
|
-
loadingPath: string | null;
|
|
27
|
-
/** Absolute path to the slot's error component */
|
|
28
|
-
errorPath: string | null;
|
|
29
|
-
/** Intercepting routes within this slot */
|
|
9
|
+
};
|
|
10
|
+
type ParallelSlot = {
|
|
11
|
+
/** Slot name (e.g. "team" from @team) */name: string; /** Absolute path to the @slot directory that owns this slot. Internal routing metadata. */
|
|
12
|
+
ownerDir: string; /** Absolute path to the slot's page component */
|
|
13
|
+
pagePath: string | null; /** Absolute path to the slot's default.tsx fallback */
|
|
14
|
+
defaultPath: string | null; /** Absolute path to the slot's layout component (wraps slot content) */
|
|
15
|
+
layoutPath: string | null; /** Absolute path to the slot's loading component */
|
|
16
|
+
loadingPath: string | null; /** Absolute path to the slot's error component */
|
|
17
|
+
errorPath: string | null; /** Intercepting routes within this slot */
|
|
30
18
|
interceptingRoutes: InterceptingRoute[];
|
|
31
19
|
/**
|
|
32
20
|
* The layout index (0-based, in route.layouts[]) that this slot belongs to.
|
|
@@ -34,23 +22,15 @@ interface ParallelSlot {
|
|
|
34
22
|
* necessarily the innermost layout. -1 means "innermost" (legacy default).
|
|
35
23
|
*/
|
|
36
24
|
layoutIndex: number;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/** URL pattern, e.g. "/" or "/about" or "/blog/:slug" */
|
|
40
|
-
|
|
41
|
-
/**
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
layouts: string[];
|
|
47
|
-
/** Ordered list of template files from root to leaf (parallel to layouts) */
|
|
48
|
-
templates: string[];
|
|
49
|
-
/** Parallel route slots (from @slot directories at the route's directory level) */
|
|
50
|
-
parallelSlots: ParallelSlot[];
|
|
51
|
-
/** Loading component path */
|
|
52
|
-
loadingPath: string | null;
|
|
53
|
-
/** Error component path (leaf directory only) */
|
|
25
|
+
};
|
|
26
|
+
type AppRoute = {
|
|
27
|
+
/** URL pattern, e.g. "/" or "/about" or "/blog/:slug" */pattern: string; /** Absolute file path to the page component */
|
|
28
|
+
pagePath: string | null; /** Absolute file path to the route handler (route.ts) */
|
|
29
|
+
routePath: string | null; /** Ordered list of layout files from root to leaf */
|
|
30
|
+
layouts: string[]; /** Ordered list of template files from root to leaf (parallel to layouts) */
|
|
31
|
+
templates: string[]; /** Parallel route slots (from @slot directories at the route's directory level) */
|
|
32
|
+
parallelSlots: ParallelSlot[]; /** Loading component path */
|
|
33
|
+
loadingPath: string | null; /** Error component path (leaf directory only) */
|
|
54
34
|
errorPath: string | null;
|
|
55
35
|
/**
|
|
56
36
|
* Per-layout error boundary paths, aligned with the layouts array.
|
|
@@ -59,8 +39,7 @@ interface AppRoute {
|
|
|
59
39
|
* Used to interleave ErrorBoundary components with layouts so that
|
|
60
40
|
* ancestor error boundaries catch errors from descendant segments.
|
|
61
41
|
*/
|
|
62
|
-
layoutErrorPaths: (string | null)[];
|
|
63
|
-
/** Not-found component path (nearest, walking up from page dir) */
|
|
42
|
+
layoutErrorPaths: (string | null)[]; /** Not-found component path (nearest, walking up from page dir) */
|
|
64
43
|
notFoundPath: string | null;
|
|
65
44
|
/**
|
|
66
45
|
* Not-found component paths per layout level (aligned with layouts array).
|
|
@@ -68,10 +47,8 @@ interface AppRoute {
|
|
|
68
47
|
* Used to create per-layout NotFoundBoundary so that notFound() thrown from
|
|
69
48
|
* a layout is caught by the parent layout's boundary (matching Next.js behavior).
|
|
70
49
|
*/
|
|
71
|
-
notFoundPaths: (string | null)[];
|
|
72
|
-
/**
|
|
73
|
-
forbiddenPath: string | null;
|
|
74
|
-
/** Unauthorized component path (401) */
|
|
50
|
+
notFoundPaths: (string | null)[]; /** Forbidden component path (403) */
|
|
51
|
+
forbiddenPath: string | null; /** Unauthorized component path (401) */
|
|
75
52
|
unauthorizedPath: string | null;
|
|
76
53
|
/**
|
|
77
54
|
* Filesystem segments from app/ root to the route's directory.
|
|
@@ -86,14 +63,11 @@ interface AppRoute {
|
|
|
86
63
|
* Unlike the old layoutSegmentDepths, this counts ALL directory levels including
|
|
87
64
|
* route groups and parallel slots.
|
|
88
65
|
*/
|
|
89
|
-
layoutTreePositions: number[];
|
|
90
|
-
/**
|
|
91
|
-
|
|
92
|
-
/** Parameter names for dynamic segments */
|
|
93
|
-
params: string[];
|
|
94
|
-
/** Pre-split pattern segments (computed once at scan time, reused per request) */
|
|
66
|
+
layoutTreePositions: number[]; /** Whether this is a dynamic route */
|
|
67
|
+
isDynamic: boolean; /** Parameter names for dynamic segments */
|
|
68
|
+
params: string[]; /** Pre-split pattern segments (computed once at scan time, reused per request) */
|
|
95
69
|
patternParts: string[];
|
|
96
|
-
}
|
|
70
|
+
};
|
|
97
71
|
declare function invalidateAppRouteCache(): void;
|
|
98
72
|
/**
|
|
99
73
|
* Scan the app/ directory and return a list of routes.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-router.js","names":[],"sources":["../../src/routing/app-router.ts"],"sourcesContent":["/**\n * App Router file-system routing.\n *\n * Scans the app/ directory following Next.js App Router conventions:\n * - app/page.tsx -> /\n * - app/about/page.tsx -> /about\n * - app/blog/[slug]/page.tsx -> /blog/:slug\n * - app/[...catchAll]/page.tsx -> /:catchAll+\n * - app/route.ts -> / (API route)\n * - app/(group)/page.tsx -> / (route groups are transparent)\n * - Layouts: app/layout.tsx wraps all children\n * - Loading: app/loading.tsx -> Suspense fallback\n * - Error: app/error.tsx -> ErrorBoundary\n * - Not Found: app/not-found.tsx\n */\nimport path from \"node:path\";\nimport fs from \"node:fs\";\nimport { compareRoutes, decodeRouteSegment, normalizePathnameForRouteMatch } from \"./utils.js\";\nimport {\n createValidFileMatcher,\n scanWithExtensions,\n type ValidFileMatcher,\n} from \"./file-matcher.js\";\nimport { validateRoutePatterns } from \"./route-validation.js\";\nimport { buildRouteTrie, trieMatch, type TrieNode } from \"./route-trie.js\";\n\nexport interface InterceptingRoute {\n /** The interception convention: \".\" | \"..\" | \"../..\" | \"...\" */\n convention: string;\n /** The URL pattern this intercepts (e.g. \"/photos/:id\") */\n targetPattern: string;\n /** Absolute path to the intercepting page component */\n pagePath: string;\n /** Parameter names for dynamic segments */\n params: string[];\n}\n\nexport interface ParallelSlot {\n /** Slot name (e.g. \"team\" from @team) */\n name: string;\n /** Absolute path to the @slot directory that owns this slot. Internal routing metadata. */\n ownerDir: string;\n /** Absolute path to the slot's page component */\n pagePath: string | null;\n /** Absolute path to the slot's default.tsx fallback */\n defaultPath: string | null;\n /** Absolute path to the slot's layout component (wraps slot content) */\n layoutPath: string | null;\n /** Absolute path to the slot's loading component */\n loadingPath: string | null;\n /** Absolute path to the slot's error component */\n errorPath: string | null;\n /** Intercepting routes within this slot */\n interceptingRoutes: InterceptingRoute[];\n /**\n * The layout index (0-based, in route.layouts[]) that this slot belongs to.\n * Slots are passed as props to the layout at their directory level, not\n * necessarily the innermost layout. -1 means \"innermost\" (legacy default).\n */\n layoutIndex: number;\n}\n\nexport interface AppRoute {\n /** URL pattern, e.g. \"/\" or \"/about\" or \"/blog/:slug\" */\n pattern: string;\n /** Absolute file path to the page component */\n pagePath: string | null;\n /** Absolute file path to the route handler (route.ts) */\n routePath: string | null;\n /** Ordered list of layout files from root to leaf */\n layouts: string[];\n /** Ordered list of template files from root to leaf (parallel to layouts) */\n templates: string[];\n /** Parallel route slots (from @slot directories at the route's directory level) */\n parallelSlots: ParallelSlot[];\n /** Loading component path */\n loadingPath: string | null;\n /** Error component path (leaf directory only) */\n errorPath: string | null;\n /**\n * Per-layout error boundary paths, aligned with the layouts array.\n * Each entry is the error.tsx at the same directory level as the\n * corresponding layout (or null if that level has no error.tsx).\n * Used to interleave ErrorBoundary components with layouts so that\n * ancestor error boundaries catch errors from descendant segments.\n */\n layoutErrorPaths: (string | null)[];\n /** Not-found component path (nearest, walking up from page dir) */\n notFoundPath: string | null;\n /**\n * Not-found component paths per layout level (aligned with layouts array).\n * Each entry is the not-found.tsx at that layout's directory, or null.\n * Used to create per-layout NotFoundBoundary so that notFound() thrown from\n * a layout is caught by the parent layout's boundary (matching Next.js behavior).\n */\n notFoundPaths: (string | null)[];\n /** Forbidden component path (403) */\n forbiddenPath: string | null;\n /** Unauthorized component path (401) */\n unauthorizedPath: string | null;\n /**\n * Filesystem segments from app/ root to the route's directory.\n * Includes route groups and dynamic segments (as template strings like \"[id]\").\n * Used at render time to compute the child segments for useSelectedLayoutSegments().\n */\n routeSegments: string[];\n /**\n * Tree position (directory depth from app/ root) for each layout.\n * Used to slice routeSegments and determine which segments are below each layout.\n * For example, root layout = 0, a layout at app/blog/ = 1, app/blog/(group)/ = 2.\n * Unlike the old layoutSegmentDepths, this counts ALL directory levels including\n * route groups and parallel slots.\n */\n layoutTreePositions: number[];\n /** Whether this is a dynamic route */\n isDynamic: boolean;\n /** Parameter names for dynamic segments */\n params: string[];\n /** Pre-split pattern segments (computed once at scan time, reused per request) */\n patternParts: string[];\n}\n\n// Cache for app routes\nlet cachedRoutes: AppRoute[] | null = null;\nlet cachedAppDir: string | null = null;\nlet cachedPageExtensionsKey: string | null = null;\n\nexport function invalidateAppRouteCache(): void {\n cachedRoutes = null;\n cachedAppDir = null;\n cachedPageExtensionsKey = null;\n}\n\n/**\n * Scan the app/ directory and return a list of routes.\n */\nexport async function appRouter(\n appDir: string,\n pageExtensions?: readonly string[],\n matcher?: ValidFileMatcher,\n): Promise<AppRoute[]> {\n matcher ??= createValidFileMatcher(pageExtensions);\n const pageExtensionsKey = JSON.stringify(matcher.extensions);\n if (cachedRoutes && cachedAppDir === appDir && cachedPageExtensionsKey === pageExtensionsKey) {\n return cachedRoutes;\n }\n\n // Find all page.tsx and route.ts files, excluding @slot directories\n // (slot pages are not standalone routes — they're rendered as props of their parent layout)\n // and _private folders (Next.js convention for colocated non-route files).\n const routes: AppRoute[] = [];\n\n const excludeDir = (name: string) => name.startsWith(\"@\") || name.startsWith(\"_\");\n\n // Process page files in a single pass\n // Use function form of exclude for Node < 22.14 compatibility (string arrays require >= 22.14)\n for await (const file of scanWithExtensions(\"**/page\", appDir, matcher.extensions, excludeDir)) {\n const route = fileToAppRoute(file, appDir, \"page\", matcher);\n if (route) routes.push(route);\n }\n\n // Process route handler files (API routes) in a single pass\n for await (const file of scanWithExtensions(\"**/route\", appDir, matcher.extensions, excludeDir)) {\n const route = fileToAppRoute(file, appDir, \"route\", matcher);\n if (route) routes.push(route);\n }\n\n // Discover sub-routes created by nested pages within parallel slots.\n // In Next.js, pages nested inside @slot directories create additional URL routes.\n // For example, @audience/demographics/page.tsx at app/parallel-routes/ creates\n // a route at /parallel-routes/demographics.\n const slotSubRoutes = discoverSlotSubRoutes(routes, appDir, matcher);\n routes.push(...slotSubRoutes);\n\n validateRoutePatterns(routes.map((route) => route.pattern));\n validateRoutePatterns(\n routes.flatMap((route) =>\n route.parallelSlots.flatMap((slot) =>\n slot.interceptingRoutes.map((intercept) => intercept.targetPattern),\n ),\n ),\n );\n\n // Sort: static routes first, then dynamic, then catch-all\n routes.sort(compareRoutes);\n\n cachedRoutes = routes;\n cachedAppDir = appDir;\n cachedPageExtensionsKey = pageExtensionsKey;\n return routes;\n}\n\n/**\n * Discover sub-routes created by nested pages within parallel slots.\n *\n * In Next.js, pages nested inside @slot directories create additional URL routes.\n * For example, given:\n * app/parallel-routes/@audience/demographics/page.tsx\n * This creates a route at /parallel-routes/demographics where:\n * - children slot → parent's default.tsx\n * - @audience slot → @audience/demographics/page.tsx (matched)\n * - other slots → their default.tsx (fallback)\n */\nfunction discoverSlotSubRoutes(\n routes: AppRoute[],\n _appDir: string,\n matcher: ValidFileMatcher,\n): AppRoute[] {\n const syntheticRoutes: AppRoute[] = [];\n\n // O(1) lookup for existing routes by pattern — avoids O(n) routes.find() per sub-path per parent.\n // Updated as new synthetic routes are pushed so that later parents can see earlier synthetic entries.\n const routesByPattern = new Map<string, AppRoute>(routes.map((r) => [r.pattern, r]));\n\n const slotKey = (slotName: string, ownerDir: string): string => `${slotName}\\u0000${ownerDir}`;\n\n const applySlotSubPages = (route: AppRoute, slotPages: Map<string, string>): void => {\n route.parallelSlots = route.parallelSlots.map((slot) => ({\n ...slot,\n pagePath: slotPages.get(slotKey(slot.name, slot.ownerDir)) ?? slot.pagePath,\n }));\n };\n\n for (const parentRoute of routes) {\n if (parentRoute.parallelSlots.length === 0) continue;\n if (!parentRoute.pagePath) continue;\n\n const parentPageDir = path.dirname(parentRoute.pagePath);\n\n // Collect sub-paths from all slots.\n // Map: normalized visible sub-path -> slot pages, raw filesystem segments (for routeSegments),\n // and the pre-computed convertedSubRoute (to avoid a redundant re-conversion in the merge loop).\n const subPathMap = new Map<\n string,\n {\n // Raw filesystem segments (with route groups, @slots, etc.) used for routeSegments so\n // that useSelectedLayoutSegments() sees the correct segment list at runtime.\n rawSegments: string[];\n // Pre-computed URL parts, params, isDynamic from convertSegmentsToRouteParts.\n converted: { urlSegments: string[]; params: string[]; isDynamic: boolean };\n slotPages: Map<string, string>;\n }\n >();\n\n for (const slot of parentRoute.parallelSlots) {\n const slotDir = path.join(parentPageDir, `@${slot.name}`);\n if (!fs.existsSync(slotDir)) continue;\n\n const subPages = findSlotSubPages(slotDir, matcher);\n for (const { relativePath, pagePath } of subPages) {\n const subSegments = relativePath.split(path.sep);\n const convertedSubRoute = convertSegmentsToRouteParts(subSegments);\n if (!convertedSubRoute) continue;\n\n const { urlSegments } = convertedSubRoute;\n const normalizedSubPath = urlSegments.join(\"/\");\n let subPathEntry = subPathMap.get(normalizedSubPath);\n\n if (!subPathEntry) {\n subPathEntry = {\n rawSegments: subSegments,\n converted: convertedSubRoute,\n slotPages: new Map(),\n };\n subPathMap.set(normalizedSubPath, subPathEntry);\n }\n\n const slotId = slotKey(slot.name, slot.ownerDir);\n const existingSlotPage = subPathEntry.slotPages.get(slotId);\n if (existingSlotPage) {\n const pattern = joinRoutePattern(parentRoute.pattern, normalizedSubPath);\n throw new Error(\n `You cannot have two routes that resolve to the same path (\"${pattern}\").`,\n );\n }\n\n subPathEntry.slotPages.set(slotId, pagePath);\n }\n }\n\n if (subPathMap.size === 0) continue;\n\n // Find the default.tsx for the children slot at the parent directory\n const childrenDefault = findFile(parentPageDir, \"default\", matcher);\n if (!childrenDefault) continue;\n\n for (const { rawSegments, converted: convertedSubRoute, slotPages } of subPathMap.values()) {\n const {\n urlSegments: urlParts,\n params: subParams,\n isDynamic: subIsDynamic,\n } = convertedSubRoute;\n\n const subUrlPath = urlParts.join(\"/\");\n const pattern = joinRoutePattern(parentRoute.pattern, subUrlPath);\n\n const existingRoute = routesByPattern.get(pattern);\n if (existingRoute) {\n if (existingRoute.routePath && !existingRoute.pagePath) {\n throw new Error(\n `You cannot have two routes that resolve to the same path (\"${pattern}\").`,\n );\n }\n applySlotSubPages(existingRoute, slotPages);\n continue;\n }\n\n // Build parallel slots for this sub-route: matching slots get the sub-page,\n // non-matching slots get null pagePath (rendering falls back to defaultPath)\n const subSlots: ParallelSlot[] = parentRoute.parallelSlots.map((slot) => ({\n ...slot,\n pagePath: slotPages.get(slotKey(slot.name, slot.ownerDir)) || null,\n }));\n\n const newRoute: AppRoute = {\n pattern,\n pagePath: childrenDefault, // children slot uses parent's default.tsx as page\n routePath: null,\n layouts: parentRoute.layouts,\n templates: parentRoute.templates,\n parallelSlots: subSlots,\n loadingPath: parentRoute.loadingPath,\n errorPath: parentRoute.errorPath,\n layoutErrorPaths: parentRoute.layoutErrorPaths,\n notFoundPath: parentRoute.notFoundPath,\n notFoundPaths: parentRoute.notFoundPaths,\n forbiddenPath: parentRoute.forbiddenPath,\n unauthorizedPath: parentRoute.unauthorizedPath,\n routeSegments: [...parentRoute.routeSegments, ...rawSegments],\n layoutTreePositions: parentRoute.layoutTreePositions,\n isDynamic: parentRoute.isDynamic || subIsDynamic,\n params: [...parentRoute.params, ...subParams],\n patternParts: [...parentRoute.patternParts, ...urlParts],\n };\n syntheticRoutes.push(newRoute);\n routesByPattern.set(pattern, newRoute);\n }\n }\n\n return syntheticRoutes;\n}\n\n/**\n * Find all page files in subdirectories of a parallel slot directory.\n * Returns relative paths (from the slot dir) and absolute page paths.\n * Skips the root page.tsx (already handled as the slot's main page)\n * and intercepting route directories.\n */\nfunction findSlotSubPages(\n slotDir: string,\n matcher: ValidFileMatcher,\n): Array<{ relativePath: string; pagePath: string }> {\n const results: Array<{ relativePath: string; pagePath: string }> = [];\n\n function scan(dir: string): void {\n if (!fs.existsSync(dir)) return;\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n // Skip intercepting route directories\n if (matchInterceptConvention(entry.name)) continue;\n // Skip private folders (prefixed with _)\n if (entry.name.startsWith(\"_\")) continue;\n\n const subDir = path.join(dir, entry.name);\n const page = findFile(subDir, \"page\", matcher);\n if (page) {\n const relativePath = path.relative(slotDir, subDir);\n results.push({ relativePath, pagePath: page });\n }\n // Continue scanning deeper for nested sub-pages\n scan(subDir);\n }\n }\n\n scan(slotDir);\n return results;\n}\n\n/**\n * Convert a file path relative to app/ into an AppRoute.\n */\nfunction fileToAppRoute(\n file: string,\n appDir: string,\n type: \"page\" | \"route\",\n matcher: ValidFileMatcher,\n): AppRoute | null {\n // Remove the filename (page.tsx or route.ts)\n const dir = path.dirname(file);\n const segments = dir === \".\" ? [] : dir.split(path.sep);\n\n const params: string[] = [];\n let isDynamic = false;\n\n const convertedRoute = convertSegmentsToRouteParts(segments);\n if (!convertedRoute) return null;\n\n const { urlSegments, params: routeParams, isDynamic: routeIsDynamic } = convertedRoute;\n params.push(...routeParams);\n isDynamic = routeIsDynamic;\n\n const pattern = \"/\" + urlSegments.join(\"/\");\n\n // Discover layouts and templates from root to leaf\n const layouts = discoverLayouts(segments, appDir, matcher);\n const templates = discoverTemplates(segments, appDir, matcher);\n\n // Compute the tree position (directory depth) for each layout.\n const layoutTreePositions = computeLayoutTreePositions(appDir, layouts);\n\n // Discover per-layout error boundaries (aligned with layouts array).\n // In Next.js, each segment independently wraps its children with an ErrorBoundary.\n // This array enables interleaving error boundaries with layouts in the rendering.\n const layoutErrorPaths = discoverLayoutAlignedErrors(segments, appDir, matcher);\n\n // Discover loading, error in the route's directory\n const routeDir = dir === \".\" ? appDir : path.join(appDir, dir);\n const loadingPath = findFile(routeDir, \"loading\", matcher);\n const errorPath = findFile(routeDir, \"error\", matcher);\n\n // Discover not-found/forbidden/unauthorized: walk from route directory up to root (nearest wins).\n const notFoundPath = discoverBoundaryFile(segments, appDir, \"not-found\", matcher);\n const forbiddenPath = discoverBoundaryFile(segments, appDir, \"forbidden\", matcher);\n const unauthorizedPath = discoverBoundaryFile(segments, appDir, \"unauthorized\", matcher);\n\n // Discover per-layout not-found files (one per layout directory).\n // These are used for per-layout NotFoundBoundary to match Next.js behavior where\n // notFound() thrown from a layout is caught by the parent layout's boundary.\n const notFoundPaths = discoverBoundaryFilePerLayout(layouts, \"not-found\", matcher);\n\n // Discover parallel slots (@team, @analytics, etc.).\n // Slots at the route's own directory use page.tsx; slots at ancestor directories\n // (inherited from parent layouts) use default.tsx as fallback.\n const parallelSlots = discoverInheritedParallelSlots(segments, appDir, routeDir, matcher);\n\n return {\n pattern: pattern === \"/\" ? \"/\" : pattern,\n pagePath: type === \"page\" ? path.join(appDir, file) : null,\n routePath: type === \"route\" ? path.join(appDir, file) : null,\n layouts,\n templates,\n parallelSlots,\n loadingPath,\n errorPath,\n layoutErrorPaths,\n notFoundPath,\n notFoundPaths,\n forbiddenPath,\n unauthorizedPath,\n routeSegments: segments,\n layoutTreePositions,\n isDynamic,\n params,\n patternParts: urlSegments,\n };\n}\n\n/**\n * Compute the tree position (directory depth from app root) for each layout.\n * Root layout = 0, a layout at app/blog/ = 1, app/blog/(group)/ = 2.\n * Counts ALL directory levels including route groups and parallel slots.\n */\nfunction computeLayoutTreePositions(appDir: string, layouts: string[]): number[] {\n return layouts.map((layoutPath) => {\n const layoutDir = path.dirname(layoutPath);\n if (layoutDir === appDir) return 0;\n const relative = path.relative(appDir, layoutDir);\n return relative.split(path.sep).length;\n });\n}\n\n/**\n * Discover all layout files from root to the given directory.\n * Each level of the directory tree may have a layout.tsx.\n */\nfunction discoverLayouts(segments: string[], appDir: string, matcher: ValidFileMatcher): string[] {\n const layouts: string[] = [];\n\n // Check root layout\n const rootLayout = findFile(appDir, \"layout\", matcher);\n if (rootLayout) layouts.push(rootLayout);\n\n // Check each directory level\n let currentDir = appDir;\n for (const segment of segments) {\n currentDir = path.join(currentDir, segment);\n const layout = findFile(currentDir, \"layout\", matcher);\n if (layout) layouts.push(layout);\n }\n\n return layouts;\n}\n\n/**\n * Discover all template files from root to the given directory.\n * Each level of the directory tree may have a template.tsx.\n * Templates are like layouts but re-mount on navigation.\n */\nfunction discoverTemplates(\n segments: string[],\n appDir: string,\n matcher: ValidFileMatcher,\n): string[] {\n const templates: string[] = [];\n\n // Check root template\n const rootTemplate = findFile(appDir, \"template\", matcher);\n if (rootTemplate) templates.push(rootTemplate);\n\n // Check each directory level\n let currentDir = appDir;\n for (const segment of segments) {\n currentDir = path.join(currentDir, segment);\n const template = findFile(currentDir, \"template\", matcher);\n if (template) templates.push(template);\n }\n\n return templates;\n}\n\n/**\n * Discover error.tsx files aligned with the layouts array.\n * Walks the same directory levels as discoverLayouts and, for each level\n * that contributes a layout entry, checks whether error.tsx also exists.\n * Returns an array of the same length as discoverLayouts() would return,\n * with the error path (or null) at each corresponding layout level.\n *\n * This enables interleaving ErrorBoundary components with layouts in the\n * rendering tree, matching Next.js behavior where each segment independently\n * wraps its children with an error boundary.\n */\nfunction discoverLayoutAlignedErrors(\n segments: string[],\n appDir: string,\n matcher: ValidFileMatcher,\n): (string | null)[] {\n const errors: (string | null)[] = [];\n\n // Root level (only if root has a layout — matching discoverLayouts logic)\n const rootLayout = findFile(appDir, \"layout\", matcher);\n if (rootLayout) {\n errors.push(findFile(appDir, \"error\", matcher));\n }\n\n // Check each directory level\n let currentDir = appDir;\n for (const segment of segments) {\n currentDir = path.join(currentDir, segment);\n const layout = findFile(currentDir, \"layout\", matcher);\n if (layout) {\n errors.push(findFile(currentDir, \"error\", matcher));\n }\n }\n\n return errors;\n}\n\n/**\n * Discover the nearest boundary file (not-found, forbidden, unauthorized)\n * by walking from the route's directory up to the app root.\n * Returns the first (closest) file found, or null.\n */\nfunction discoverBoundaryFile(\n segments: string[],\n appDir: string,\n fileName: string,\n matcher: ValidFileMatcher,\n): string | null {\n // Build all directory paths from leaf to root\n const dirs: string[] = [];\n let dir = appDir;\n dirs.push(dir);\n for (const segment of segments) {\n dir = path.join(dir, segment);\n dirs.push(dir);\n }\n\n // Walk from leaf (last) to root (first)\n for (let i = dirs.length - 1; i >= 0; i--) {\n const f = findFile(dirs[i], fileName, matcher);\n if (f) return f;\n }\n return null;\n}\n\n/**\n * Discover boundary files (not-found, forbidden, unauthorized) at each layout directory.\n * Returns an array aligned with the layouts array, where each entry is the boundary\n * file at that layout's directory, or null if none exists there.\n *\n * This is used for per-layout error boundaries. In Next.js, each layout level\n * has its own boundary that wraps the layout's children. When notFound() is thrown\n * from a layout, it propagates up to the parent layout's boundary.\n */\nfunction discoverBoundaryFilePerLayout(\n layouts: string[],\n fileName: string,\n matcher: ValidFileMatcher,\n): (string | null)[] {\n return layouts.map((layoutPath) => {\n const layoutDir = path.dirname(layoutPath);\n return findFile(layoutDir, fileName, matcher);\n });\n}\n\n/**\n * Discover parallel slots inherited from ancestor directories.\n *\n * In Next.js, parallel slots belong to the layout that defines them. When a\n * child route is rendered, its parent layout's slots must still be present.\n * If the child doesn't have matching content in a slot, the slot's default.tsx\n * is rendered instead.\n *\n * Walk from appDir through each segment to the route's directory. At each level\n * that has @slot dirs, collect them. Slots at the route's own directory level\n * use page.tsx; slots at ancestor levels use default.tsx only.\n */\nfunction discoverInheritedParallelSlots(\n segments: string[],\n appDir: string,\n routeDir: string,\n matcher: ValidFileMatcher,\n): ParallelSlot[] {\n const slotMap = new Map<string, ParallelSlot>();\n\n // Walk from appDir through each segment, tracking layout indices.\n // layoutIndex tracks which position in the route's layouts[] array corresponds\n // to a given directory. Only directories with a layout.tsx file increment.\n let currentDir = appDir;\n const dirsToCheck: { dir: string; layoutIdx: number }[] = [];\n let layoutIdx = findFile(appDir, \"layout\", matcher) ? 0 : -1;\n dirsToCheck.push({ dir: appDir, layoutIdx: Math.max(layoutIdx, 0) });\n\n for (const segment of segments) {\n currentDir = path.join(currentDir, segment);\n if (findFile(currentDir, \"layout\", matcher)) {\n layoutIdx++;\n }\n dirsToCheck.push({ dir: currentDir, layoutIdx: Math.max(layoutIdx, 0) });\n }\n\n for (const { dir, layoutIdx: lvlLayoutIdx } of dirsToCheck) {\n const isOwnDir = dir === routeDir;\n const slotsAtLevel = discoverParallelSlots(dir, appDir, matcher);\n\n for (const slot of slotsAtLevel) {\n if (isOwnDir) {\n // At the route's own directory: use page.tsx (normal behavior)\n slot.layoutIndex = lvlLayoutIdx;\n slotMap.set(slot.name, slot);\n } else {\n // At an ancestor directory: use default.tsx as the page, not page.tsx\n // (the slot's page.tsx is for the parent route, not this child route)\n const inheritedSlot: ParallelSlot = {\n ...slot,\n pagePath: null, // Don't use ancestor's page.tsx\n layoutIndex: lvlLayoutIdx,\n // defaultPath, loadingPath, errorPath, interceptingRoutes remain\n };\n // Iteration goes root-to-leaf, so later (closer) ancestors overwrite\n // earlier (farther) ones — the closest ancestor's slot wins.\n slotMap.set(slot.name, inheritedSlot);\n }\n }\n }\n\n return Array.from(slotMap.values());\n}\n\n/**\n * Discover parallel route slots (@team, @analytics, etc.) in a directory.\n * Returns a ParallelSlot for each @-prefixed subdirectory that has a page or default component.\n */\nfunction discoverParallelSlots(\n dir: string,\n appDir: string,\n matcher: ValidFileMatcher,\n): ParallelSlot[] {\n if (!fs.existsSync(dir)) return [];\n\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n const slots: ParallelSlot[] = [];\n\n for (const entry of entries) {\n if (!entry.isDirectory() || !entry.name.startsWith(\"@\")) continue;\n\n const slotName = entry.name.slice(1); // \"@team\" -> \"team\"\n const slotDir = path.join(dir, entry.name);\n\n const pagePath = findFile(slotDir, \"page\", matcher);\n const defaultPath = findFile(slotDir, \"default\", matcher);\n const interceptingRoutes = discoverInterceptingRoutes(slotDir, dir, appDir, matcher);\n\n // Only include slots that have at least a page, default, or intercepting route\n if (!pagePath && !defaultPath && interceptingRoutes.length === 0) continue;\n\n slots.push({\n name: slotName,\n ownerDir: slotDir,\n pagePath,\n defaultPath,\n layoutPath: findFile(slotDir, \"layout\", matcher),\n loadingPath: findFile(slotDir, \"loading\", matcher),\n errorPath: findFile(slotDir, \"error\", matcher),\n interceptingRoutes,\n layoutIndex: -1, // Will be set by discoverInheritedParallelSlots\n });\n }\n\n return slots;\n}\n\n/**\n * The interception convention prefix patterns.\n * (.) — same level, (..) — one level up, (..)(..)\" — two levels up, (...) — root\n */\nconst INTERCEPT_PATTERNS = [\n { prefix: \"(...)\", convention: \"...\" },\n { prefix: \"(..)(..)\", convention: \"../..\" },\n { prefix: \"(..)\", convention: \"..\" },\n { prefix: \"(.)\", convention: \".\" },\n] as const;\n\n/**\n * Discover intercepting routes inside a parallel slot directory.\n *\n * Intercepting routes use conventions like (.)photo, (..)feed, (...), etc.\n * They intercept navigation to another route and render within the slot instead.\n *\n * @param slotDir - The parallel slot directory (e.g. app/feed/@modal)\n * @param routeDir - The directory of the route that owns this slot (e.g. app/feed)\n * @param appDir - The root app directory\n */\nfunction discoverInterceptingRoutes(\n slotDir: string,\n routeDir: string,\n appDir: string,\n matcher: ValidFileMatcher,\n): InterceptingRoute[] {\n if (!fs.existsSync(slotDir)) return [];\n\n const results: InterceptingRoute[] = [];\n\n // Recursively scan for page files inside intercepting directories\n scanForInterceptingPages(slotDir, routeDir, appDir, results, matcher);\n\n return results;\n}\n\n/**\n * Recursively scan a directory tree for page.tsx files that are inside\n * intercepting route directories.\n */\nfunction scanForInterceptingPages(\n currentDir: string,\n routeDir: string,\n appDir: string,\n results: InterceptingRoute[],\n matcher: ValidFileMatcher,\n): void {\n if (!fs.existsSync(currentDir)) return;\n\n const entries = fs.readdirSync(currentDir, { withFileTypes: true });\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n // Skip private folders (prefixed with _)\n if (entry.name.startsWith(\"_\")) continue;\n\n // Check if this directory name starts with an interception convention\n const interceptMatch = matchInterceptConvention(entry.name);\n\n if (interceptMatch) {\n // This directory is the start of an intercepting route\n // e.g. \"(.)photos\" means intercept same-level \"photos\" route\n const restOfName = entry.name.slice(interceptMatch.prefix.length);\n const interceptDir = path.join(currentDir, entry.name);\n\n // Find page files within this intercepting directory tree\n collectInterceptingPages(\n interceptDir,\n interceptDir,\n interceptMatch.convention,\n restOfName,\n routeDir,\n appDir,\n results,\n matcher,\n );\n } else {\n // Regular subdirectory — keep scanning for intercepting dirs\n scanForInterceptingPages(\n path.join(currentDir, entry.name),\n routeDir,\n appDir,\n results,\n matcher,\n );\n }\n }\n}\n\n/**\n * Match a directory name against interception convention prefixes.\n */\nfunction matchInterceptConvention(name: string): { prefix: string; convention: string } | null {\n for (const pattern of INTERCEPT_PATTERNS) {\n if (name.startsWith(pattern.prefix)) {\n return pattern;\n }\n }\n return null;\n}\n\n/**\n * Collect page.tsx files inside an intercepting route directory tree\n * and compute their target URL patterns.\n */\nfunction collectInterceptingPages(\n currentDir: string,\n interceptRoot: string,\n convention: string,\n interceptSegment: string,\n routeDir: string,\n appDir: string,\n results: InterceptingRoute[],\n matcher: ValidFileMatcher,\n): void {\n // Check for page.tsx in current directory\n const page = findFile(currentDir, \"page\", matcher);\n if (page) {\n const targetPattern = computeInterceptTarget(\n convention,\n interceptSegment,\n currentDir,\n interceptRoot,\n routeDir,\n appDir,\n );\n if (targetPattern) {\n results.push({\n convention,\n targetPattern: targetPattern.pattern,\n pagePath: page,\n params: targetPattern.params,\n });\n }\n }\n\n // Recurse into subdirectories for nested intercepting routes\n if (!fs.existsSync(currentDir)) return;\n const entries = fs.readdirSync(currentDir, { withFileTypes: true });\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n // Skip private folders (prefixed with _)\n if (entry.name.startsWith(\"_\")) continue;\n collectInterceptingPages(\n path.join(currentDir, entry.name),\n interceptRoot,\n convention,\n interceptSegment,\n routeDir,\n appDir,\n results,\n matcher,\n );\n }\n}\n\n/**\n * Check whether a path segment is invisible in the URL (route groups, parallel slots, \".\").\n *\n * Used by computeInterceptTarget, convertSegmentsToRouteParts, and\n * hasRemainingVisibleSegments — keep this the single source of truth.\n */\nfunction isInvisibleSegment(segment: string): boolean {\n if (segment === \".\") return true;\n if (segment.startsWith(\"(\") && segment.endsWith(\")\")) return true;\n if (segment.startsWith(\"@\")) return true;\n return false;\n}\n\n/**\n * Compute the target URL pattern for an intercepting route.\n *\n * Interception conventions (..), (..)(..)\" climb by *visible route segments*\n * (not filesystem directories). Route groups like (marketing) and parallel\n * slots like @modal are invisible and must be skipped when counting levels.\n *\n * - (.) same level: resolve relative to routeDir\n * - (..) one level up: climb 1 visible segment\n * - (..)(..) two levels up: climb 2 visible segments\n * - (...) root: resolve from appDir\n */\nfunction computeInterceptTarget(\n convention: string,\n interceptSegment: string,\n currentDir: string,\n interceptRoot: string,\n routeDir: string,\n appDir: string,\n): { pattern: string; params: string[] } | null {\n // Determine the base segments for target resolution.\n // We work on route segments (not filesystem paths) so that route groups\n // and parallel slots are properly skipped when climbing.\n const routeSegments = path.relative(appDir, routeDir).split(path.sep).filter(Boolean);\n\n let baseParts: string[];\n switch (convention) {\n case \".\":\n baseParts = routeSegments;\n break;\n case \"..\":\n case \"../..\": {\n const levelsToClimb = convention === \"..\" ? 1 : 2;\n let climbed = 0;\n let cutIndex = routeSegments.length;\n while (cutIndex > 0 && climbed < levelsToClimb) {\n cutIndex--;\n if (!isInvisibleSegment(routeSegments[cutIndex])) {\n climbed++;\n }\n }\n baseParts = routeSegments.slice(0, cutIndex);\n break;\n }\n case \"...\":\n baseParts = [];\n break;\n default:\n return null;\n }\n\n // Add the intercept segment and any nested path segments\n const nestedParts = path.relative(interceptRoot, currentDir).split(path.sep).filter(Boolean);\n const allSegments = [...baseParts, interceptSegment, ...nestedParts];\n\n const convertedTarget = convertSegmentsToRouteParts(allSegments);\n if (!convertedTarget) return null;\n\n const { urlSegments, params } = convertedTarget;\n\n const pattern = \"/\" + urlSegments.join(\"/\");\n return { pattern: pattern === \"/\" ? \"/\" : pattern, params };\n}\n\n/**\n * Find a file by name (without extension) in a directory.\n * Checks configured pageExtensions.\n */\nfunction findFile(dir: string, name: string, matcher: ValidFileMatcher): string | null {\n for (const ext of matcher.dottedExtensions) {\n const filePath = path.join(dir, name + ext);\n if (fs.existsSync(filePath)) return filePath;\n }\n return null;\n}\n\n/**\n * Convert filesystem path segments to URL route parts, skipping invisible segments\n * (route groups, @slots, \".\") and converting dynamic segment syntax to Express-style\n * patterns (e.g. \"[id]\" → \":id\", \"[...slug]\" → \":slug+\").\n */\nfunction convertSegmentsToRouteParts(\n segments: string[],\n): { urlSegments: string[]; params: string[]; isDynamic: boolean } | null {\n const urlSegments: string[] = [];\n const params: string[] = [];\n let isDynamic = false;\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n\n if (isInvisibleSegment(segment)) continue;\n\n // Catch-all segments are only valid in terminal URL position.\n const catchAllMatch = segment.match(/^\\[\\.\\.\\.([\\w-]+)\\]$/);\n if (catchAllMatch) {\n if (hasRemainingVisibleSegments(segments, i + 1)) return null;\n isDynamic = true;\n params.push(catchAllMatch[1]);\n urlSegments.push(`:${catchAllMatch[1]}+`);\n continue;\n }\n\n const optionalCatchAllMatch = segment.match(/^\\[\\[\\.\\.\\.([\\w-]+)\\]\\]$/);\n if (optionalCatchAllMatch) {\n if (hasRemainingVisibleSegments(segments, i + 1)) return null;\n isDynamic = true;\n params.push(optionalCatchAllMatch[1]);\n urlSegments.push(`:${optionalCatchAllMatch[1]}*`);\n continue;\n }\n\n const dynamicMatch = segment.match(/^\\[([\\w-]+)\\]$/);\n if (dynamicMatch) {\n isDynamic = true;\n params.push(dynamicMatch[1]);\n urlSegments.push(`:${dynamicMatch[1]}`);\n continue;\n }\n\n urlSegments.push(decodeRouteSegment(segment));\n }\n\n return { urlSegments, params, isDynamic };\n}\n\nfunction hasRemainingVisibleSegments(segments: string[], startIndex: number): boolean {\n for (let i = startIndex; i < segments.length; i++) {\n if (!isInvisibleSegment(segments[i])) return true;\n }\n return false;\n}\n\n// Trie cache — keyed by route array identity (same array = same trie)\nconst appTrieCache = new WeakMap<AppRoute[], TrieNode<AppRoute>>();\n\nfunction getOrBuildAppTrie(routes: AppRoute[]): TrieNode<AppRoute> {\n let trie = appTrieCache.get(routes);\n if (!trie) {\n trie = buildRouteTrie(routes);\n appTrieCache.set(routes, trie);\n }\n return trie;\n}\n\nfunction joinRoutePattern(basePattern: string, subPath: string): string {\n if (!subPath) return basePattern;\n return basePattern === \"/\" ? `/${subPath}` : `${basePattern}/${subPath}`;\n}\n\n/**\n * Match a URL against App Router routes.\n */\nexport function matchAppRoute(\n url: string,\n routes: AppRoute[],\n): { route: AppRoute; params: Record<string, string | string[]> } | null {\n const pathname = url.split(\"?\")[0];\n let normalizedUrl = pathname === \"/\" ? \"/\" : pathname.replace(/\\/$/, \"\");\n normalizedUrl = normalizePathnameForRouteMatch(normalizedUrl);\n\n // Split URL once, look up via trie\n const urlParts = normalizedUrl.split(\"/\").filter(Boolean);\n const trie = getOrBuildAppTrie(routes);\n return trieMatch(trie, urlParts);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA2HA,IAAI,eAAkC;AACtC,IAAI,eAA8B;AAClC,IAAI,0BAAyC;AAE7C,SAAgB,0BAAgC;AAC9C,gBAAe;AACf,gBAAe;AACf,2BAA0B;;;;;AAM5B,eAAsB,UACpB,QACA,gBACA,SACqB;AACrB,aAAY,uBAAuB,eAAe;CAClD,MAAM,oBAAoB,KAAK,UAAU,QAAQ,WAAW;AAC5D,KAAI,gBAAgB,iBAAiB,UAAU,4BAA4B,kBACzE,QAAO;CAMT,MAAM,SAAqB,EAAE;CAE7B,MAAM,cAAc,SAAiB,KAAK,WAAW,IAAI,IAAI,KAAK,WAAW,IAAI;AAIjF,YAAW,MAAM,QAAQ,mBAAmB,WAAW,QAAQ,QAAQ,YAAY,WAAW,EAAE;EAC9F,MAAM,QAAQ,eAAe,MAAM,QAAQ,QAAQ,QAAQ;AAC3D,MAAI,MAAO,QAAO,KAAK,MAAM;;AAI/B,YAAW,MAAM,QAAQ,mBAAmB,YAAY,QAAQ,QAAQ,YAAY,WAAW,EAAE;EAC/F,MAAM,QAAQ,eAAe,MAAM,QAAQ,SAAS,QAAQ;AAC5D,MAAI,MAAO,QAAO,KAAK,MAAM;;CAO/B,MAAM,gBAAgB,sBAAsB,QAAQ,QAAQ,QAAQ;AACpE,QAAO,KAAK,GAAG,cAAc;AAE7B,uBAAsB,OAAO,KAAK,UAAU,MAAM,QAAQ,CAAC;AAC3D,uBACE,OAAO,SAAS,UACd,MAAM,cAAc,SAAS,SAC3B,KAAK,mBAAmB,KAAK,cA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esContent":["/**\n * App Router file-system routing.\n *\n * Scans the app/ directory following Next.js App Router conventions:\n * - app/page.tsx -> /\n * - app/about/page.tsx -> /about\n * - app/blog/[slug]/page.tsx -> /blog/:slug\n * - app/[...catchAll]/page.tsx -> /:catchAll+\n * - app/route.ts -> / (API route)\n * - app/(group)/page.tsx -> / (route groups are transparent)\n * - Layouts: app/layout.tsx wraps all children\n * - Loading: app/loading.tsx -> Suspense fallback\n * - Error: app/error.tsx -> ErrorBoundary\n * - Not Found: app/not-found.tsx\n */\nimport path from \"node:path\";\nimport fs from \"node:fs\";\nimport { compareRoutes, decodeRouteSegment, normalizePathnameForRouteMatch } from \"./utils.js\";\nimport {\n createValidFileMatcher,\n scanWithExtensions,\n type ValidFileMatcher,\n} from \"./file-matcher.js\";\nimport { validateRoutePatterns } from \"./route-validation.js\";\nimport { buildRouteTrie, trieMatch, type TrieNode } from \"./route-trie.js\";\n\nexport type InterceptingRoute = {\n /** The interception convention: \".\" | \"..\" | \"../..\" | \"...\" */\n convention: string;\n /** The URL pattern this intercepts (e.g. \"/photos/:id\") */\n targetPattern: string;\n /** Absolute path to the intercepting page component */\n pagePath: string;\n /** Parameter names for dynamic segments */\n params: string[];\n};\n\nexport type ParallelSlot = {\n /** Slot name (e.g. \"team\" from @team) */\n name: string;\n /** Absolute path to the @slot directory that owns this slot. Internal routing metadata. */\n ownerDir: string;\n /** Absolute path to the slot's page component */\n pagePath: string | null;\n /** Absolute path to the slot's default.tsx fallback */\n defaultPath: string | null;\n /** Absolute path to the slot's layout component (wraps slot content) */\n layoutPath: string | null;\n /** Absolute path to the slot's loading component */\n loadingPath: string | null;\n /** Absolute path to the slot's error component */\n errorPath: string | null;\n /** Intercepting routes within this slot */\n interceptingRoutes: InterceptingRoute[];\n /**\n * The layout index (0-based, in route.layouts[]) that this slot belongs to.\n * Slots are passed as props to the layout at their directory level, not\n * necessarily the innermost layout. -1 means \"innermost\" (legacy default).\n */\n layoutIndex: number;\n};\n\nexport type AppRoute = {\n /** URL pattern, e.g. \"/\" or \"/about\" or \"/blog/:slug\" */\n pattern: string;\n /** Absolute file path to the page component */\n pagePath: string | null;\n /** Absolute file path to the route handler (route.ts) */\n routePath: string | null;\n /** Ordered list of layout files from root to leaf */\n layouts: string[];\n /** Ordered list of template files from root to leaf (parallel to layouts) */\n templates: string[];\n /** Parallel route slots (from @slot directories at the route's directory level) */\n parallelSlots: ParallelSlot[];\n /** Loading component path */\n loadingPath: string | null;\n /** Error component path (leaf directory only) */\n errorPath: string | null;\n /**\n * Per-layout error boundary paths, aligned with the layouts array.\n * Each entry is the error.tsx at the same directory level as the\n * corresponding layout (or null if that level has no error.tsx).\n * Used to interleave ErrorBoundary components with layouts so that\n * ancestor error boundaries catch errors from descendant segments.\n */\n layoutErrorPaths: (string | null)[];\n /** Not-found component path (nearest, walking up from page dir) */\n notFoundPath: string | null;\n /**\n * Not-found component paths per layout level (aligned with layouts array).\n * Each entry is the not-found.tsx at that layout's directory, or null.\n * Used to create per-layout NotFoundBoundary so that notFound() thrown from\n * a layout is caught by the parent layout's boundary (matching Next.js behavior).\n */\n notFoundPaths: (string | null)[];\n /** Forbidden component path (403) */\n forbiddenPath: string | null;\n /** Unauthorized component path (401) */\n unauthorizedPath: string | null;\n /**\n * Filesystem segments from app/ root to the route's directory.\n * Includes route groups and dynamic segments (as template strings like \"[id]\").\n * Used at render time to compute the child segments for useSelectedLayoutSegments().\n */\n routeSegments: string[];\n /**\n * Tree position (directory depth from app/ root) for each layout.\n * Used to slice routeSegments and determine which segments are below each layout.\n * For example, root layout = 0, a layout at app/blog/ = 1, app/blog/(group)/ = 2.\n * Unlike the old layoutSegmentDepths, this counts ALL directory levels including\n * route groups and parallel slots.\n */\n layoutTreePositions: number[];\n /** Whether this is a dynamic route */\n isDynamic: boolean;\n /** Parameter names for dynamic segments */\n params: string[];\n /** Pre-split pattern segments (computed once at scan time, reused per request) */\n patternParts: string[];\n};\n\n// Cache for app routes\nlet cachedRoutes: AppRoute[] | null = null;\nlet cachedAppDir: string | null = null;\nlet cachedPageExtensionsKey: string | null = null;\n\nexport function invalidateAppRouteCache(): void {\n cachedRoutes = null;\n cachedAppDir = null;\n cachedPageExtensionsKey = null;\n}\n\n/**\n * Scan the app/ directory and return a list of routes.\n */\nexport async function appRouter(\n appDir: string,\n pageExtensions?: readonly string[],\n matcher?: ValidFileMatcher,\n): Promise<AppRoute[]> {\n matcher ??= createValidFileMatcher(pageExtensions);\n const pageExtensionsKey = JSON.stringify(matcher.extensions);\n if (cachedRoutes && cachedAppDir === appDir && cachedPageExtensionsKey === pageExtensionsKey) {\n return cachedRoutes;\n }\n\n // Find all page.tsx and route.ts files, excluding @slot directories\n // (slot pages are not standalone routes — they're rendered as props of their parent layout)\n // and _private folders (Next.js convention for colocated non-route files).\n const routes: AppRoute[] = [];\n\n const excludeDir = (name: string) => name.startsWith(\"@\") || name.startsWith(\"_\");\n\n // Process page files in a single pass\n // Use function form of exclude for Node < 22.14 compatibility (string arrays require >= 22.14)\n for await (const file of scanWithExtensions(\"**/page\", appDir, matcher.extensions, excludeDir)) {\n const route = fileToAppRoute(file, appDir, \"page\", matcher);\n if (route) routes.push(route);\n }\n\n // Process route handler files (API routes) in a single pass\n for await (const file of scanWithExtensions(\"**/route\", appDir, matcher.extensions, excludeDir)) {\n const route = fileToAppRoute(file, appDir, \"route\", matcher);\n if (route) routes.push(route);\n }\n\n // Discover sub-routes created by nested pages within parallel slots.\n // In Next.js, pages nested inside @slot directories create additional URL routes.\n // For example, @audience/demographics/page.tsx at app/parallel-routes/ creates\n // a route at /parallel-routes/demographics.\n const slotSubRoutes = discoverSlotSubRoutes(routes, appDir, matcher);\n routes.push(...slotSubRoutes);\n\n validateRoutePatterns(routes.map((route) => route.pattern));\n validateRoutePatterns(\n routes.flatMap((route) =>\n route.parallelSlots.flatMap((slot) =>\n slot.interceptingRoutes.map((intercept) => intercept.targetPattern),\n ),\n ),\n );\n\n // Sort: static routes first, then dynamic, then catch-all\n routes.sort(compareRoutes);\n\n cachedRoutes = routes;\n cachedAppDir = appDir;\n cachedPageExtensionsKey = pageExtensionsKey;\n return routes;\n}\n\n/**\n * Discover sub-routes created by nested pages within parallel slots.\n *\n * In Next.js, pages nested inside @slot directories create additional URL routes.\n * For example, given:\n * app/parallel-routes/@audience/demographics/page.tsx\n * This creates a route at /parallel-routes/demographics where:\n * - children slot → parent's default.tsx\n * - @audience slot → @audience/demographics/page.tsx (matched)\n * - other slots → their default.tsx (fallback)\n */\nfunction discoverSlotSubRoutes(\n routes: AppRoute[],\n _appDir: string,\n matcher: ValidFileMatcher,\n): AppRoute[] {\n const syntheticRoutes: AppRoute[] = [];\n\n // O(1) lookup for existing routes by pattern — avoids O(n) routes.find() per sub-path per parent.\n // Updated as new synthetic routes are pushed so that later parents can see earlier synthetic entries.\n const routesByPattern = new Map<string, AppRoute>(routes.map((r) => [r.pattern, r]));\n\n const slotKey = (slotName: string, ownerDir: string): string => `${slotName}\\u0000${ownerDir}`;\n\n const applySlotSubPages = (route: AppRoute, slotPages: Map<string, string>): void => {\n route.parallelSlots = route.parallelSlots.map((slot) => ({\n ...slot,\n pagePath: slotPages.get(slotKey(slot.name, slot.ownerDir)) ?? slot.pagePath,\n }));\n };\n\n for (const parentRoute of routes) {\n if (parentRoute.parallelSlots.length === 0) continue;\n if (!parentRoute.pagePath) continue;\n\n const parentPageDir = path.dirname(parentRoute.pagePath);\n\n // Collect sub-paths from all slots.\n // Map: normalized visible sub-path -> slot pages, raw filesystem segments (for routeSegments),\n // and the pre-computed convertedSubRoute (to avoid a redundant re-conversion in the merge loop).\n const subPathMap = new Map<\n string,\n {\n // Raw filesystem segments (with route groups, @slots, etc.) used for routeSegments so\n // that useSelectedLayoutSegments() sees the correct segment list at runtime.\n rawSegments: string[];\n // Pre-computed URL parts, params, isDynamic from convertSegmentsToRouteParts.\n converted: { urlSegments: string[]; params: string[]; isDynamic: boolean };\n slotPages: Map<string, string>;\n }\n >();\n\n for (const slot of parentRoute.parallelSlots) {\n const slotDir = path.join(parentPageDir, `@${slot.name}`);\n if (!fs.existsSync(slotDir)) continue;\n\n const subPages = findSlotSubPages(slotDir, matcher);\n for (const { relativePath, pagePath } of subPages) {\n const subSegments = relativePath.split(path.sep);\n const convertedSubRoute = convertSegmentsToRouteParts(subSegments);\n if (!convertedSubRoute) continue;\n\n const { urlSegments } = convertedSubRoute;\n const normalizedSubPath = urlSegments.join(\"/\");\n let subPathEntry = subPathMap.get(normalizedSubPath);\n\n if (!subPathEntry) {\n subPathEntry = {\n rawSegments: subSegments,\n converted: convertedSubRoute,\n slotPages: new Map(),\n };\n subPathMap.set(normalizedSubPath, subPathEntry);\n }\n\n const slotId = slotKey(slot.name, slot.ownerDir);\n const existingSlotPage = subPathEntry.slotPages.get(slotId);\n if (existingSlotPage) {\n const pattern = joinRoutePattern(parentRoute.pattern, normalizedSubPath);\n throw new Error(\n `You cannot have two routes that resolve to the same path (\"${pattern}\").`,\n );\n }\n\n subPathEntry.slotPages.set(slotId, pagePath);\n }\n }\n\n if (subPathMap.size === 0) continue;\n\n // Find the default.tsx for the children slot at the parent directory\n const childrenDefault = findFile(parentPageDir, \"default\", matcher);\n if (!childrenDefault) continue;\n\n for (const { rawSegments, converted: convertedSubRoute, slotPages } of subPathMap.values()) {\n const {\n urlSegments: urlParts,\n params: subParams,\n isDynamic: subIsDynamic,\n } = convertedSubRoute;\n\n const subUrlPath = urlParts.join(\"/\");\n const pattern = joinRoutePattern(parentRoute.pattern, subUrlPath);\n\n const existingRoute = routesByPattern.get(pattern);\n if (existingRoute) {\n if (existingRoute.routePath && !existingRoute.pagePath) {\n throw new Error(\n `You cannot have two routes that resolve to the same path (\"${pattern}\").`,\n );\n }\n applySlotSubPages(existingRoute, slotPages);\n continue;\n }\n\n // Build parallel slots for this sub-route: matching slots get the sub-page,\n // non-matching slots get null pagePath (rendering falls back to defaultPath)\n const subSlots: ParallelSlot[] = parentRoute.parallelSlots.map((slot) => ({\n ...slot,\n pagePath: slotPages.get(slotKey(slot.name, slot.ownerDir)) || null,\n }));\n\n const newRoute: AppRoute = {\n pattern,\n pagePath: childrenDefault, // children slot uses parent's default.tsx as page\n routePath: null,\n layouts: parentRoute.layouts,\n templates: parentRoute.templates,\n parallelSlots: subSlots,\n loadingPath: parentRoute.loadingPath,\n errorPath: parentRoute.errorPath,\n layoutErrorPaths: parentRoute.layoutErrorPaths,\n notFoundPath: parentRoute.notFoundPath,\n notFoundPaths: parentRoute.notFoundPaths,\n forbiddenPath: parentRoute.forbiddenPath,\n unauthorizedPath: parentRoute.unauthorizedPath,\n routeSegments: [...parentRoute.routeSegments, ...rawSegments],\n layoutTreePositions: parentRoute.layoutTreePositions,\n isDynamic: parentRoute.isDynamic || subIsDynamic,\n params: [...parentRoute.params, ...subParams],\n patternParts: [...parentRoute.patternParts, ...urlParts],\n };\n syntheticRoutes.push(newRoute);\n routesByPattern.set(pattern, newRoute);\n }\n }\n\n return syntheticRoutes;\n}\n\n/**\n * Find all page files in subdirectories of a parallel slot directory.\n * Returns relative paths (from the slot dir) and absolute page paths.\n * Skips the root page.tsx (already handled as the slot's main page)\n * and intercepting route directories.\n */\nfunction findSlotSubPages(\n slotDir: string,\n matcher: ValidFileMatcher,\n): Array<{ relativePath: string; pagePath: string }> {\n const results: Array<{ relativePath: string; pagePath: string }> = [];\n\n function scan(dir: string): void {\n if (!fs.existsSync(dir)) return;\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n // Skip intercepting route directories\n if (matchInterceptConvention(entry.name)) continue;\n // Skip private folders (prefixed with _)\n if (entry.name.startsWith(\"_\")) continue;\n\n const subDir = path.join(dir, entry.name);\n const page = findFile(subDir, \"page\", matcher);\n if (page) {\n const relativePath = path.relative(slotDir, subDir);\n results.push({ relativePath, pagePath: page });\n }\n // Continue scanning deeper for nested sub-pages\n scan(subDir);\n }\n }\n\n scan(slotDir);\n return results;\n}\n\n/**\n * Convert a file path relative to app/ into an AppRoute.\n */\nfunction fileToAppRoute(\n file: string,\n appDir: string,\n type: \"page\" | \"route\",\n matcher: ValidFileMatcher,\n): AppRoute | null {\n // Remove the filename (page.tsx or route.ts)\n const dir = path.dirname(file);\n const segments = dir === \".\" ? [] : dir.split(path.sep);\n\n const params: string[] = [];\n let isDynamic = false;\n\n const convertedRoute = convertSegmentsToRouteParts(segments);\n if (!convertedRoute) return null;\n\n const { urlSegments, params: routeParams, isDynamic: routeIsDynamic } = convertedRoute;\n params.push(...routeParams);\n isDynamic = routeIsDynamic;\n\n const pattern = \"/\" + urlSegments.join(\"/\");\n\n // Discover layouts and templates from root to leaf\n const layouts = discoverLayouts(segments, appDir, matcher);\n const templates = discoverTemplates(segments, appDir, matcher);\n\n // Compute the tree position (directory depth) for each layout.\n const layoutTreePositions = computeLayoutTreePositions(appDir, layouts);\n\n // Discover per-layout error boundaries (aligned with layouts array).\n // In Next.js, each segment independently wraps its children with an ErrorBoundary.\n // This array enables interleaving error boundaries with layouts in the rendering.\n const layoutErrorPaths = discoverLayoutAlignedErrors(segments, appDir, matcher);\n\n // Discover loading, error in the route's directory\n const routeDir = dir === \".\" ? appDir : path.join(appDir, dir);\n const loadingPath = findFile(routeDir, \"loading\", matcher);\n const errorPath = findFile(routeDir, \"error\", matcher);\n\n // Discover not-found/forbidden/unauthorized: walk from route directory up to root (nearest wins).\n const notFoundPath = discoverBoundaryFile(segments, appDir, \"not-found\", matcher);\n const forbiddenPath = discoverBoundaryFile(segments, appDir, \"forbidden\", matcher);\n const unauthorizedPath = discoverBoundaryFile(segments, appDir, \"unauthorized\", matcher);\n\n // Discover per-layout not-found files (one per layout directory).\n // These are used for per-layout NotFoundBoundary to match Next.js behavior where\n // notFound() thrown from a layout is caught by the parent layout's boundary.\n const notFoundPaths = discoverBoundaryFilePerLayout(layouts, \"not-found\", matcher);\n\n // Discover parallel slots (@team, @analytics, etc.).\n // Slots at the route's own directory use page.tsx; slots at ancestor directories\n // (inherited from parent layouts) use default.tsx as fallback.\n const parallelSlots = discoverInheritedParallelSlots(segments, appDir, routeDir, matcher);\n\n return {\n pattern: pattern === \"/\" ? \"/\" : pattern,\n pagePath: type === \"page\" ? path.join(appDir, file) : null,\n routePath: type === \"route\" ? path.join(appDir, file) : null,\n layouts,\n templates,\n parallelSlots,\n loadingPath,\n errorPath,\n layoutErrorPaths,\n notFoundPath,\n notFoundPaths,\n forbiddenPath,\n unauthorizedPath,\n routeSegments: segments,\n layoutTreePositions,\n isDynamic,\n params,\n patternParts: urlSegments,\n };\n}\n\n/**\n * Compute the tree position (directory depth from app root) for each layout.\n * Root layout = 0, a layout at app/blog/ = 1, app/blog/(group)/ = 2.\n * Counts ALL directory levels including route groups and parallel slots.\n */\nfunction computeLayoutTreePositions(appDir: string, layouts: string[]): number[] {\n return layouts.map((layoutPath) => {\n const layoutDir = path.dirname(layoutPath);\n if (layoutDir === appDir) return 0;\n const relative = path.relative(appDir, layoutDir);\n return relative.split(path.sep).length;\n });\n}\n\n/**\n * Discover all layout files from root to the given directory.\n * Each level of the directory tree may have a layout.tsx.\n */\nfunction discoverLayouts(segments: string[], appDir: string, matcher: ValidFileMatcher): string[] {\n const layouts: string[] = [];\n\n // Check root layout\n const rootLayout = findFile(appDir, \"layout\", matcher);\n if (rootLayout) layouts.push(rootLayout);\n\n // Check each directory level\n let currentDir = appDir;\n for (const segment of segments) {\n currentDir = path.join(currentDir, segment);\n const layout = findFile(currentDir, \"layout\", matcher);\n if (layout) layouts.push(layout);\n }\n\n return layouts;\n}\n\n/**\n * Discover all template files from root to the given directory.\n * Each level of the directory tree may have a template.tsx.\n * Templates are like layouts but re-mount on navigation.\n */\nfunction discoverTemplates(\n segments: string[],\n appDir: string,\n matcher: ValidFileMatcher,\n): string[] {\n const templates: string[] = [];\n\n // Check root template\n const rootTemplate = findFile(appDir, \"template\", matcher);\n if (rootTemplate) templates.push(rootTemplate);\n\n // Check each directory level\n let currentDir = appDir;\n for (const segment of segments) {\n currentDir = path.join(currentDir, segment);\n const template = findFile(currentDir, \"template\", matcher);\n if (template) templates.push(template);\n }\n\n return templates;\n}\n\n/**\n * Discover error.tsx files aligned with the layouts array.\n * Walks the same directory levels as discoverLayouts and, for each level\n * that contributes a layout entry, checks whether error.tsx also exists.\n * Returns an array of the same length as discoverLayouts() would return,\n * with the error path (or null) at each corresponding layout level.\n *\n * This enables interleaving ErrorBoundary components with layouts in the\n * rendering tree, matching Next.js behavior where each segment independently\n * wraps its children with an error boundary.\n */\nfunction discoverLayoutAlignedErrors(\n segments: string[],\n appDir: string,\n matcher: ValidFileMatcher,\n): (string | null)[] {\n const errors: (string | null)[] = [];\n\n // Root level (only if root has a layout — matching discoverLayouts logic)\n const rootLayout = findFile(appDir, \"layout\", matcher);\n if (rootLayout) {\n errors.push(findFile(appDir, \"error\", matcher));\n }\n\n // Check each directory level\n let currentDir = appDir;\n for (const segment of segments) {\n currentDir = path.join(currentDir, segment);\n const layout = findFile(currentDir, \"layout\", matcher);\n if (layout) {\n errors.push(findFile(currentDir, \"error\", matcher));\n }\n }\n\n return errors;\n}\n\n/**\n * Discover the nearest boundary file (not-found, forbidden, unauthorized)\n * by walking from the route's directory up to the app root.\n * Returns the first (closest) file found, or null.\n */\nfunction discoverBoundaryFile(\n segments: string[],\n appDir: string,\n fileName: string,\n matcher: ValidFileMatcher,\n): string | null {\n // Build all directory paths from leaf to root\n const dirs: string[] = [];\n let dir = appDir;\n dirs.push(dir);\n for (const segment of segments) {\n dir = path.join(dir, segment);\n dirs.push(dir);\n }\n\n // Walk from leaf (last) to root (first)\n for (let i = dirs.length - 1; i >= 0; i--) {\n const f = findFile(dirs[i], fileName, matcher);\n if (f) return f;\n }\n return null;\n}\n\n/**\n * Discover boundary files (not-found, forbidden, unauthorized) at each layout directory.\n * Returns an array aligned with the layouts array, where each entry is the boundary\n * file at that layout's directory, or null if none exists there.\n *\n * This is used for per-layout error boundaries. In Next.js, each layout level\n * has its own boundary that wraps the layout's children. When notFound() is thrown\n * from a layout, it propagates up to the parent layout's boundary.\n */\nfunction discoverBoundaryFilePerLayout(\n layouts: string[],\n fileName: string,\n matcher: ValidFileMatcher,\n): (string | null)[] {\n return layouts.map((layoutPath) => {\n const layoutDir = path.dirname(layoutPath);\n return findFile(layoutDir, fileName, matcher);\n });\n}\n\n/**\n * Discover parallel slots inherited from ancestor directories.\n *\n * In Next.js, parallel slots belong to the layout that defines them. When a\n * child route is rendered, its parent layout's slots must still be present.\n * If the child doesn't have matching content in a slot, the slot's default.tsx\n * is rendered instead.\n *\n * Walk from appDir through each segment to the route's directory. At each level\n * that has @slot dirs, collect them. Slots at the route's own directory level\n * use page.tsx; slots at ancestor levels use default.tsx only.\n */\nfunction discoverInheritedParallelSlots(\n segments: string[],\n appDir: string,\n routeDir: string,\n matcher: ValidFileMatcher,\n): ParallelSlot[] {\n const slotMap = new Map<string, ParallelSlot>();\n\n // Walk from appDir through each segment, tracking layout indices.\n // layoutIndex tracks which position in the route's layouts[] array corresponds\n // to a given directory. Only directories with a layout.tsx file increment.\n let currentDir = appDir;\n const dirsToCheck: { dir: string; layoutIdx: number }[] = [];\n let layoutIdx = findFile(appDir, \"layout\", matcher) ? 0 : -1;\n dirsToCheck.push({ dir: appDir, layoutIdx: Math.max(layoutIdx, 0) });\n\n for (const segment of segments) {\n currentDir = path.join(currentDir, segment);\n if (findFile(currentDir, \"layout\", matcher)) {\n layoutIdx++;\n }\n dirsToCheck.push({ dir: currentDir, layoutIdx: Math.max(layoutIdx, 0) });\n }\n\n for (const { dir, layoutIdx: lvlLayoutIdx } of dirsToCheck) {\n const isOwnDir = dir === routeDir;\n const slotsAtLevel = discoverParallelSlots(dir, appDir, matcher);\n\n for (const slot of slotsAtLevel) {\n if (isOwnDir) {\n // At the route's own directory: use page.tsx (normal behavior)\n slot.layoutIndex = lvlLayoutIdx;\n slotMap.set(slot.name, slot);\n } else {\n // At an ancestor directory: use default.tsx as the page, not page.tsx\n // (the slot's page.tsx is for the parent route, not this child route)\n const inheritedSlot: ParallelSlot = {\n ...slot,\n pagePath: null, // Don't use ancestor's page.tsx\n layoutIndex: lvlLayoutIdx,\n // defaultPath, loadingPath, errorPath, interceptingRoutes remain\n };\n // Iteration goes root-to-leaf, so later (closer) ancestors overwrite\n // earlier (farther) ones — the closest ancestor's slot wins.\n slotMap.set(slot.name, inheritedSlot);\n }\n }\n }\n\n return Array.from(slotMap.values());\n}\n\n/**\n * Discover parallel route slots (@team, @analytics, etc.) in a directory.\n * Returns a ParallelSlot for each @-prefixed subdirectory that has a page or default component.\n */\nfunction discoverParallelSlots(\n dir: string,\n appDir: string,\n matcher: ValidFileMatcher,\n): ParallelSlot[] {\n if (!fs.existsSync(dir)) return [];\n\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n const slots: ParallelSlot[] = [];\n\n for (const entry of entries) {\n if (!entry.isDirectory() || !entry.name.startsWith(\"@\")) continue;\n\n const slotName = entry.name.slice(1); // \"@team\" -> \"team\"\n const slotDir = path.join(dir, entry.name);\n\n const pagePath = findFile(slotDir, \"page\", matcher);\n const defaultPath = findFile(slotDir, \"default\", matcher);\n const interceptingRoutes = discoverInterceptingRoutes(slotDir, dir, appDir, matcher);\n\n // Only include slots that have at least a page, default, or intercepting route\n if (!pagePath && !defaultPath && interceptingRoutes.length === 0) continue;\n\n slots.push({\n name: slotName,\n ownerDir: slotDir,\n pagePath,\n defaultPath,\n layoutPath: findFile(slotDir, \"layout\", matcher),\n loadingPath: findFile(slotDir, \"loading\", matcher),\n errorPath: findFile(slotDir, \"error\", matcher),\n interceptingRoutes,\n layoutIndex: -1, // Will be set by discoverInheritedParallelSlots\n });\n }\n\n return slots;\n}\n\n/**\n * The interception convention prefix patterns.\n * (.) — same level, (..) — one level up, (..)(..)\" — two levels up, (...) — root\n */\nconst INTERCEPT_PATTERNS = [\n { prefix: \"(...)\", convention: \"...\" },\n { prefix: \"(..)(..)\", convention: \"../..\" },\n { prefix: \"(..)\", convention: \"..\" },\n { prefix: \"(.)\", convention: \".\" },\n] as const;\n\n/**\n * Discover intercepting routes inside a parallel slot directory.\n *\n * Intercepting routes use conventions like (.)photo, (..)feed, (...), etc.\n * They intercept navigation to another route and render within the slot instead.\n *\n * @param slotDir - The parallel slot directory (e.g. app/feed/@modal)\n * @param routeDir - The directory of the route that owns this slot (e.g. app/feed)\n * @param appDir - The root app directory\n */\nfunction discoverInterceptingRoutes(\n slotDir: string,\n routeDir: string,\n appDir: string,\n matcher: ValidFileMatcher,\n): InterceptingRoute[] {\n if (!fs.existsSync(slotDir)) return [];\n\n const results: InterceptingRoute[] = [];\n\n // Recursively scan for page files inside intercepting directories\n scanForInterceptingPages(slotDir, routeDir, appDir, results, matcher);\n\n return results;\n}\n\n/**\n * Recursively scan a directory tree for page.tsx files that are inside\n * intercepting route directories.\n */\nfunction scanForInterceptingPages(\n currentDir: string,\n routeDir: string,\n appDir: string,\n results: InterceptingRoute[],\n matcher: ValidFileMatcher,\n): void {\n if (!fs.existsSync(currentDir)) return;\n\n const entries = fs.readdirSync(currentDir, { withFileTypes: true });\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n // Skip private folders (prefixed with _)\n if (entry.name.startsWith(\"_\")) continue;\n\n // Check if this directory name starts with an interception convention\n const interceptMatch = matchInterceptConvention(entry.name);\n\n if (interceptMatch) {\n // This directory is the start of an intercepting route\n // e.g. \"(.)photos\" means intercept same-level \"photos\" route\n const restOfName = entry.name.slice(interceptMatch.prefix.length);\n const interceptDir = path.join(currentDir, entry.name);\n\n // Find page files within this intercepting directory tree\n collectInterceptingPages(\n interceptDir,\n interceptDir,\n interceptMatch.convention,\n restOfName,\n routeDir,\n appDir,\n results,\n matcher,\n );\n } else {\n // Regular subdirectory — keep scanning for intercepting dirs\n scanForInterceptingPages(\n path.join(currentDir, entry.name),\n routeDir,\n appDir,\n results,\n matcher,\n );\n }\n }\n}\n\n/**\n * Match a directory name against interception convention prefixes.\n */\nfunction matchInterceptConvention(name: string): { prefix: string; convention: string } | null {\n for (const pattern of INTERCEPT_PATTERNS) {\n if (name.startsWith(pattern.prefix)) {\n return pattern;\n }\n }\n return null;\n}\n\n/**\n * Collect page.tsx files inside an intercepting route directory tree\n * and compute their target URL patterns.\n */\nfunction collectInterceptingPages(\n currentDir: string,\n interceptRoot: string,\n convention: string,\n interceptSegment: string,\n routeDir: string,\n appDir: string,\n results: InterceptingRoute[],\n matcher: ValidFileMatcher,\n): void {\n // Check for page.tsx in current directory\n const page = findFile(currentDir, \"page\", matcher);\n if (page) {\n const targetPattern = computeInterceptTarget(\n convention,\n interceptSegment,\n currentDir,\n interceptRoot,\n routeDir,\n appDir,\n );\n if (targetPattern) {\n results.push({\n convention,\n targetPattern: targetPattern.pattern,\n pagePath: page,\n params: targetPattern.params,\n });\n }\n }\n\n // Recurse into subdirectories for nested intercepting routes\n if (!fs.existsSync(currentDir)) return;\n const entries = fs.readdirSync(currentDir, { withFileTypes: true });\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n // Skip private folders (prefixed with _)\n if (entry.name.startsWith(\"_\")) continue;\n collectInterceptingPages(\n path.join(currentDir, entry.name),\n interceptRoot,\n convention,\n interceptSegment,\n routeDir,\n appDir,\n results,\n matcher,\n );\n }\n}\n\n/**\n * Check whether a path segment is invisible in the URL (route groups, parallel slots, \".\").\n *\n * Used by computeInterceptTarget, convertSegmentsToRouteParts, and\n * hasRemainingVisibleSegments — keep this the single source of truth.\n */\nfunction isInvisibleSegment(segment: string): boolean {\n if (segment === \".\") return true;\n if (segment.startsWith(\"(\") && segment.endsWith(\")\")) return true;\n if (segment.startsWith(\"@\")) return true;\n return false;\n}\n\n/**\n * Compute the target URL pattern for an intercepting route.\n *\n * Interception conventions (..), (..)(..)\" climb by *visible route segments*\n * (not filesystem directories). Route groups like (marketing) and parallel\n * slots like @modal are invisible and must be skipped when counting levels.\n *\n * - (.) same level: resolve relative to routeDir\n * - (..) one level up: climb 1 visible segment\n * - (..)(..) two levels up: climb 2 visible segments\n * - (...) root: resolve from appDir\n */\nfunction computeInterceptTarget(\n convention: string,\n interceptSegment: string,\n currentDir: string,\n interceptRoot: string,\n routeDir: string,\n appDir: string,\n): { pattern: string; params: string[] } | null {\n // Determine the base segments for target resolution.\n // We work on route segments (not filesystem paths) so that route groups\n // and parallel slots are properly skipped when climbing.\n const routeSegments = path.relative(appDir, routeDir).split(path.sep).filter(Boolean);\n\n let baseParts: string[];\n switch (convention) {\n case \".\":\n baseParts = routeSegments;\n break;\n case \"..\":\n case \"../..\": {\n const levelsToClimb = convention === \"..\" ? 1 : 2;\n let climbed = 0;\n let cutIndex = routeSegments.length;\n while (cutIndex > 0 && climbed < levelsToClimb) {\n cutIndex--;\n if (!isInvisibleSegment(routeSegments[cutIndex])) {\n climbed++;\n }\n }\n baseParts = routeSegments.slice(0, cutIndex);\n break;\n }\n case \"...\":\n baseParts = [];\n break;\n default:\n return null;\n }\n\n // Add the intercept segment and any nested path segments\n const nestedParts = path.relative(interceptRoot, currentDir).split(path.sep).filter(Boolean);\n const allSegments = [...baseParts, interceptSegment, ...nestedParts];\n\n const convertedTarget = convertSegmentsToRouteParts(allSegments);\n if (!convertedTarget) return null;\n\n const { urlSegments, params } = convertedTarget;\n\n const pattern = \"/\" + urlSegments.join(\"/\");\n return { pattern: pattern === \"/\" ? \"/\" : pattern, params };\n}\n\n/**\n * Find a file by name (without extension) in a directory.\n * Checks configured pageExtensions.\n */\nfunction findFile(dir: string, name: string, matcher: ValidFileMatcher): string | null {\n for (const ext of matcher.dottedExtensions) {\n const filePath = path.join(dir, name + ext);\n if (fs.existsSync(filePath)) return filePath;\n }\n return null;\n}\n\n/**\n * Convert filesystem path segments to URL route parts, skipping invisible segments\n * (route groups, @slots, \".\") and converting dynamic segment syntax to Express-style\n * patterns (e.g. \"[id]\" → \":id\", \"[...slug]\" → \":slug+\").\n */\nfunction convertSegmentsToRouteParts(\n segments: string[],\n): { urlSegments: string[]; params: string[]; isDynamic: boolean } | null {\n const urlSegments: string[] = [];\n const params: string[] = [];\n let isDynamic = false;\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n\n if (isInvisibleSegment(segment)) continue;\n\n // Catch-all segments are only valid in terminal URL position.\n const catchAllMatch = segment.match(/^\\[\\.\\.\\.([\\w-]+)\\]$/);\n if (catchAllMatch) {\n if (hasRemainingVisibleSegments(segments, i + 1)) return null;\n isDynamic = true;\n params.push(catchAllMatch[1]);\n urlSegments.push(`:${catchAllMatch[1]}+`);\n continue;\n }\n\n const optionalCatchAllMatch = segment.match(/^\\[\\[\\.\\.\\.([\\w-]+)\\]\\]$/);\n if (optionalCatchAllMatch) {\n if (hasRemainingVisibleSegments(segments, i + 1)) return null;\n isDynamic = true;\n params.push(optionalCatchAllMatch[1]);\n urlSegments.push(`:${optionalCatchAllMatch[1]}*`);\n continue;\n }\n\n const dynamicMatch = segment.match(/^\\[([\\w-]+)\\]$/);\n if (dynamicMatch) {\n isDynamic = true;\n params.push(dynamicMatch[1]);\n urlSegments.push(`:${dynamicMatch[1]}`);\n continue;\n }\n\n urlSegments.push(decodeRouteSegment(segment));\n }\n\n return { urlSegments, params, isDynamic };\n}\n\nfunction hasRemainingVisibleSegments(segments: string[], startIndex: number): boolean {\n for (let i = startIndex; i < segments.length; i++) {\n if (!isInvisibleSegment(segments[i])) return true;\n }\n return false;\n}\n\n// Trie cache — keyed by route array identity (same array = same trie)\nconst appTrieCache = new WeakMap<AppRoute[], TrieNode<AppRoute>>();\n\nfunction getOrBuildAppTrie(routes: AppRoute[]): TrieNode<AppRoute> {\n let trie = appTrieCache.get(routes);\n if (!trie) {\n trie = buildRouteTrie(routes);\n appTrieCache.set(routes, trie);\n }\n return trie;\n}\n\nfunction joinRoutePattern(basePattern: string, subPath: string): string {\n if (!subPath) return basePattern;\n return basePattern === \"/\" ? `/${subPath}` : `${basePattern}/${subPath}`;\n}\n\n/**\n * Match a URL against App Router routes.\n */\nexport function matchAppRoute(\n url: string,\n routes: AppRoute[],\n): { route: AppRoute; params: Record<string, string | string[]> } | null {\n const pathname = url.split(\"?\")[0];\n let normalizedUrl = pathname === \"/\" ? \"/\" : pathname.replace(/\\/$/, \"\");\n normalizedUrl = normalizePathnameForRouteMatch(normalizedUrl);\n\n // Split URL once, look up via trie\n const urlParts = normalizedUrl.split(\"/\").filter(Boolean);\n const trie = getOrBuildAppTrie(routes);\n return trieMatch(trie, urlParts);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA2HA,IAAI,eAAkC;AACtC,IAAI,eAA8B;AAClC,IAAI,0BAAyC;AAE7C,SAAgB,0BAAgC;AAC9C,gBAAe;AACf,gBAAe;AACf,2BAA0B;;;;;AAM5B,eAAsB,UACpB,QACA,gBACA,SACqB;AACrB,aAAY,uBAAuB,eAAe;CAClD,MAAM,oBAAoB,KAAK,UAAU,QAAQ,WAAW;AAC5D,KAAI,gBAAgB,iBAAiB,UAAU,4BAA4B,kBACzE,QAAO;CAMT,MAAM,SAAqB,EAAE;CAE7B,MAAM,cAAc,SAAiB,KAAK,WAAW,IAAI,IAAI,KAAK,WAAW,IAAI;AAIjF,YAAW,MAAM,QAAQ,mBAAmB,WAAW,QAAQ,QAAQ,YAAY,WAAW,EAAE;EAC9F,MAAM,QAAQ,eAAe,MAAM,QAAQ,QAAQ,QAAQ;AAC3D,MAAI,MAAO,QAAO,KAAK,MAAM;;AAI/B,YAAW,MAAM,QAAQ,mBAAmB,YAAY,QAAQ,QAAQ,YAAY,WAAW,EAAE;EAC/F,MAAM,QAAQ,eAAe,MAAM,QAAQ,SAAS,QAAQ;AAC5D,MAAI,MAAO,QAAO,KAAK,MAAM;;CAO/B,MAAM,gBAAgB,sBAAsB,QAAQ,QAAQ,QAAQ;AACpE,QAAO,KAAK,GAAG,cAAc;AAE7B,uBAAsB,OAAO,KAAK,UAAU,MAAM,QAAQ,CAAC;AAC3D,uBACE,OAAO,SAAS,UACd,MAAM,cAAc,SAAS,SAC3B,KAAK,mBAAmB,KAAK,cAAc,UAAU,cAAc,CACpE,CACF,CACF;AAGD,QAAO,KAAK,cAAc;AAE1B,gBAAe;AACf,gBAAe;AACf,2BAA0B;AAC1B,QAA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AO;AACzD,eAAY;AACZ,UAAO,KAAK,sBAAsB,GAAG;AACrC,eAAY,KAAK,IAAI,sBAAsB,GAAG,GAAG;AACjD;;EAGF,MAAM,eAAe,QAAQ,MAAM,iBAAiB;AACpD,MAAI,cAAc;AAChB,eAAY;AACZ,UAAO,KAAK,aAAa,GAAG;AAC5B,eAAY,KAAK,IAAI,aAAa,KAAK;AACvC;;AAGF,cAAY,KAAK,mBAAmB,QAAQ,CAAC;;AAG/C,QAAO;EAAE;EAAa;EAAQ;EAAW;;AAG3C,SAAS,4BAA4B,UAAoB,YAA6B;AACpF,MAAK,IAAI,IAAI,YAAY,IAAI,SAAS,QAAQ,IAC5C,KAAI,CAAC,mBAAmB,SAAS,GAAG,CAAE,QAAO;AAE/C,QAAO;;AAIT,MAAM,+BAAe,IAAI,SAAyC;AAElE,SAAS,kBAAkB,QAAwC;CACjE,IAAI,OAAO,aAAa,IAAI,OAAO;AACnC,KAAI,CAAC,MAAM;AACT,SAAO,eAAe,OAAO;AAC7B,eAAa,IAAI,QAAQ,KAAK;;AAEhC,QAAO;;AAGT,SAAS,iBAAiB,aAAqB,SAAyB;AACtE,KAAI,CAAC,QAAS,QAAO;AACrB,QAAO,gBAAgB,MAAM,IAAI,YAAY,GAAG,YAAY,GAAG;;;;;AAMjE,SAAgB,cACd,KACA,QACuE;CACvE,MAAM,WAAW,IAAI,MAAM,IAAI,CAAC;CAChC,IAAI,gBAAgB,aAAa,MAAM,MAAM,SAAS,QAAQ,OAAO,GAAG;AACxE,iBAAgB,+BAA+B,cAAc;CAG7D,MAAM,WAAW,cAAc,MAAM,IAAI,CAAC,OAAO,QAAQ;AAEzD,QAAO,UADM,kBAAkB,OAAO,EACf,SAAS"}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
declare const DEFAULT_PAGE_EXTENSIONS: readonly ["tsx", "ts", "jsx", "js"];
|
|
3
3
|
declare function normalizePageExtensions(pageExtensions?: readonly string[] | null): string[];
|
|
4
4
|
declare function buildExtensionGlob(stem: string, extensions: readonly string[]): string;
|
|
5
|
-
|
|
5
|
+
type ValidFileMatcher = {
|
|
6
6
|
extensions: string[];
|
|
7
7
|
dottedExtensions: string[];
|
|
8
8
|
extensionRegex: RegExp;
|
|
@@ -12,7 +12,7 @@ interface ValidFileMatcher {
|
|
|
12
12
|
isAppLayoutFile(filePath: string): boolean;
|
|
13
13
|
isAppDefaultFile(filePath: string): boolean;
|
|
14
14
|
stripExtension(filePath: string): string;
|
|
15
|
-
}
|
|
15
|
+
};
|
|
16
16
|
/**
|
|
17
17
|
* Ported in spirit from Next.js createValidFileMatcher:
|
|
18
18
|
* packages/next/src/server/lib/find-page-file.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-matcher.js","names":[],"sources":["../../src/routing/file-matcher.ts"],"sourcesContent":["import { glob } from \"node:fs/promises\";\n\nexport const DEFAULT_PAGE_EXTENSIONS = [\"tsx\", \"ts\", \"jsx\", \"js\"] as const;\n\nfunction escapeRegex(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nexport function normalizePageExtensions(pageExtensions?: readonly string[] | null): string[] {\n if (!Array.isArray(pageExtensions) || pageExtensions.length === 0) {\n return [...DEFAULT_PAGE_EXTENSIONS];\n }\n\n const filtered = pageExtensions\n .filter((ext): ext is string => typeof ext === \"string\")\n .map((ext) => ext.trim().replace(/^\\.+/, \"\"))\n .filter((ext) => ext.length > 0);\n return filtered.length > 0 ? [...filtered] : [...DEFAULT_PAGE_EXTENSIONS];\n}\n\nexport function buildExtensionGlob(stem: string, extensions: readonly string[]): string {\n if (extensions.length === 1) {\n return `${stem}.${extensions[0]}`;\n }\n return `${stem}.{${extensions.join(\",\")}}`;\n}\n\nexport
|
|
1
|
+
{"version":3,"file":"file-matcher.js","names":[],"sources":["../../src/routing/file-matcher.ts"],"sourcesContent":["import { glob } from \"node:fs/promises\";\n\nexport const DEFAULT_PAGE_EXTENSIONS = [\"tsx\", \"ts\", \"jsx\", \"js\"] as const;\n\nfunction escapeRegex(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nexport function normalizePageExtensions(pageExtensions?: readonly string[] | null): string[] {\n if (!Array.isArray(pageExtensions) || pageExtensions.length === 0) {\n return [...DEFAULT_PAGE_EXTENSIONS];\n }\n\n const filtered = pageExtensions\n .filter((ext): ext is string => typeof ext === \"string\")\n .map((ext) => ext.trim().replace(/^\\.+/, \"\"))\n .filter((ext) => ext.length > 0);\n return filtered.length > 0 ? [...filtered] : [...DEFAULT_PAGE_EXTENSIONS];\n}\n\nexport function buildExtensionGlob(stem: string, extensions: readonly string[]): string {\n if (extensions.length === 1) {\n return `${stem}.${extensions[0]}`;\n }\n return `${stem}.{${extensions.join(\",\")}}`;\n}\n\nexport type ValidFileMatcher = {\n extensions: string[];\n dottedExtensions: string[];\n extensionRegex: RegExp;\n isPageFile(filePath: string): boolean;\n isAppRouterPage(filePath: string): boolean;\n isAppRouterRoute(filePath: string): boolean;\n isAppLayoutFile(filePath: string): boolean;\n isAppDefaultFile(filePath: string): boolean;\n stripExtension(filePath: string): string;\n};\n\n/**\n * Ported in spirit from Next.js createValidFileMatcher:\n * packages/next/src/server/lib/find-page-file.ts\n */\nexport function createValidFileMatcher(\n pageExtensions?: readonly string[] | null,\n): ValidFileMatcher {\n const extensions = normalizePageExtensions(pageExtensions);\n const dottedExtensions = extensions.map((ext) => `.${ext}`);\n const extPattern = `(?:${extensions.map((ext) => escapeRegex(ext)).join(\"|\")})`;\n\n const extensionRegex = new RegExp(`\\\\.${extPattern}$`);\n const createLeafPattern = (fileNames: readonly string[]): RegExp => {\n const names = fileNames.length === 1 ? fileNames[0] : `(${fileNames.join(\"|\")})`;\n return new RegExp(`(^${names}|[\\\\\\\\/]${names})\\\\.${extPattern}$`);\n };\n\n const appRouterPageRegex = createLeafPattern([\"page\", \"route\"]);\n const appRouterRouteRegex = createLeafPattern([\"route\"]);\n const appLayoutRegex = createLeafPattern([\"layout\"]);\n const appDefaultRegex = createLeafPattern([\"default\"]);\n\n return {\n extensions,\n dottedExtensions,\n extensionRegex,\n isPageFile(filePath: string) {\n return extensionRegex.test(filePath);\n },\n isAppRouterPage(filePath: string) {\n return appRouterPageRegex.test(filePath);\n },\n isAppRouterRoute(filePath: string) {\n return appRouterRouteRegex.test(filePath);\n },\n isAppLayoutFile(filePath: string) {\n return appLayoutRegex.test(filePath);\n },\n isAppDefaultFile(filePath: string) {\n return appDefaultRegex.test(filePath);\n },\n stripExtension(filePath: string) {\n return filePath.replace(extensionRegex, \"\");\n },\n };\n}\n\n/**\n * Use function-form exclude for Node < 22.14 compatibility.\n */\nexport async function* scanWithExtensions(\n stem: string,\n cwd: string,\n extensions: readonly string[],\n exclude?: (name: string) => boolean,\n): AsyncGenerator<string> {\n const pattern = buildExtensionGlob(stem, extensions);\n for await (const file of glob(pattern, {\n cwd,\n ...(exclude ? { exclude } : {}),\n })) {\n yield file;\n }\n}\n"],"mappings":";;AAEA,MAAa,0BAA0B;CAAC;CAAO;CAAM;CAAO;CAAK;AAEjE,SAAS,YAAY,OAAuB;AAC1C,QAAO,MAAM,QAAQ,uBAAuB,OAAO;;AAGrD,SAAgB,wBAAwB,gBAAqD;AAC3F,KAAI,CAAC,MAAM,QAAQ,eAAe,IAAI,eAAe,WAAW,EAC9D,QAAO,CAAC,GAAG,wBAAwB;CAGrC,MAAM,WAAW,eACd,QAAQ,QAAuB,OAAO,QAAQ,SAAS,CACvD,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,QAAQ,GAAG,CAAC,CAC5C,QAAQ,QAAQ,IAAI,SAAS,EAAE;AAClC,QAAO,SAAS,SAAS,IAAI,CAAC,GAAG,SAAS,GAAG,CAAC,GAAG,wBAAwB;;AAG3E,SAAgB,mBAAmB,MAAc,YAAuC;AACtF,KAAI,WAAW,WAAW,EACxB,QAAO,GAAG,KAAK,GAAG,WAAW;AAE/B,QAAO,GAAG,KAAK,IAAI,W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 -2,18 +2,13 @@ import { ValidFileMatcher } from "./file-matcher.js";
|
|
|
2
2
|
import { patternToNextFormat } from "./route-validation.js";
|
|
3
3
|
|
|
4
4
|
//#region src/routing/pages-router.d.ts
|
|
5
|
-
|
|
6
|
-
/** URL pattern, e.g. "/" or "/about" or "/posts/:id" */
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
/** Absolute file path to the page component */
|
|
11
|
-
filePath: string;
|
|
12
|
-
/** Whether this is a dynamic route */
|
|
13
|
-
isDynamic: boolean;
|
|
14
|
-
/** Parameter names for dynamic segments */
|
|
5
|
+
type Route = {
|
|
6
|
+
/** URL pattern, e.g. "/" or "/about" or "/posts/:id" */pattern: string; /** Pre-split pattern segments (computed once at scan time, reused per request) */
|
|
7
|
+
patternParts: string[]; /** Absolute file path to the page component */
|
|
8
|
+
filePath: string; /** Whether this is a dynamic route */
|
|
9
|
+
isDynamic: boolean; /** Parameter names for dynamic segments */
|
|
15
10
|
params: string[];
|
|
16
|
-
}
|
|
11
|
+
};
|
|
17
12
|
/**
|
|
18
13
|
* Invalidate cached routes for a given pages directory.
|
|
19
14
|
* Called by the file watcher when pages are added/removed.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pages-router.js","names":[],"sources":["../../src/routing/pages-router.ts"],"sourcesContent":["import path from \"node:path\";\nimport { compareRoutes, decodeRouteSegment, normalizePathnameForRouteMatch } from \"./utils.js\";\nimport {\n createValidFileMatcher,\n scanWithExtensions,\n type ValidFileMatcher,\n} from \"./file-matcher.js\";\nimport { patternToNextFormat, validateRoutePatterns } from \"./route-validation.js\";\nimport { buildRouteTrie, trieMatch, type TrieNode } from \"./route-trie.js\";\n\nexport interface Route {\n /** URL pattern, e.g. \"/\" or \"/about\" or \"/posts/:id\" */\n pattern: string;\n /** Pre-split pattern segments (computed once at scan time, reused per request) */\n patternParts: string[];\n /** Absolute file path to the page component */\n filePath: string;\n /** Whether this is a dynamic route */\n isDynamic: boolean;\n /** Parameter names for dynamic segments */\n params: string[];\n}\n\n// Route cache — invalidated when pages directory changes\nconst routeCache = new Map<string, { routes: Route[]; promise: Promise<Route[]> }>();\n\n/**\n * Invalidate cached routes for a given pages directory.\n * Called by the file watcher when pages are added/removed.\n */\nexport function invalidateRouteCache(pagesDir: string): void {\n for (const key of routeCache.keys()) {\n if (key.startsWith(`pages:${pagesDir}:`) || key.startsWith(`api:${pagesDir}:`)) {\n routeCache.delete(key);\n }\n }\n}\n\n/**\n * Scan the pages/ directory and return a list of routes.\n * Results are cached — call invalidateRouteCache() when files change.\n *\n * Follows Next.js Pages Router conventions:\n * - pages/index.tsx -> /\n * - pages/about.tsx -> /about\n * - pages/posts/[id].tsx -> /posts/:id\n * - pages/[...slug].tsx -> /:slug+\n * - Ignores _app.tsx, _document.tsx, _error.tsx, files starting with _\n * - Ignores pages/api/ (handled separately later)\n */\nexport async function pagesRouter(\n pagesDir: string,\n pageExtensions?: readonly string[],\n matcher?: ValidFileMatcher,\n): Promise<Route[]> {\n matcher ??= createValidFileMatcher(pageExtensions);\n const cacheKey = `pages:${pagesDir}:${JSON.stringify(matcher.extensions)}`;\n const cached = routeCache.get(cacheKey);\n if (cached) return cached.promise;\n\n const promise = scanPageRoutes(pagesDir, matcher);\n routeCache.set(cacheKey, { routes: [], promise });\n const routes = await promise;\n routeCache.set(cacheKey, { routes, promise });\n return routes;\n}\n\nasync function scanPageRoutes(pagesDir: string, matcher: ValidFileMatcher): Promise<Route[]> {\n const routes: Route[] = [];\n\n // Use function form of exclude for Node < 22.14 compatibility (string arrays require >= 22.14)\n for await (const file of scanWithExtensions(\n \"**/*\",\n pagesDir,\n matcher.extensions,\n (name: string) => name === \"api\" || name.startsWith(\"_\"),\n )) {\n const route = fileToRoute(file, pagesDir, matcher);\n if (route) routes.push(route);\n }\n\n validateRoutePatterns(routes.map((route) => route.pattern));\n\n // Sort: static routes first, then dynamic, then catch-all\n routes.sort(compareRoutes);\n\n return routes;\n}\n\n/**\n * Convert a file path relative to pages/ into a Route.\n */\nfunction fileToRoute(file: string, pagesDir: string, matcher: ValidFileMatcher): Route | null {\n // Remove extension\n const withoutExt = matcher.stripExtension(file);\n if (withoutExt === file) return null;\n\n // Convert to URL segments\n const segments = withoutExt.split(path.sep);\n\n // Handle index files: pages/index.tsx -> /\n const lastSegment = segments[segments.length - 1];\n if (lastSegment === \"index\") {\n segments.pop();\n }\n\n const params: string[] = [];\n let isDynamic = false;\n\n // Convert Next.js dynamic segments to URL patterns.\n // Catch-all segments are only valid in terminal position.\n const urlSegments: string[] = [];\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n\n // Catch-all: [...slug] -> :slug+ (param names may contain hyphens)\n const catchAllMatch = segment.match(/^\\[\\.\\.\\.([\\w-]+)\\]$/);\n if (catchAllMatch) {\n if (i !== segments.length - 1) return null;\n isDynamic = true;\n params.push(catchAllMatch[1]);\n urlSegments.push(`:${catchAllMatch[1]}+`);\n continue;\n }\n\n // Optional catch-all: [[...slug]] -> :slug* (param names may contain hyphens)\n const optionalCatchAllMatch = segment.match(/^\\[\\[\\.\\.\\.([\\w-]+)\\]\\]$/);\n if (optionalCatchAllMatch) {\n if (i !== segments.length - 1) return null;\n isDynamic = true;\n params.push(optionalCatchAllMatch[1]);\n urlSegments.push(`:${optionalCatchAllMatch[1]}*`);\n continue;\n }\n\n // Dynamic segment: [id] -> :id (param names may contain hyphens)\n const dynamicMatch = segment.match(/^\\[([\\w-]+)\\]$/);\n if (dynamicMatch) {\n isDynamic = true;\n params.push(dynamicMatch[1]);\n urlSegments.push(`:${dynamicMatch[1]}`);\n continue;\n }\n\n urlSegments.push(decodeRouteSegment(segment));\n }\n\n const pattern = \"/\" + urlSegments.join(\"/\");\n\n return {\n pattern: pattern === \"/\" ? \"/\" : pattern,\n patternParts: urlSegments.filter(Boolean),\n filePath: path.join(pagesDir, file),\n isDynamic,\n params,\n };\n}\n\n// Trie cache — keyed by route array identity (same array = same trie)\nconst trieCache = new WeakMap<Route[], TrieNode<Route>>();\n\nfunction getOrBuildTrie(routes: Route[]): TrieNode<Route> {\n let trie = trieCache.get(routes);\n if (!trie) {\n trie = buildRouteTrie(routes);\n trieCache.set(routes, trie);\n }\n return trie;\n}\n\n/**\n * Match a URL path against a route pattern.\n * Returns the matched params or null if no match.\n */\nexport function matchRoute(\n url: string,\n routes: Route[],\n): { route: Route; params: Record<string, string | string[]> } | null {\n // Normalize: strip query string and trailing slash\n const pathname = url.split(\"?\")[0];\n let normalizedUrl = pathname === \"/\" ? \"/\" : pathname.replace(/\\/$/, \"\");\n normalizedUrl = normalizePathnameForRouteMatch(normalizedUrl);\n\n // Split URL once, look up via trie\n const urlParts = normalizedUrl.split(\"/\").filter(Boolean);\n const trie = getOrBuildTrie(routes);\n return trieMatch(trie, urlParts);\n}\n\n/**\n * Scan the pages/api/ directory and return API routes.\n * Results are cached — call invalidateRouteCache() when files change.\n *\n * Follows Next.js conventions:\n * - pages/api/hello.ts -> /api/hello\n * - pages/api/users/[id].ts -> /api/users/:id\n */\nexport async function apiRouter(\n pagesDir: string,\n pageExtensions?: readonly string[],\n matcher?: ValidFileMatcher,\n): Promise<Route[]> {\n matcher ??= createValidFileMatcher(pageExtensions);\n const cacheKey = `api:${pagesDir}:${JSON.stringify(matcher.extensions)}`;\n const cached = routeCache.get(cacheKey);\n if (cached) return cached.promise;\n\n const promise = scanApiRoutes(pagesDir, matcher);\n routeCache.set(cacheKey, { routes: [], promise });\n const routes = await promise;\n routeCache.set(cacheKey, { routes, promise });\n return routes;\n}\n\nasync function scanApiRoutes(pagesDir: string, matcher: ValidFileMatcher): Promise<Route[]> {\n const apiDir = path.join(pagesDir, \"api\");\n let files: string[];\n try {\n files = [];\n for await (const file of scanWithExtensions(\n \"**/*\",\n apiDir,\n matcher.extensions,\n (name: string) => name.startsWith(\"_\"),\n )) {\n files.push(file);\n }\n } catch {\n files = [];\n }\n\n const routes: Route[] = [];\n\n for (const file of files) {\n // Reuse fileToRoute but pretend the file is under a virtual \"api/\" prefix\n const route = fileToRoute(path.join(\"api\", file), pagesDir, matcher);\n if (route) {\n routes.push(route);\n }\n }\n\n validateRoutePatterns(routes.map((route) => route.pattern));\n\n // Sort same as page routes\n routes.sort(compareRoutes);\n\n return routes;\n}\n\n/**\n * Convert internal route pattern (e.g., \"/posts/:id\", \"/docs/:slug+\")\n * to Next.js bracket format (e.g., \"/posts/[id]\", \"/docs/[...slug]\").\n * Used for __NEXT_DATA__.page which apps expect in Next.js format.\n */\nexport { patternToNextFormat } from \"./route-validation.js\";\n"],"mappings":";;;;;;AAwBA,MAAM,6BAAa,IAAI,KAA6D;;;;;AAMpF,SAAgB,qBAAqB,UAAwB;AAC3D,MAAK,MAAM,OAAO,WAAW,MAAM,CACjC,KAAI,IAAI,WAAW,SAAS,SAAS,GAAG,IAAI,IAAI,WAAW,OAAO,SAAS,GAAG,CAC5E,YAAW,OAAO,IAAI;;;;;;;;;;;;;;AAiB5B,eAAsB,YACpB,UACA,gBACA,SACkB;AAClB,aAAY,uBAAuB,eAAe;CAClD,MAAM,WAAW,SAAS,SAAS,GAAG,KAAK,UAAU,QAAQ,WAAW;CACxE,MAAM,SAAS,WAAW,IAAI,SAAS;AACvC,KAAI,OAAQ,QAAO,OAAO;CAE1B,MAAM,UAAU,eAAe,UAAU,QAAQ;AACjD,YAAW,IAAI,UAAU;EAAE,QAAQ,EAAE;EAAE;EAAS,CAAC;CACjD,MAAM,SAAS,MAAM;AACrB,YAAW,IAAI,UAAU;EAAE;EAAQ;EAAS,CAAC;AAC7C,QAAO;;AAGT,eAAe,eAAe,UAAkB,SAA6C;CAC3F,MAAM,SAAkB,EAAE;AAG1B,YAAW,MAAM,QAAQ,mBACvB,QACA,UACA,QAAQ,aACP,SAAiB,SAAS,SAAS,KAAK,WAAW,IAAI,CACzD,EAAE;EACD,MAAM,QAAQ,YAAY,MAAM,UAAU,QAAQ;AAClD,MAAI,MAAO,QAAO,KAAK,MAAM;;AAG/B,uBAAsB,OAAO,KAAK,UAAU,MAAM,QA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MAAM,QAAQ,CAAC;AAG3D,QAAO,KAAK,cAAc;AAE1B,QAAO"}
|
|
1
|
+
{"version":3,"file":"pages-router.js","names":[],"sources":["../../src/routing/pages-router.ts"],"sourcesContent":["import path from \"node:path\";\nimport { compareRoutes, decodeRouteSegment, normalizePathnameForRouteMatch } from \"./utils.js\";\nimport {\n createValidFileMatcher,\n scanWithExtensions,\n type ValidFileMatcher,\n} from \"./file-matcher.js\";\nimport { patternToNextFormat, validateRoutePatterns } from \"./route-validation.js\";\nimport { buildRouteTrie, trieMatch, type TrieNode } from \"./route-trie.js\";\n\nexport type Route = {\n /** URL pattern, e.g. \"/\" or \"/about\" or \"/posts/:id\" */\n pattern: string;\n /** Pre-split pattern segments (computed once at scan time, reused per request) */\n patternParts: string[];\n /** Absolute file path to the page component */\n filePath: string;\n /** Whether this is a dynamic route */\n isDynamic: boolean;\n /** Parameter names for dynamic segments */\n params: string[];\n};\n\n// Route cache — invalidated when pages directory changes\nconst routeCache = new Map<string, { routes: Route[]; promise: Promise<Route[]> }>();\n\n/**\n * Invalidate cached routes for a given pages directory.\n * Called by the file watcher when pages are added/removed.\n */\nexport function invalidateRouteCache(pagesDir: string): void {\n for (const key of routeCache.keys()) {\n if (key.startsWith(`pages:${pagesDir}:`) || key.startsWith(`api:${pagesDir}:`)) {\n routeCache.delete(key);\n }\n }\n}\n\n/**\n * Scan the pages/ directory and return a list of routes.\n * Results are cached — call invalidateRouteCache() when files change.\n *\n * Follows Next.js Pages Router conventions:\n * - pages/index.tsx -> /\n * - pages/about.tsx -> /about\n * - pages/posts/[id].tsx -> /posts/:id\n * - pages/[...slug].tsx -> /:slug+\n * - Ignores _app.tsx, _document.tsx, _error.tsx, files starting with _\n * - Ignores pages/api/ (handled separately later)\n */\nexport async function pagesRouter(\n pagesDir: string,\n pageExtensions?: readonly string[],\n matcher?: ValidFileMatcher,\n): Promise<Route[]> {\n matcher ??= createValidFileMatcher(pageExtensions);\n const cacheKey = `pages:${pagesDir}:${JSON.stringify(matcher.extensions)}`;\n const cached = routeCache.get(cacheKey);\n if (cached) return cached.promise;\n\n const promise = scanPageRoutes(pagesDir, matcher);\n routeCache.set(cacheKey, { routes: [], promise });\n const routes = await promise;\n routeCache.set(cacheKey, { routes, promise });\n return routes;\n}\n\nasync function scanPageRoutes(pagesDir: string, matcher: ValidFileMatcher): Promise<Route[]> {\n const routes: Route[] = [];\n\n // Use function form of exclude for Node < 22.14 compatibility (string arrays require >= 22.14)\n for await (const file of scanWithExtensions(\n \"**/*\",\n pagesDir,\n matcher.extensions,\n (name: string) => name === \"api\" || name.startsWith(\"_\"),\n )) {\n const route = fileToRoute(file, pagesDir, matcher);\n if (route) routes.push(route);\n }\n\n validateRoutePatterns(routes.map((route) => route.pattern));\n\n // Sort: static routes first, then dynamic, then catch-all\n routes.sort(compareRoutes);\n\n return routes;\n}\n\n/**\n * Convert a file path relative to pages/ into a Route.\n */\nfunction fileToRoute(file: string, pagesDir: string, matcher: ValidFileMatcher): Route | null {\n // Remove extension\n const withoutExt = matcher.stripExtension(file);\n if (withoutExt === file) return null;\n\n // Convert to URL segments\n const segments = withoutExt.split(path.sep);\n\n // Handle index files: pages/index.tsx -> /\n const lastSegment = segments[segments.length - 1];\n if (lastSegment === \"index\") {\n segments.pop();\n }\n\n const params: string[] = [];\n let isDynamic = false;\n\n // Convert Next.js dynamic segments to URL patterns.\n // Catch-all segments are only valid in terminal position.\n const urlSegments: string[] = [];\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n\n // Catch-all: [...slug] -> :slug+ (param names may contain hyphens)\n const catchAllMatch = segment.match(/^\\[\\.\\.\\.([\\w-]+)\\]$/);\n if (catchAllMatch) {\n if (i !== segments.length - 1) return null;\n isDynamic = true;\n params.push(catchAllMatch[1]);\n urlSegments.push(`:${catchAllMatch[1]}+`);\n continue;\n }\n\n // Optional catch-all: [[...slug]] -> :slug* (param names may contain hyphens)\n const optionalCatchAllMatch = segment.match(/^\\[\\[\\.\\.\\.([\\w-]+)\\]\\]$/);\n if (optionalCatchAllMatch) {\n if (i !== segments.length - 1) return null;\n isDynamic = true;\n params.push(optionalCatchAllMatch[1]);\n urlSegments.push(`:${optionalCatchAllMatch[1]}*`);\n continue;\n }\n\n // Dynamic segment: [id] -> :id (param names may contain hyphens)\n const dynamicMatch = segment.match(/^\\[([\\w-]+)\\]$/);\n if (dynamicMatch) {\n isDynamic = true;\n params.push(dynamicMatch[1]);\n urlSegments.push(`:${dynamicMatch[1]}`);\n continue;\n }\n\n urlSegments.push(decodeRouteSegment(segment));\n }\n\n const pattern = \"/\" + urlSegments.join(\"/\");\n\n return {\n pattern: pattern === \"/\" ? \"/\" : pattern,\n patternParts: urlSegments.filter(Boolean),\n filePath: path.join(pagesDir, file),\n isDynamic,\n params,\n };\n}\n\n// Trie cache — keyed by route array identity (same array = same trie)\nconst trieCache = new WeakMap<Route[], TrieNode<Route>>();\n\nfunction getOrBuildTrie(routes: Route[]): TrieNode<Route> {\n let trie = trieCache.get(routes);\n if (!trie) {\n trie = buildRouteTrie(routes);\n trieCache.set(routes, trie);\n }\n return trie;\n}\n\n/**\n * Match a URL path against a route pattern.\n * Returns the matched params or null if no match.\n */\nexport function matchRoute(\n url: string,\n routes: Route[],\n): { route: Route; params: Record<string, string | string[]> } | null {\n // Normalize: strip query string and trailing slash\n const pathname = url.split(\"?\")[0];\n let normalizedUrl = pathname === \"/\" ? \"/\" : pathname.replace(/\\/$/, \"\");\n normalizedUrl = normalizePathnameForRouteMatch(normalizedUrl);\n\n // Split URL once, look up via trie\n const urlParts = normalizedUrl.split(\"/\").filter(Boolean);\n const trie = getOrBuildTrie(routes);\n return trieMatch(trie, urlParts);\n}\n\n/**\n * Scan the pages/api/ directory and return API routes.\n * Results are cached — call invalidateRouteCache() when files change.\n *\n * Follows Next.js conventions:\n * - pages/api/hello.ts -> /api/hello\n * - pages/api/users/[id].ts -> /api/users/:id\n */\nexport async function apiRouter(\n pagesDir: string,\n pageExtensions?: readonly string[],\n matcher?: ValidFileMatcher,\n): Promise<Route[]> {\n matcher ??= createValidFileMatcher(pageExtensions);\n const cacheKey = `api:${pagesDir}:${JSON.stringify(matcher.extensions)}`;\n const cached = routeCache.get(cacheKey);\n if (cached) return cached.promise;\n\n const promise = scanApiRoutes(pagesDir, matcher);\n routeCache.set(cacheKey, { routes: [], promise });\n const routes = await promise;\n routeCache.set(cacheKey, { routes, promise });\n return routes;\n}\n\nasync function scanApiRoutes(pagesDir: string, matcher: ValidFileMatcher): Promise<Route[]> {\n const apiDir = path.join(pagesDir, \"api\");\n let files: string[];\n try {\n files = [];\n for await (const file of scanWithExtensions(\n \"**/*\",\n apiDir,\n matcher.extensions,\n (name: string) => name.startsWith(\"_\"),\n )) {\n files.push(file);\n }\n } catch {\n files = [];\n }\n\n const routes: Route[] = [];\n\n for (const file of files) {\n // Reuse fileToRoute but pretend the file is under a virtual \"api/\" prefix\n const route = fileToRoute(path.join(\"api\", file), pagesDir, matcher);\n if (route) {\n routes.push(route);\n }\n }\n\n validateRoutePatterns(routes.map((route) => route.pattern));\n\n // Sort same as page routes\n routes.sort(compareRoutes);\n\n return routes;\n}\n\n/**\n * Convert internal route pattern (e.g., \"/posts/:id\", \"/docs/:slug+\")\n * to Next.js bracket format (e.g., \"/posts/[id]\", \"/docs/[...slug]\").\n * Used for __NEXT_DATA__.page which apps expect in Next.js format.\n */\nexport { patternToNextFormat } from \"./route-validation.js\";\n"],"mappings":";;;;;;AAwBA,MAAM,6BAAa,IAAI,KAA6D;;;;;AAMpF,SAAgB,qBAAqB,UAAwB;AAC3D,MAAK,MAAM,OAAO,WAAW,MAAM,CACjC,KAAI,IAAI,WAAW,SAAS,SAAS,GAAG,IAAI,IAAI,WAAW,OAAO,SAAS,GAAG,CAC5E,YAAW,OAAO,IAAI;;;;;;;;;;;;;;AAiB5B,eAAsB,YACpB,UACA,gBACA,SACkB;AAClB,aAAY,uBAAuB,eAAe;CAClD,MAAM,WAAW,SAAS,SAAS,GAAG,KAAK,UAAU,QAAQ,WAAW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,CAAC;CACjD,MAAM,SAAS,MAAM;AACrB,YAAW,IAAI,UAAU;EAAE;EAAQ;EAAS,CAAC;AAC7C,QAAO;;AAGT,eAAe,cAAc,UAAkB,SAA6C;CAC1F,MAAM,SAAS,KAAK,KAAK,UAAU,MAAM;CACzC,IAAI;AACJ,KAAI;AACF,UAAQ,EAAE;AACV,aAAW,MAAM,QAAQ,mBACvB,QACA,QACA,QAAQ,aACP,SAAiB,KAAK,WAAW,IAAI,CACvC,CACC,OAAM,KAAK,KAAK;SAEZ;AACN,UAAQ,EAAE;;CAGZ,MAAM,SAAkB,EAAE;AAE1B,MAAK,MAAM,QAAQ,OAAO;EAExB,MAAM,QAAQ,YAAY,KAAK,KAAK,OAAO,KAAK,EAAE,UAAU,QAAQ;AACpE,MAAI,MACF,QAAO,KAAK,MAAM;;AAItB,uBAAsB,OAAO,KAAK,UAAU,MAAM,QAAQ,CAAC;AAG3D,QAAO,KAAK,cAAc;AAE1B,QAAO"}
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
* Backtracking via recursive DFS ensures that dead-end static/dynamic
|
|
13
13
|
* branches fall through to catch-all alternatives.
|
|
14
14
|
*/
|
|
15
|
-
|
|
15
|
+
type TrieNode<R> = {
|
|
16
16
|
staticChildren: Map<string, TrieNode<R>>;
|
|
17
17
|
dynamicChild: {
|
|
18
18
|
paramName: string;
|
|
@@ -27,7 +27,7 @@ interface TrieNode<R> {
|
|
|
27
27
|
route: R;
|
|
28
28
|
} | null;
|
|
29
29
|
route: R | null;
|
|
30
|
-
}
|
|
30
|
+
};
|
|
31
31
|
/**
|
|
32
32
|
* Build a trie from pre-sorted routes.
|
|
33
33
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route-trie.js","names":[],"sources":["../../src/routing/route-trie.ts"],"sourcesContent":["/**\n * Trie (prefix tree) for O(depth) route matching.\n *\n * Replaces the O(n) linear scan over pre-sorted routes with a trie-based\n * lookup. Priority is enforced by traversal order at each node:\n * 1. Static child (exact segment match) — highest priority\n * 2. Dynamic child (single-segment param) — medium\n * 3. Catch-all (1+ remaining segments) — low\n * 4. Optional catch-all (0+ remaining segments) — lowest\n *\n * Backtracking via recursive DFS ensures that dead-end static/dynamic\n * branches fall through to catch-all alternatives.\n */\n\nexport
|
|
1
|
+
{"version":3,"file":"route-trie.js","names":[],"sources":["../../src/routing/route-trie.ts"],"sourcesContent":["/**\n * Trie (prefix tree) for O(depth) route matching.\n *\n * Replaces the O(n) linear scan over pre-sorted routes with a trie-based\n * lookup. Priority is enforced by traversal order at each node:\n * 1. Static child (exact segment match) — highest priority\n * 2. Dynamic child (single-segment param) — medium\n * 3. Catch-all (1+ remaining segments) — low\n * 4. Optional catch-all (0+ remaining segments) — lowest\n *\n * Backtracking via recursive DFS ensures that dead-end static/dynamic\n * branches fall through to catch-all alternatives.\n */\n\nexport type TrieNode<R> = {\n staticChildren: Map<string, TrieNode<R>>;\n dynamicChild: { paramName: string; node: TrieNode<R> } | null;\n catchAllChild: { paramName: string; route: R } | null;\n optionalCatchAllChild: { paramName: string; route: R } | null;\n route: R | null;\n};\n\nfunction createNode<R>(): TrieNode<R> {\n return {\n staticChildren: new Map(),\n dynamicChild: null,\n catchAllChild: null,\n optionalCatchAllChild: null,\n route: null,\n };\n}\n\n/**\n * Build a trie from pre-sorted routes.\n *\n * Routes must have a `patternParts` property (string[] of URL segments).\n * Pattern segment conventions:\n * - `:name` — dynamic segment\n * - `:name+` — catch-all (1+ segments)\n * - `:name*` — optional catch-all (0+ segments)\n * - anything else — static segment\n *\n * First route to claim a terminal position wins (routes are pre-sorted\n * by precedence, so insertion order preserves correct priority).\n */\nexport function buildRouteTrie<R extends { patternParts: string[] }>(routes: R[]): TrieNode<R> {\n const root = createNode<R>();\n\n for (const route of routes) {\n const parts = route.patternParts;\n\n // Root route (patternParts = [])\n if (parts.length === 0) {\n if (root.route === null) {\n root.route = route;\n }\n continue;\n }\n\n let node = root;\n\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n\n // Catch-all: :name+ (must be terminal — skip malformed non-terminal catch-alls)\n if (part.endsWith(\"+\") && part.startsWith(\":\")) {\n if (i !== parts.length - 1) break; // malformed: not terminal\n const paramName = part.slice(1, -1);\n if (node.catchAllChild === null) {\n node.catchAllChild = { paramName, route };\n }\n break;\n }\n\n // Optional catch-all: :name* (must be terminal — skip malformed non-terminal)\n if (part.endsWith(\"*\") && part.startsWith(\":\")) {\n if (i !== parts.length - 1) break; // malformed: not terminal\n const paramName = part.slice(1, -1);\n if (node.optionalCatchAllChild === null) {\n node.optionalCatchAllChild = { paramName, route };\n }\n break;\n }\n\n // Dynamic segment: :name\n if (part.startsWith(\":\")) {\n const paramName = part.slice(1);\n if (node.dynamicChild === null) {\n node.dynamicChild = { paramName, node: createNode<R>() };\n }\n node = node.dynamicChild.node;\n\n // If this is the last segment, set the route\n if (i === parts.length - 1) {\n if (node.route === null) {\n node.route = route;\n }\n }\n continue;\n }\n\n // Static segment\n let child = node.staticChildren.get(part);\n if (!child) {\n child = createNode<R>();\n node.staticChildren.set(part, child);\n }\n node = child;\n\n // If this is the last segment, set the route\n if (i === parts.length - 1) {\n if (node.route === null) {\n node.route = route;\n }\n }\n }\n }\n\n return root;\n}\n\n/**\n * Match a URL against the trie.\n *\n * @param root - Trie root built by `buildRouteTrie`\n * @param urlParts - Pre-split URL segments (no empty strings)\n * @returns Match result with route and extracted params, or null\n */\nexport function trieMatch<R>(\n root: TrieNode<R>,\n urlParts: string[],\n): { route: R; params: Record<string, string | string[]> } | null {\n return match(root, urlParts, 0);\n}\n\nfunction match<R>(\n node: TrieNode<R>,\n urlParts: string[],\n index: number,\n): { route: R; params: Record<string, string | string[]> } | null {\n // All URL segments consumed\n if (index === urlParts.length) {\n // Exact match at this node\n if (node.route !== null) {\n return { route: node.route, params: Object.create(null) };\n }\n\n // Optional catch-all with 0 segments\n if (node.optionalCatchAllChild !== null) {\n const params: Record<string, string | string[]> = Object.create(null);\n params[node.optionalCatchAllChild.paramName] = [];\n return { route: node.optionalCatchAllChild.route, params };\n }\n\n return null;\n }\n\n const segment = urlParts[index];\n\n // 1. Try static child (highest priority)\n const staticChild = node.staticChildren.get(segment);\n if (staticChild) {\n const result = match(staticChild, urlParts, index + 1);\n if (result !== null) {\n return result;\n }\n }\n\n // 2. Try dynamic child (single segment)\n if (node.dynamicChild !== null) {\n const result = match(node.dynamicChild.node, urlParts, index + 1);\n if (result !== null) {\n result.params[node.dynamicChild.paramName] = segment;\n return result;\n }\n }\n\n // 3. Try catch-all (1+ remaining segments)\n if (node.catchAllChild !== null) {\n const remaining = urlParts.slice(index);\n const params: Record<string, string | string[]> = Object.create(null);\n params[node.catchAllChild.paramName] = remaining;\n return { route: node.catchAllChild.route, params };\n }\n\n // 4. Try optional catch-all (0+ remaining segments)\n if (node.optionalCatchAllChild !== null) {\n const remaining = urlParts.slice(index);\n const params: Record<string, string | string[]> = Object.create(null);\n params[node.optionalCatchAllChild.paramName] = remaining;\n return { route: node.optionalCatchAllChild.route, params };\n }\n\n return null;\n}\n"],"mappings":";AAsBA,SAAS,aAA6B;AACpC,QAAO;EACL,gCAAgB,IAAI,KAAK;EACzB,cAAc;EACd,eAAe;EACf,uBAAuB;EACvB,OAAO;EACR;;;;;;;;;;;;;;;AAgBH,SAAgB,eAAqD,QAA0B;CAC7F,MAAM,OAAO,YAAe;AAE5B,MAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,QAAQ,MAAM;AAGpB,MAAI,MAAM,WAAW,GAAG;AACtB,OAAI,KAAK,UAAU,KACjB,MAAK,QAAQ;AAEf;;EAGF,IAAI,OAAO;AAEX,OAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;GACrC,MAAM,OAAO,MAAM;AAGnB,OAAI,KAAK,SAAS,IAAI,IAAI,KAAK,WAAW,IAAI,EAAE;AAC9C,QAAI,MAAM,MAAM,SAAS,EAAG;IAC5B,MAAM,YAAY,KAAK,MAAM,GAAG,GAAG;AACnC,QAAI,KAAK,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