vinext 0.0.46 → 0.0.48
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 +8 -6
- package/dist/build/layout-classification.js +3 -1
- package/dist/build/layout-classification.js.map +1 -1
- package/dist/build/prerender.d.ts +2 -1
- package/dist/build/prerender.js +80 -24
- package/dist/build/prerender.js.map +1 -1
- package/dist/build/report.d.ts +9 -5
- package/dist/build/report.js +17 -7
- package/dist/build/report.js.map +1 -1
- package/dist/build/route-classification-injector.d.ts +35 -0
- package/dist/build/route-classification-injector.js +61 -0
- package/dist/build/route-classification-injector.js.map +1 -0
- package/dist/build/route-classification-manifest.d.ts +1 -1
- package/dist/build/run-prerender.d.ts +5 -0
- package/dist/build/run-prerender.js +4 -1
- package/dist/build/run-prerender.js.map +1 -1
- package/dist/build/server-manifest.js +2 -7
- package/dist/build/server-manifest.js.map +1 -1
- package/dist/build/standalone.js +3 -5
- package/dist/build/standalone.js.map +1 -1
- package/dist/build/static-export.d.ts +1 -1
- package/dist/check.js +45 -29
- package/dist/check.js.map +1 -1
- package/dist/cli-args.d.ts +33 -0
- package/dist/cli-args.js +121 -0
- package/dist/cli-args.js.map +1 -0
- package/dist/cli.js +11 -20
- package/dist/cli.js.map +1 -1
- package/dist/cloudflare/kv-cache-handler.js +29 -9
- package/dist/cloudflare/kv-cache-handler.js.map +1 -1
- package/dist/config/config-matchers.js +46 -37
- package/dist/config/config-matchers.js.map +1 -1
- package/dist/config/next-config.d.ts +4 -2
- package/dist/config/next-config.js +3 -0
- package/dist/config/next-config.js.map +1 -1
- package/dist/deploy.d.ts +18 -2
- package/dist/deploy.js +47 -4
- package/dist/deploy.js.map +1 -1
- package/dist/entries/app-rsc-entry.d.ts +4 -3
- package/dist/entries/app-rsc-entry.js +379 -858
- package/dist/entries/app-rsc-entry.js.map +1 -1
- package/dist/entries/app-rsc-manifest.d.ts +1 -1
- package/dist/entries/app-rsc-manifest.js +6 -1
- package/dist/entries/app-rsc-manifest.js.map +1 -1
- package/dist/entries/pages-client-entry.js +3 -2
- package/dist/entries/pages-client-entry.js.map +1 -1
- package/dist/entries/pages-server-entry.js +19 -61
- package/dist/entries/pages-server-entry.js.map +1 -1
- package/dist/entries/runtime-entry-module.d.ts +12 -3
- package/dist/entries/runtime-entry-module.js +15 -4
- package/dist/entries/runtime-entry-module.js.map +1 -1
- package/dist/index.js +40 -58
- package/dist/index.js.map +1 -1
- package/dist/plugins/fonts.js +54 -32
- package/dist/plugins/fonts.js.map +1 -1
- package/dist/plugins/og-assets.js +15 -16
- package/dist/plugins/og-assets.js.map +1 -1
- package/dist/plugins/rsc-client-shim-excludes.d.ts +2 -1
- package/dist/plugins/rsc-client-shim-excludes.js +11 -1
- package/dist/plugins/rsc-client-shim-excludes.js.map +1 -1
- package/dist/routing/app-route-graph.d.ts +195 -0
- package/dist/routing/app-route-graph.js +1022 -0
- package/dist/routing/app-route-graph.js.map +1 -0
- package/dist/routing/app-router.d.ts +14 -88
- package/dist/routing/app-router.js +21 -712
- package/dist/routing/app-router.js.map +1 -1
- package/dist/routing/file-matcher.d.ts +3 -1
- package/dist/routing/file-matcher.js +6 -1
- package/dist/routing/file-matcher.js.map +1 -1
- package/dist/routing/pages-router.js +10 -19
- package/dist/routing/pages-router.js.map +1 -1
- package/dist/routing/route-matching.d.ts +28 -0
- package/dist/routing/route-matching.js +44 -0
- package/dist/routing/route-matching.js.map +1 -0
- package/dist/routing/route-pattern.js +4 -1
- package/dist/routing/route-pattern.js.map +1 -1
- package/dist/routing/route-trie.d.ts +8 -0
- package/dist/routing/route-trie.js +12 -1
- package/dist/routing/route-trie.js.map +1 -1
- package/dist/routing/route-validation.js +3 -4
- package/dist/routing/route-validation.js.map +1 -1
- package/dist/routing/utils.d.ts +8 -1
- package/dist/routing/utils.js +25 -2
- package/dist/routing/utils.js.map +1 -1
- package/dist/server/app-browser-entry.js +145 -294
- package/dist/server/app-browser-entry.js.map +1 -1
- package/dist/server/app-browser-error.d.ts +3 -4
- package/dist/server/app-browser-error.js +8 -4
- package/dist/server/app-browser-error.js.map +1 -1
- package/dist/server/app-browser-navigation-controller.d.ts +75 -0
- package/dist/server/app-browser-navigation-controller.js +290 -0
- package/dist/server/app-browser-navigation-controller.js.map +1 -0
- package/dist/server/app-browser-state.d.ts +33 -15
- package/dist/server/app-browser-state.js +52 -59
- package/dist/server/app-browser-state.js.map +1 -1
- package/dist/server/app-browser-visible-commit.d.ts +68 -0
- package/dist/server/app-browser-visible-commit.js +182 -0
- package/dist/server/app-browser-visible-commit.js.map +1 -0
- package/dist/server/app-client-reference-preloader.d.ts +15 -0
- package/dist/server/app-client-reference-preloader.js +46 -0
- package/dist/server/app-client-reference-preloader.js.map +1 -0
- package/dist/server/app-elements-wire.d.ts +130 -0
- package/dist/server/app-elements-wire.js +205 -0
- package/dist/server/app-elements-wire.js.map +1 -0
- package/dist/server/app-elements.d.ts +2 -84
- package/dist/server/app-elements.js +4 -107
- package/dist/server/app-elements.js.map +1 -1
- package/dist/server/app-fallback-renderer.d.ts +57 -0
- package/dist/server/app-fallback-renderer.js +79 -0
- package/dist/server/app-fallback-renderer.js.map +1 -0
- package/dist/server/app-hook-warning-suppression.d.ts +7 -0
- package/dist/server/app-hook-warning-suppression.js +12 -0
- package/dist/server/app-hook-warning-suppression.js.map +1 -0
- package/dist/server/app-middleware.d.ts +2 -1
- package/dist/server/app-middleware.js +34 -11
- package/dist/server/app-middleware.js.map +1 -1
- package/dist/server/app-mounted-slots-header.d.ts +17 -0
- package/dist/server/app-mounted-slots-header.js +21 -0
- package/dist/server/app-mounted-slots-header.js.map +1 -0
- package/dist/server/app-page-boundary-render.d.ts +3 -3
- package/dist/server/app-page-boundary-render.js +8 -5
- package/dist/server/app-page-boundary-render.js.map +1 -1
- package/dist/server/app-page-boundary.js +2 -1
- package/dist/server/app-page-boundary.js.map +1 -1
- package/dist/server/app-page-cache.d.ts +19 -4
- package/dist/server/app-page-cache.js +60 -22
- package/dist/server/app-page-cache.js.map +1 -1
- package/dist/server/app-page-dispatch.d.ts +9 -5
- package/dist/server/app-page-dispatch.js +41 -17
- package/dist/server/app-page-dispatch.js.map +1 -1
- package/dist/server/app-page-element-builder.d.ts +61 -0
- package/dist/server/app-page-element-builder.js +142 -0
- package/dist/server/app-page-element-builder.js.map +1 -0
- package/dist/server/app-page-execution.d.ts +23 -5
- package/dist/server/app-page-execution.js +39 -24
- package/dist/server/app-page-execution.js.map +1 -1
- package/dist/server/app-page-head.js +2 -1
- package/dist/server/app-page-head.js.map +1 -1
- package/dist/server/app-page-method.js +2 -5
- package/dist/server/app-page-method.js.map +1 -1
- package/dist/server/app-page-params.d.ts +2 -1
- package/dist/server/app-page-params.js +3 -3
- package/dist/server/app-page-params.js.map +1 -1
- package/dist/server/app-page-probe.d.ts +1 -1
- package/dist/server/app-page-probe.js +5 -1
- package/dist/server/app-page-probe.js.map +1 -1
- package/dist/server/app-page-render.d.ts +6 -2
- package/dist/server/app-page-render.js +118 -30
- package/dist/server/app-page-render.js.map +1 -1
- package/dist/server/app-page-request.d.ts +19 -5
- package/dist/server/app-page-request.js +49 -7
- package/dist/server/app-page-request.js.map +1 -1
- package/dist/server/app-page-response.d.ts +1 -0
- package/dist/server/app-page-response.js +6 -9
- package/dist/server/app-page-response.js.map +1 -1
- package/dist/server/app-page-route-wiring.d.ts +20 -4
- package/dist/server/app-page-route-wiring.js +15 -12
- package/dist/server/app-page-route-wiring.js.map +1 -1
- package/dist/server/app-page-stream.d.ts +7 -0
- package/dist/server/app-page-stream.js +9 -2
- package/dist/server/app-page-stream.js.map +1 -1
- package/dist/server/app-post-middleware-context.d.ts +16 -0
- package/dist/server/app-post-middleware-context.js +28 -0
- package/dist/server/app-post-middleware-context.js.map +1 -0
- package/dist/server/app-prerender-endpoints.js +3 -2
- package/dist/server/app-prerender-endpoints.js.map +1 -1
- package/dist/server/app-request-context.d.ts +22 -0
- package/dist/server/app-request-context.js +30 -0
- package/dist/server/app-request-context.js.map +1 -0
- package/dist/server/app-route-handler-cache.d.ts +1 -0
- package/dist/server/app-route-handler-cache.js +7 -2
- package/dist/server/app-route-handler-cache.js.map +1 -1
- package/dist/server/app-route-handler-dispatch.d.ts +1 -0
- package/dist/server/app-route-handler-dispatch.js +8 -5
- package/dist/server/app-route-handler-dispatch.js.map +1 -1
- package/dist/server/app-route-handler-execution.d.ts +2 -1
- package/dist/server/app-route-handler-execution.js +2 -2
- package/dist/server/app-route-handler-execution.js.map +1 -1
- package/dist/server/app-route-handler-policy.js +13 -13
- package/dist/server/app-route-handler-policy.js.map +1 -1
- package/dist/server/app-route-handler-response.d.ts +4 -2
- package/dist/server/app-route-handler-response.js +9 -7
- package/dist/server/app-route-handler-response.js.map +1 -1
- package/dist/server/app-route-handler-runtime.d.ts +9 -1
- package/dist/server/app-route-handler-runtime.js +11 -1
- package/dist/server/app-route-handler-runtime.js.map +1 -1
- package/dist/server/app-router-entry.js +9 -4
- package/dist/server/app-router-entry.js.map +1 -1
- package/dist/server/app-rsc-cache-busting.d.ts +34 -0
- package/dist/server/app-rsc-cache-busting.js +137 -0
- package/dist/server/app-rsc-cache-busting.js.map +1 -0
- package/dist/server/app-rsc-error-handler.d.ts +21 -0
- package/dist/server/app-rsc-error-handler.js +30 -0
- package/dist/server/app-rsc-error-handler.js.map +1 -0
- package/dist/server/app-rsc-handler.d.ts +117 -0
- package/dist/server/app-rsc-handler.js +271 -0
- package/dist/server/app-rsc-handler.js.map +1 -0
- package/dist/server/app-rsc-request-normalization.d.ts +42 -0
- package/dist/server/app-rsc-request-normalization.js +67 -0
- package/dist/server/app-rsc-request-normalization.js.map +1 -0
- package/dist/server/app-rsc-response-finalizer.d.ts +30 -0
- package/dist/server/app-rsc-response-finalizer.js +38 -0
- package/dist/server/app-rsc-response-finalizer.js.map +1 -0
- package/dist/server/app-rsc-route-matching.js +8 -4
- package/dist/server/app-rsc-route-matching.js.map +1 -1
- package/dist/server/app-segment-config.d.ts +33 -0
- package/dist/server/app-segment-config.js +90 -0
- package/dist/server/app-segment-config.js.map +1 -0
- package/dist/server/app-server-action-execution.d.ts +2 -0
- package/dist/server/app-server-action-execution.js +45 -51
- package/dist/server/app-server-action-execution.js.map +1 -1
- package/dist/server/app-ssr-entry.js +21 -20
- package/dist/server/app-ssr-entry.js.map +1 -1
- package/dist/server/artifact-compatibility.d.ts +44 -0
- package/dist/server/artifact-compatibility.js +82 -0
- package/dist/server/artifact-compatibility.js.map +1 -0
- package/dist/server/cache-control.d.ts +24 -0
- package/dist/server/cache-control.js +33 -0
- package/dist/server/cache-control.js.map +1 -0
- package/dist/server/cache-proof.d.ts +200 -0
- package/dist/server/cache-proof.js +342 -0
- package/dist/server/cache-proof.js.map +1 -0
- package/dist/server/dev-error-overlay-store.d.ts +23 -0
- package/dist/server/dev-error-overlay-store.js +67 -0
- package/dist/server/dev-error-overlay-store.js.map +1 -0
- package/dist/server/dev-error-overlay.d.ts +15 -0
- package/dist/server/dev-error-overlay.js +548 -0
- package/dist/server/dev-error-overlay.js.map +1 -0
- package/dist/server/dev-origin-check.js +8 -4
- package/dist/server/dev-origin-check.js.map +1 -1
- package/dist/server/dev-server.js +1 -6
- package/dist/server/dev-server.js.map +1 -1
- package/dist/server/http-error-responses.d.ts +67 -0
- package/dist/server/http-error-responses.js +77 -0
- package/dist/server/http-error-responses.js.map +1 -0
- package/dist/server/image-optimization.js +2 -1
- package/dist/server/image-optimization.js.map +1 -1
- package/dist/server/instrumentation-runtime.d.ts +44 -0
- package/dist/server/instrumentation-runtime.js +29 -0
- package/dist/server/instrumentation-runtime.js.map +1 -0
- package/dist/server/isr-cache.d.ts +2 -7
- package/dist/server/isr-cache.js +7 -10
- package/dist/server/isr-cache.js.map +1 -1
- package/dist/server/metadata-route-response.js +6 -5
- package/dist/server/metadata-route-response.js.map +1 -1
- package/dist/server/metadata-routes.d.ts +1 -0
- package/dist/server/metadata-routes.js +6 -0
- package/dist/server/metadata-routes.js.map +1 -1
- package/dist/server/middleware-matcher.js +2 -2
- package/dist/server/middleware-matcher.js.map +1 -1
- package/dist/server/middleware-response-headers.js +21 -0
- package/dist/server/middleware-response-headers.js.map +1 -1
- package/dist/server/middleware-runtime.js +3 -3
- package/dist/server/middleware-runtime.js.map +1 -1
- package/dist/server/navigation-trace.d.ts +33 -0
- package/dist/server/navigation-trace.js +35 -0
- package/dist/server/navigation-trace.js.map +1 -0
- package/dist/server/next-error-digest.d.ts +44 -0
- package/dist/server/next-error-digest.js +40 -0
- package/dist/server/next-error-digest.js.map +1 -0
- package/dist/server/pages-api-route.js +2 -1
- package/dist/server/pages-api-route.js.map +1 -1
- package/dist/server/pages-node-compat.js +4 -16
- package/dist/server/pages-node-compat.js.map +1 -1
- package/dist/server/pages-page-data.d.ts +2 -1
- package/dist/server/pages-page-data.js +6 -5
- package/dist/server/pages-page-data.js.map +1 -1
- package/dist/server/pages-page-response.d.ts +3 -8
- package/dist/server/pages-page-response.js +46 -15
- package/dist/server/pages-page-response.js.map +1 -1
- package/dist/server/prod-server.d.ts +6 -0
- package/dist/server/prod-server.js +28 -21
- package/dist/server/prod-server.js.map +1 -1
- package/dist/server/request-pipeline.d.ts +42 -1
- package/dist/server/request-pipeline.js +97 -17
- package/dist/server/request-pipeline.js.map +1 -1
- package/dist/server/rsc-stream-hints.d.ts +3 -1
- package/dist/server/rsc-stream-hints.js +4 -1
- package/dist/server/rsc-stream-hints.js.map +1 -1
- package/dist/server/seed-cache.js +19 -8
- package/dist/server/seed-cache.js.map +1 -1
- package/dist/shims/cache-runtime.d.ts +2 -2
- package/dist/shims/cache-runtime.js +31 -17
- package/dist/shims/cache-runtime.js.map +1 -1
- package/dist/shims/cache.d.ts +15 -3
- package/dist/shims/cache.js +45 -20
- package/dist/shims/cache.js.map +1 -1
- package/dist/shims/error-boundary.d.ts +17 -1
- package/dist/shims/error-boundary.js +31 -1
- package/dist/shims/error-boundary.js.map +1 -1
- package/dist/shims/fetch-cache.d.ts +4 -1
- package/dist/shims/fetch-cache.js +57 -16
- package/dist/shims/fetch-cache.js.map +1 -1
- package/dist/shims/head-state.js +2 -3
- package/dist/shims/head-state.js.map +1 -1
- package/dist/shims/headers.js +4 -44
- package/dist/shims/headers.js.map +1 -1
- package/dist/shims/i18n-state.js +2 -3
- package/dist/shims/i18n-state.js.map +1 -1
- package/dist/shims/image.js +93 -5
- package/dist/shims/image.js.map +1 -1
- package/dist/shims/internal/als-registry.d.ts +15 -0
- package/dist/shims/internal/als-registry.js +55 -0
- package/dist/shims/internal/als-registry.js.map +1 -0
- package/dist/shims/internal/cookie-serialize.d.ts +46 -0
- package/dist/shims/internal/cookie-serialize.js +51 -0
- package/dist/shims/internal/cookie-serialize.js.map +1 -0
- package/dist/shims/link.js +31 -26
- package/dist/shims/link.js.map +1 -1
- package/dist/shims/metadata.d.ts +26 -1
- package/dist/shims/metadata.js +94 -4
- package/dist/shims/metadata.js.map +1 -1
- package/dist/shims/navigation-state.js +2 -3
- package/dist/shims/navigation-state.js.map +1 -1
- package/dist/shims/navigation.d.ts +2 -7
- package/dist/shims/navigation.js +44 -36
- package/dist/shims/navigation.js.map +1 -1
- package/dist/shims/request-context.js +2 -4
- package/dist/shims/request-context.js.map +1 -1
- package/dist/shims/request-state-types.d.ts +1 -1
- package/dist/shims/router-state.js +2 -3
- package/dist/shims/router-state.js.map +1 -1
- package/dist/shims/router.js +2 -2
- package/dist/shims/router.js.map +1 -1
- package/dist/shims/server.js +5 -30
- package/dist/shims/server.js.map +1 -1
- package/dist/shims/slot.d.ts +1 -1
- package/dist/shims/slot.js +5 -4
- package/dist/shims/slot.js.map +1 -1
- package/dist/shims/thenable-params.d.ts +5 -2
- package/dist/shims/thenable-params.js +26 -6
- package/dist/shims/thenable-params.js.map +1 -1
- package/dist/shims/unified-request-context.d.ts +1 -1
- package/dist/shims/unified-request-context.js +3 -14
- package/dist/shims/unified-request-context.js.map +1 -1
- package/dist/shims/use-merged-ref.d.ts +7 -0
- package/dist/shims/use-merged-ref.js +40 -0
- package/dist/shims/use-merged-ref.js.map +1 -0
- package/dist/utils/base-path.d.ts +7 -1
- package/dist/utils/base-path.js +12 -1
- package/dist/utils/base-path.js.map +1 -1
- package/dist/utils/cache-control-metadata.d.ts +6 -0
- package/dist/utils/cache-control-metadata.js +16 -0
- package/dist/utils/cache-control-metadata.js.map +1 -0
- package/dist/utils/safe-json-file.d.ts +18 -0
- package/dist/utils/safe-json-file.js +25 -0
- package/dist/utils/safe-json-file.js.map +1 -0
- package/dist/utils/text-stream.d.ts +29 -0
- package/dist/utils/text-stream.js +66 -0
- package/dist/utils/text-stream.js.map +1 -0
- package/package.json +5 -5
|
@@ -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 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 /** Absolute layout paths inside the intercepting route tree, outermost to innermost */\n layoutPaths: string[];\n /** Parameter names for dynamic segments */\n params: string[];\n};\n\nexport type ParallelSlot = {\n /** Stable slot identity (name + owning directory), used for route serialization keys. */\n key: string;\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 * Filesystem segments from the slot's root directory to its active page.\n * Used at render time to compute segments for useSelectedLayoutSegment(slotName).\n * For a page at the slot root (@team/page.tsx), this is [].\n * For a sub-page (@team/members/page.tsx), this is [\"members\"].\n * null when the slot has no active page (showing default.tsx fallback).\n */\n routeSegments: string[] | null;\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 all discovered template files from root to leaf (not necessarily aligned 1:1 with 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 /**\n * Forbidden component paths per layout level (aligned with layouts array).\n * Each entry is the forbidden.tsx at that layout's directory, or null.\n * Used to create per-layout ForbiddenBoundary.\n */\n forbiddenPaths: (string | null)[];\n /** Forbidden component path (403) at the route's directory level */\n forbiddenPath: string | null;\n /** Unauthorized component path (401) at the route's directory level */\n unauthorizedPath: string | null;\n /** Unauthorized component paths per layout level (aligned with layouts array). */\n unauthorizedPaths: (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 /** Tree position (directory depth from app/ root) for each template. */\n templateTreePositions?: number[];\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 /** Dynamic parameter names captured by the route's root layout. */\n rootParamNames?: 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\nfunction hasParallelSlotDirectory(dir: string): boolean {\n try {\n return fs\n .readdirSync(dir, { withFileTypes: true })\n .some((entry) => entry.isDirectory() && entry.name.startsWith(\"@\"));\n } catch {\n return false;\n }\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 // Layouts with parallel slot pages are valid route entries even when the\n // segment has no children page. Next.js uses this for modal/feed patterns\n // like app/user/[id]/layout + @feed/page + @modal/default.\n const routePatterns = new Set(routes.map((route) => route.pattern));\n for await (const file of scanWithExtensions(\n \"**/layout\",\n appDir,\n matcher.extensions,\n excludeDir,\n )) {\n const dir = path.dirname(file);\n const routeDir = dir === \".\" ? appDir : path.join(appDir, dir);\n if (!hasParallelSlotDirectory(routeDir)) continue;\n if (discoverParallelSlots(routeDir, appDir, matcher).length === 0) continue;\n\n const route = directoryToAppRoute(dir, appDir, matcher, null, null);\n if (!route || routePatterns.has(route.pattern)) continue;\n\n routes.push(route);\n routePatterns.add(route.pattern);\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 validatePageRouteConflicts(routes, appDir);\n validateRoutePatterns(routes.map((route) => route.pattern));\n const interceptTargetPatterns = [\n ...new Set(\n routes.flatMap((route) =>\n route.parallelSlots.flatMap((slot) =>\n slot.interceptingRoutes.map((intercept) => intercept.targetPattern),\n ),\n ),\n ),\n ];\n validateRoutePatterns(interceptTargetPatterns);\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\nfunction validatePageRouteConflicts(routes: AppRoute[], appDir: string): void {\n const byPattern = new Map<string, { pagePath: string | null; routePath: string | null }>();\n\n // validateRoutePatterns() would also reject page/route pairs because they\n // share a URL pattern. Keep this pass first so the error names both files.\n for (const route of routes) {\n const entry = byPattern.get(route.pattern);\n if (!entry) {\n byPattern.set(route.pattern, {\n pagePath: route.pagePath,\n routePath: route.routePath,\n });\n continue;\n }\n\n if (!entry.pagePath && route.pagePath) {\n entry.pagePath = route.pagePath;\n }\n if (!entry.routePath && route.routePath) {\n entry.routePath = route.routePath;\n }\n }\n\n for (const [pattern, entry] of byPattern) {\n if (!entry.pagePath || !entry.routePath) continue;\n\n throw new Error(\n `Conflicting route and page at ${pattern}: route at ${formatAppFilePath(\n entry.routePath,\n appDir,\n )} and page at ${formatAppFilePath(entry.pagePath, appDir)}`,\n );\n }\n}\n\nfunction formatAppFilePath(filePath: string, appDir: string): string {\n const relativePath = path.relative(appDir, filePath).replace(/\\\\/g, \"/\");\n const parsedPath = path.parse(relativePath);\n const withoutExtension = path.join(parsedPath.dir, parsedPath.name).replace(/\\\\/g, \"/\");\n return withoutExtension.startsWith(\"/\") ? withoutExtension : `/${withoutExtension}`;\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 applySlotSubPages = (\n route: AppRoute,\n slotPages: Map<string, string>,\n rawSegments: string[],\n ): void => {\n route.parallelSlots = route.parallelSlots.map((slot) => {\n const subPage = slotPages.get(slot.key);\n if (subPage !== undefined) {\n return { ...slot, pagePath: subPage, routeSegments: rawSegments };\n }\n return slot;\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 // Only scan sub-pages from slots owned by this route directory.\n // Inherited slots with the same name live in different owner dirs.\n if (path.dirname(slot.ownerDir) !== parentPageDir) {\n continue;\n }\n const slotDir = slot.ownerDir;\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 existingSlotPage = subPathEntry.slotPages.get(slot.key);\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(slot.key, 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, rawSegments);\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 const subPage = slotPages.get(slot.key);\n return {\n ...slot,\n pagePath: subPage || null,\n routeSegments: subPage ? rawSegments : null,\n };\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 forbiddenPaths: parentRoute.forbiddenPaths,\n forbiddenPath: parentRoute.forbiddenPath,\n unauthorizedPath: parentRoute.unauthorizedPath,\n unauthorizedPaths: parentRoute.unauthorizedPaths,\n routeSegments: [...parentRoute.routeSegments, ...rawSegments],\n templateTreePositions: parentRoute.templateTreePositions,\n layoutTreePositions: parentRoute.layoutTreePositions,\n isDynamic: parentRoute.isDynamic || subIsDynamic,\n params: [...parentRoute.params, ...subParams],\n rootParamNames: parentRoute.rootParamNames,\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 return directoryToAppRoute(\n dir,\n appDir,\n matcher,\n type === \"page\" ? path.join(appDir, file) : null,\n type === \"route\" ? path.join(appDir, file) : null,\n );\n}\n\nfunction directoryToAppRoute(\n dir: string,\n appDir: string,\n matcher: ValidFileMatcher,\n pagePath: string | null,\n routePath: string | null,\n): AppRoute | null {\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 const templateTreePositions = computeLayoutTreePositions(appDir, templates);\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 const forbiddenPaths = discoverBoundaryFilePerLayout(layouts, \"forbidden\", matcher);\n const unauthorizedPaths = discoverBoundaryFilePerLayout(layouts, \"unauthorized\", 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,\n routePath,\n layouts,\n templates,\n parallelSlots,\n loadingPath,\n errorPath,\n layoutErrorPaths,\n notFoundPath,\n notFoundPaths,\n forbiddenPaths,\n forbiddenPath,\n unauthorizedPath,\n unauthorizedPaths,\n routeSegments: segments,\n templateTreePositions,\n layoutTreePositions,\n isDynamic,\n params,\n rootParamNames: computeRootParamNames(segments, layoutTreePositions),\n patternParts: urlSegments,\n };\n}\n\nfunction dynamicParamNameFromSegment(segment: string): string | null {\n if (segment.startsWith(\"[[...\") && segment.endsWith(\"]]\")) return segment.slice(5, -2);\n if (segment.startsWith(\"[...\") && segment.endsWith(\"]\")) return segment.slice(4, -1);\n if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) return segment.slice(1, -1);\n return null;\n}\n\nexport function computeRootParamNames(\n routeSegments: readonly string[],\n layoutTreePositions: readonly number[],\n): string[] {\n const rootLayoutPosition = layoutTreePositions[0];\n if (rootLayoutPosition == null || rootLayoutPosition <= 0) return [];\n\n const names: string[] = [];\n for (const segment of routeSegments.slice(0, rootLayoutPosition)) {\n const name = dynamicParamNameFromSegment(segment);\n if (name && !names.includes(name)) names.push(name);\n }\n return names;\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 });\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 });\n }\n\n const routeHasLayout = layoutIdx >= 0;\n\n for (const { dir, layoutIdx: lvlLayoutIdx } of dirsToCheck) {\n // Once a route has a root layout below app/, slots discovered before that\n // layout are above the root and cannot be owned by any layout in this route.\n // Layout-less routes keep their legacy slot metadata here; validation is separate.\n if (lvlLayoutIdx < 0 && routeHasLayout) continue;\n\n const isOwnDir = dir === routeDir;\n const slotLayoutIdx = Math.max(lvlLayoutIdx, 0);\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 = slotLayoutIdx;\n slotMap.set(slot.key, 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: slotLayoutIdx,\n routeSegments: null,\n // defaultPath, loadingPath, errorPath, interceptingRoutes remain\n };\n slotMap.set(slot.key, 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 key: `${slotName}@${path.relative(appDir, slotDir).replace(/\\\\/g, \"/\")}`,\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 routeSegments: pagePath ? [] : null,\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 parentLayoutPaths: readonly string[] = [],\n): void {\n const currentLayoutPath = findFile(currentDir, \"layout\", matcher);\n const layoutPaths = currentLayoutPath\n ? [...parentLayoutPaths, currentLayoutPath]\n : parentLayoutPaths;\n\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 layoutPaths: [...layoutPaths],\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 layoutPaths,\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 if (climbed < levelsToClimb) {\n const interceptionRoute = formatInterceptionRoutePath(\n routeSegments,\n convention,\n interceptSegment,\n path.relative(interceptRoot, currentDir).split(path.sep).filter(Boolean),\n );\n if (convention === \"..\") {\n throw new Error(\n `Invalid interception route: ${interceptionRoute}. Cannot use (..) marker at the root level, use (.) instead.`,\n );\n }\n throw new Error(\n `Invalid interception route: ${interceptionRoute}. Cannot use (..)(..) marker at the root level or one level up.`,\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\nfunction formatInterceptionRoutePath(\n routeSegments: string[],\n convention: string,\n interceptSegment: string,\n nestedParts: string[],\n): string {\n const marker = markerForInterceptionConvention(convention);\n const convertedRoute = convertSegmentsToRouteParts(routeSegments);\n const prefix = convertedRoute\n ? convertedRoute.urlSegments\n : routeSegments.filter((segment) => !isInvisibleSegment(segment));\n const routePath = [...prefix, `${marker}${interceptSegment}`, ...nestedParts]\n .filter(Boolean)\n .join(\"/\");\n return routePath ? `/${routePath}` : \"/\";\n}\n\nfunction markerForInterceptionConvention(convention: string): string {\n switch (convention) {\n case \".\":\n return \"(.)\";\n case \"..\":\n return \"(..)\";\n case \"../..\":\n return \"(..)(..)\";\n case \"...\":\n return \"(...)\";\n default:\n return \"\";\n }\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":";;;;;;;;;;;;;;;;;;;;;;AAmJA,IAAI,eAAkC;AACtC,IAAI,eAA8B;AAClC,IAAI,0BAAyC;AAE7C,SAAgB,0BAAgC;AAC9C,gBAAe;AACf,gBAAe;AACf,2BAA0B;;AAG5B,SAAS,yBAAyB,KAAsB;AACtD,KAAI;AACF,SAAO,GACJ,YAAY,KAAK,EAAE,eAAe,MAAM,CAAC,CACzC,MAAM,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AIT,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"}
|
|
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 { createValidFileMatcher, type ValidFileMatcher } from \"./file-matcher.js\";\nimport { createRouteTrieCache, matchRouteWithTrie } from \"./route-matching.js\";\nimport {\n buildAppRouteGraph,\n type AppRoute,\n type AppRouteGraphRoute,\n type RouteManifest,\n} from \"./app-route-graph.js\";\nexport type { AppRoute } from \"./app-route-graph.js\";\nexport { computeRootParamNames } from \"./app-route-graph.js\";\n\ntype AppRouteGraph = {\n routes: AppRouteGraphRoute[];\n routeManifest: RouteManifest;\n};\n\n// Cache for app routes\nlet cachedGraph: AppRouteGraph | null = null;\nlet cachedAppDir: string | null = null;\nlet cachedPageExtensionsKey: string | null = null;\n\nexport function invalidateAppRouteCache(): void {\n cachedGraph = null;\n cachedAppDir = null;\n cachedPageExtensionsKey = null;\n}\n\n/**\n * Scan the app/ directory and return the route graph.\n * TODO(#726): Layer 4 should consume this read model directly once the\n * navigation planner owns route graph facts.\n *\n * @internal\n */\nexport async function appRouteGraph(\n appDir: string,\n pageExtensions?: readonly string[],\n matcher?: ValidFileMatcher,\n): Promise<AppRouteGraph> {\n matcher ??= createValidFileMatcher(pageExtensions);\n const pageExtensionsKey = JSON.stringify(matcher.extensions);\n if (cachedGraph && cachedAppDir === appDir && cachedPageExtensionsKey === pageExtensionsKey) {\n return cachedGraph;\n }\n\n const graph = await buildAppRouteGraph(appDir, matcher);\n cachedGraph = graph;\n cachedAppDir = appDir;\n cachedPageExtensionsKey = pageExtensionsKey;\n return graph;\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<AppRouteGraphRoute[]> {\n const graph = await appRouteGraph(appDir, pageExtensions, matcher);\n return graph.routes;\n}\n\n// Trie cache — keyed by route array identity (same array = same trie)\nconst appTrieCache = createRouteTrieCache<AppRoute>();\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 return matchRouteWithTrie(url, routes, appTrieCache);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgCA,IAAI,cAAoC;AACxC,IAAI,eAA8B;AAClC,IAAI,0BAAyC;AAE7C,SAAgB,0BAAgC;AAC9C,eAAc;AACd,gBAAe;AACf,2BAA0B;;;;;;;;;AAU5B,eAAsB,cACpB,QACA,gBACA,SACwB;AACxB,aAAY,uBAAuB,eAAe;CAClD,MAAM,oBAAoB,KAAK,UAAU,QAAQ,WAAW;AAC5D,KAAI,eAAe,iBAAiB,UAAU,4BAA4B,kBACxE,QAAO;CAGT,MAAM,QAAQ,MAAM,mBAAmB,QAAQ,QAAQ;AACvD,eAAc;AACd,gBAAe;AACf,2BAA0B;AAC1B,QAAO;;;;;AAMT,eAAsB,UACpB,QACA,gBACA,SAC+B;AAE/B,SADc,MAAM,cAAc,QAAQ,gBAAgB,QAAQ,EACrD;;AAIf,MAAM,eAAe,sBAAgC;;;;AAKrD,SAAgB,cACd,KACA,QACuE;AACvE,QAAO,mBAAmB,KAAK,QAAQ,aAAa"}
|
|
@@ -16,10 +16,12 @@ type ValidFileMatcher = {
|
|
|
16
16
|
* packages/next/src/server/lib/find-page-file.ts
|
|
17
17
|
*/
|
|
18
18
|
declare function createValidFileMatcher(pageExtensions?: readonly string[] | null): ValidFileMatcher;
|
|
19
|
+
/** Check if a file exists with any configured page extension. */
|
|
20
|
+
declare function findFileWithExtensions(basePath: string, matcher: ValidFileMatcher): boolean;
|
|
19
21
|
/**
|
|
20
22
|
* Use function-form exclude for Node < 22.14 compatibility.
|
|
21
23
|
*/
|
|
22
24
|
declare function scanWithExtensions(stem: string, cwd: string, extensions: readonly string[], exclude?: (name: string) => boolean): AsyncGenerator<string>;
|
|
23
25
|
//#endregion
|
|
24
|
-
export { ValidFileMatcher, createValidFileMatcher, normalizePageExtensions, scanWithExtensions };
|
|
26
|
+
export { ValidFileMatcher, createValidFileMatcher, findFileWithExtensions, normalizePageExtensions, scanWithExtensions };
|
|
25
27
|
//# sourceMappingURL=file-matcher.d.ts.map
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
1
2
|
import { glob } from "node:fs/promises";
|
|
2
3
|
//#region src/routing/file-matcher.ts
|
|
3
4
|
const DEFAULT_PAGE_EXTENSIONS = [
|
|
@@ -59,6 +60,10 @@ function createValidFileMatcher(pageExtensions) {
|
|
|
59
60
|
}
|
|
60
61
|
};
|
|
61
62
|
}
|
|
63
|
+
/** Check if a file exists with any configured page extension. */
|
|
64
|
+
function findFileWithExtensions(basePath, matcher) {
|
|
65
|
+
return matcher.dottedExtensions.some((ext) => existsSync(basePath + ext));
|
|
66
|
+
}
|
|
62
67
|
/**
|
|
63
68
|
* Use function-form exclude for Node < 22.14 compatibility.
|
|
64
69
|
*/
|
|
@@ -70,6 +75,6 @@ async function* scanWithExtensions(stem, cwd, extensions, exclude) {
|
|
|
70
75
|
})) yield file;
|
|
71
76
|
}
|
|
72
77
|
//#endregion
|
|
73
|
-
export { createValidFileMatcher, normalizePageExtensions, scanWithExtensions };
|
|
78
|
+
export { createValidFileMatcher, findFileWithExtensions, normalizePageExtensions, scanWithExtensions };
|
|
74
79
|
|
|
75
80
|
//# sourceMappingURL=file-matcher.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-matcher.js","names":[],"sources":["../../src/routing/file-matcher.ts"],"sourcesContent":["import { glob } from \"node:fs/promises\";\n\nconst 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\nfunction 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":"
|
|
1
|
+
{"version":3,"file":"file-matcher.js","names":[],"sources":["../../src/routing/file-matcher.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { glob } from \"node:fs/promises\";\n\nconst 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\nfunction 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/** Check if a file exists with any configured page extension. */\nexport function findFileWithExtensions(basePath: string, matcher: ValidFileMatcher): boolean {\n return matcher.dottedExtensions.some((ext) => existsSync(basePath + ext));\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":";;;AAGA,MAAM,0BAA0B;CAAC;CAAO;CAAM;CAAO;CAAK;AAE1D,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;CA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B;AAChC,UAAO,eAAe,KAAK,SAAS;;EAEtC,iBAAiB,UAAkB;AACjC,UAAO,gBAAgB,KAAK,SAAS;;EAEvC,eAAe,UAAkB;AAC/B,UAAO,SAAS,QAAQ,gBAAgB,GAAG;;EAE9C;;;AAIH,SAAgB,uBAAuB,UAAkB,SAAoC;AAC3F,QAAO,QAAQ,iBAAiB,MAAM,QAAQ,WAAW,WAAW,IAAI,CAAC;;;;;AAM3E,gBAAuB,mBACrB,MACA,KACA,YACA,SACwB;CACxB,MAAM,UAAU,mBAAmB,MAAM,WAAW;AACpD,YAAW,MAAM,QAAQ,KAAK,SAAS;EACrC;EACA,GAAI,UAAU,EAAE,SAAS,GAAG,EAAE;EAC/B,CAAC,CACA,OAAM"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { compareRoutes, decodeRouteSegment
|
|
1
|
+
import { compareRoutes, decodeRouteSegment } from "./utils.js";
|
|
2
2
|
import { createValidFileMatcher, scanWithExtensions } from "./file-matcher.js";
|
|
3
3
|
import { patternToNextFormat, validateRoutePatterns } from "./route-validation.js";
|
|
4
|
-
import {
|
|
4
|
+
import { createRouteTrieCache, matchRouteWithTrie } from "./route-matching.js";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
//#region src/routing/pages-router.ts
|
|
7
7
|
const routeCache = /* @__PURE__ */ new Map();
|
|
@@ -64,24 +64,27 @@ function fileToRoute(file, pagesDir, matcher) {
|
|
|
64
64
|
const urlSegments = [];
|
|
65
65
|
for (let i = 0; i < segments.length; i++) {
|
|
66
66
|
const segment = segments[i];
|
|
67
|
-
const catchAllMatch = segment.match(/^\[\.\.\.([
|
|
67
|
+
const catchAllMatch = segment.match(/^\[\.\.\.([^\]]+)\]$/);
|
|
68
68
|
if (catchAllMatch) {
|
|
69
69
|
if (i !== segments.length - 1) return null;
|
|
70
|
+
if (catchAllMatch[1].endsWith("+") || catchAllMatch[1].endsWith("*")) return null;
|
|
70
71
|
isDynamic = true;
|
|
71
72
|
params.push(catchAllMatch[1]);
|
|
72
73
|
urlSegments.push(`:${catchAllMatch[1]}+`);
|
|
73
74
|
continue;
|
|
74
75
|
}
|
|
75
|
-
const optionalCatchAllMatch = segment.match(/^\[\[\.\.\.([
|
|
76
|
+
const optionalCatchAllMatch = segment.match(/^\[\[\.\.\.([^\]]+)\]\]$/);
|
|
76
77
|
if (optionalCatchAllMatch) {
|
|
77
78
|
if (i !== segments.length - 1) return null;
|
|
79
|
+
if (optionalCatchAllMatch[1].endsWith("+") || optionalCatchAllMatch[1].endsWith("*")) return null;
|
|
78
80
|
isDynamic = true;
|
|
79
81
|
params.push(optionalCatchAllMatch[1]);
|
|
80
82
|
urlSegments.push(`:${optionalCatchAllMatch[1]}*`);
|
|
81
83
|
continue;
|
|
82
84
|
}
|
|
83
|
-
const dynamicMatch = segment.match(/^\[([
|
|
85
|
+
const dynamicMatch = segment.match(/^\[([^\]]+)\]$/);
|
|
84
86
|
if (dynamicMatch) {
|
|
87
|
+
if (dynamicMatch[1].endsWith("+") || dynamicMatch[1].endsWith("*")) return null;
|
|
85
88
|
isDynamic = true;
|
|
86
89
|
params.push(dynamicMatch[1]);
|
|
87
90
|
urlSegments.push(`:${dynamicMatch[1]}`);
|
|
@@ -98,25 +101,13 @@ function fileToRoute(file, pagesDir, matcher) {
|
|
|
98
101
|
params
|
|
99
102
|
};
|
|
100
103
|
}
|
|
101
|
-
const trieCache =
|
|
102
|
-
function getOrBuildTrie(routes) {
|
|
103
|
-
let trie = trieCache.get(routes);
|
|
104
|
-
if (!trie) {
|
|
105
|
-
trie = buildRouteTrie(routes);
|
|
106
|
-
trieCache.set(routes, trie);
|
|
107
|
-
}
|
|
108
|
-
return trie;
|
|
109
|
-
}
|
|
104
|
+
const trieCache = createRouteTrieCache();
|
|
110
105
|
/**
|
|
111
106
|
* Match a URL path against a route pattern.
|
|
112
107
|
* Returns the matched params or null if no match.
|
|
113
108
|
*/
|
|
114
109
|
function matchRoute(url, routes) {
|
|
115
|
-
|
|
116
|
-
let normalizedUrl = pathname === "/" ? "/" : pathname.replace(/\/$/, "");
|
|
117
|
-
normalizedUrl = normalizePathnameForRouteMatch(normalizedUrl);
|
|
118
|
-
const urlParts = normalizedUrl.split("/").filter(Boolean);
|
|
119
|
-
return trieMatch(getOrBuildTrie(routes), urlParts);
|
|
110
|
+
return matchRouteWithTrie(url, routes, trieCache);
|
|
120
111
|
}
|
|
121
112
|
/**
|
|
122
113
|
* Scan the pages/api/ directory and return API routes.
|
|
@@ -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 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,WAA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ACkB;AAClB,aAAY,uBAAuB,eAAe;CAClD,MAAM,WAAW,OAAO,SAAS,GAAG,KAAK,UAAU,QAAQ,WAAW;CACtE,MAAM,SAAS,WAAW,IAAI,SAAS;AACvC,KAAI,OAAQ,QAAO,OAAO;CAE1B,MAAM,UAAU,cAAc,UAAU,QAAQ;AAChD,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,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"}
|
|
1
|
+
{"version":3,"file":"pages-router.js","names":[],"sources":["../../src/routing/pages-router.ts"],"sourcesContent":["import path from \"node:path\";\nimport { compareRoutes, decodeRouteSegment } from \"./utils.js\";\nimport {\n createValidFileMatcher,\n scanWithExtensions,\n type ValidFileMatcher,\n} from \"./file-matcher.js\";\nimport { patternToNextFormat, validateRoutePatterns } from \"./route-validation.js\";\nimport { createRouteTrieCache, matchRouteWithTrie } from \"./route-matching.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 any non-] chars)\n // Matches Next.js PARAMETER_PATTERN.\n const catchAllMatch = segment.match(/^\\[\\.\\.\\.([^\\]]+)\\]$/);\n if (catchAllMatch) {\n if (i !== segments.length - 1) return null;\n // Guard: names ending in + or * would collide with internal pattern modifiers.\n if (catchAllMatch[1].endsWith(\"+\") || catchAllMatch[1].endsWith(\"*\")) 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 any non-] chars)\n const optionalCatchAllMatch = segment.match(/^\\[\\[\\.\\.\\.([^\\]]+)\\]\\]$/);\n if (optionalCatchAllMatch) {\n if (i !== segments.length - 1) return null;\n if (optionalCatchAllMatch[1].endsWith(\"+\") || optionalCatchAllMatch[1].endsWith(\"*\"))\n 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 any non-] chars)\n const dynamicMatch = segment.match(/^\\[([^\\]]+)\\]$/);\n if (dynamicMatch) {\n if (dynamicMatch[1].endsWith(\"+\") || dynamicMatch[1].endsWith(\"*\")) return null;\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 = createRouteTrieCache<Route>();\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 return matchRouteWithTrie(url, routes, trieCache);\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,QAA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.js";
|
|
2
|
+
|
|
3
|
+
//#region src/routing/route-matching.d.ts
|
|
4
|
+
type RouteTrieCache<R extends {
|
|
5
|
+
patternParts: string[];
|
|
6
|
+
}> = WeakMap<R[], TrieNode<R>>;
|
|
7
|
+
declare function createRouteTrieCache<R extends {
|
|
8
|
+
patternParts: string[];
|
|
9
|
+
}>(): RouteTrieCache<R>;
|
|
10
|
+
/**
|
|
11
|
+
* Match a URL path against a list of routes via the shared preamble:
|
|
12
|
+
* 1. strip query string
|
|
13
|
+
* 2. trailing-slash normalize (preserving root "/")
|
|
14
|
+
* 3. run `normalizePathnameForRouteMatch`
|
|
15
|
+
* 4. split into url parts and look up via the (cached) trie
|
|
16
|
+
*
|
|
17
|
+
* Generic over the route shape; both Pages `Route` and App `AppRoute`
|
|
18
|
+
* satisfy `{ patternParts: string[] }`.
|
|
19
|
+
*/
|
|
20
|
+
declare function matchRouteWithTrie<R extends {
|
|
21
|
+
patternParts: string[];
|
|
22
|
+
}>(url: string, routes: R[], cache: RouteTrieCache<R>): {
|
|
23
|
+
route: R;
|
|
24
|
+
params: Record<string, string | string[]>;
|
|
25
|
+
} | null;
|
|
26
|
+
//#endregion
|
|
27
|
+
export { createRouteTrieCache, matchRouteWithTrie };
|
|
28
|
+
//# sourceMappingURL=route-matching.d.ts.map
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { normalizePathnameForRouteMatch } from "./utils.js";
|
|
2
|
+
import { buildRouteTrie, trieMatch } from "./route-trie.js";
|
|
3
|
+
//#region src/routing/route-matching.ts
|
|
4
|
+
/**
|
|
5
|
+
* Shared route-match preamble used by both Pages Router and App Router.
|
|
6
|
+
*
|
|
7
|
+
* Both routers normalize URLs and call `trieMatch` with nearly-identical
|
|
8
|
+
* preamble: strip query, trailing-slash normalize, run
|
|
9
|
+
* `normalizePathnameForRouteMatch`, split into url parts, then look up via a
|
|
10
|
+
* per-routes-array trie cache. This module factors that out so each router
|
|
11
|
+
* just calls `matchRouteWithTrie(url, routes)`.
|
|
12
|
+
*/
|
|
13
|
+
function createRouteTrieCache() {
|
|
14
|
+
return /* @__PURE__ */ new WeakMap();
|
|
15
|
+
}
|
|
16
|
+
function getOrBuildTrie(cache, routes) {
|
|
17
|
+
let trie = cache.get(routes);
|
|
18
|
+
if (!trie) {
|
|
19
|
+
trie = buildRouteTrie(routes);
|
|
20
|
+
cache.set(routes, trie);
|
|
21
|
+
}
|
|
22
|
+
return trie;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Match a URL path against a list of routes via the shared preamble:
|
|
26
|
+
* 1. strip query string
|
|
27
|
+
* 2. trailing-slash normalize (preserving root "/")
|
|
28
|
+
* 3. run `normalizePathnameForRouteMatch`
|
|
29
|
+
* 4. split into url parts and look up via the (cached) trie
|
|
30
|
+
*
|
|
31
|
+
* Generic over the route shape; both Pages `Route` and App `AppRoute`
|
|
32
|
+
* satisfy `{ patternParts: string[] }`.
|
|
33
|
+
*/
|
|
34
|
+
function matchRouteWithTrie(url, routes, cache) {
|
|
35
|
+
const pathname = url.split("?")[0];
|
|
36
|
+
let normalizedUrl = pathname === "/" ? "/" : pathname.replace(/\/$/, "");
|
|
37
|
+
normalizedUrl = normalizePathnameForRouteMatch(normalizedUrl);
|
|
38
|
+
const urlParts = normalizedUrl.split("/").filter(Boolean);
|
|
39
|
+
return trieMatch(getOrBuildTrie(cache, routes), urlParts);
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
export { createRouteTrieCache, matchRouteWithTrie };
|
|
43
|
+
|
|
44
|
+
//# sourceMappingURL=route-matching.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"route-matching.js","names":[],"sources":["../../src/routing/route-matching.ts"],"sourcesContent":["/**\n * Shared route-match preamble used by both Pages Router and App Router.\n *\n * Both routers normalize URLs and call `trieMatch` with nearly-identical\n * preamble: strip query, trailing-slash normalize, run\n * `normalizePathnameForRouteMatch`, split into url parts, then look up via a\n * per-routes-array trie cache. This module factors that out so each router\n * just calls `matchRouteWithTrie(url, routes)`.\n */\nimport { normalizePathnameForRouteMatch } from \"./utils.js\";\nimport { buildRouteTrie, trieMatch, type TrieNode } from \"./route-trie.js\";\n\n// Trie cache — keyed by route array identity (same array = same trie).\n// Each caller gets its own cache via `createRouteTrieCache()`, so different\n// route shapes (Pages routes vs App routes) don't share a cache slot.\ntype RouteTrieCache<R extends { patternParts: string[] }> = WeakMap<R[], TrieNode<R>>;\n\nexport function createRouteTrieCache<R extends { patternParts: string[] }>(): RouteTrieCache<R> {\n return new WeakMap<R[], TrieNode<R>>();\n}\n\nfunction getOrBuildTrie<R extends { patternParts: string[] }>(\n cache: RouteTrieCache<R>,\n routes: R[],\n): TrieNode<R> {\n let trie = cache.get(routes);\n if (!trie) {\n trie = buildRouteTrie(routes);\n cache.set(routes, trie);\n }\n return trie;\n}\n\n/**\n * Match a URL path against a list of routes via the shared preamble:\n * 1. strip query string\n * 2. trailing-slash normalize (preserving root \"/\")\n * 3. run `normalizePathnameForRouteMatch`\n * 4. split into url parts and look up via the (cached) trie\n *\n * Generic over the route shape; both Pages `Route` and App `AppRoute`\n * satisfy `{ patternParts: string[] }`.\n */\nexport function matchRouteWithTrie<R extends { patternParts: string[] }>(\n url: string,\n routes: R[],\n cache: RouteTrieCache<R>,\n): { route: R; 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(cache, routes);\n return trieMatch(trie, urlParts);\n}\n"],"mappings":";;;;;;;;;;;;AAiBA,SAAgB,uBAAgF;AAC9F,wBAAO,IAAI,SAA2B;;AAGxC,SAAS,eACP,OACA,QACa;CACb,IAAI,OAAO,MAAM,IAAI,OAAO;AAC5B,KAAI,CAAC,MAAM;AACT,SAAO,eAAe,OAAO;AAC7B,QAAM,IAAI,QAAQ,KAAK;;AAEzB,QAAO;;;;;;;;;;;;AAaT,SAAgB,mBACd,KACA,QACA,OACgE;CAEhE,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,eAAe,OAAO,OAAO,EACnB,SAAS"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { decodeMatchedParams } from "./utils.js";
|
|
1
2
|
//#region src/routing/route-pattern.ts
|
|
2
3
|
function routePatternPart(segment) {
|
|
3
4
|
if (segment.startsWith("[[...") && segment.endsWith("]]")) return `:${segment.slice(5, -2)}*`;
|
|
@@ -82,7 +83,9 @@ function matchRoutePattern(urlParts, patternParts) {
|
|
|
82
83
|
if (urlIndex >= urlParts.length || urlParts[urlIndex] !== patternPart) return false;
|
|
83
84
|
return matchFrom(urlIndex + 1, patternIndex + 1);
|
|
84
85
|
}
|
|
85
|
-
|
|
86
|
+
if (!matchFrom(0, 0)) return null;
|
|
87
|
+
decodeMatchedParams(params);
|
|
88
|
+
return params;
|
|
86
89
|
}
|
|
87
90
|
//#endregion
|
|
88
91
|
export { fillRoutePatternSegments, matchRoutePattern, routePattern, routePatternParts };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route-pattern.js","names":[],"sources":["../../src/routing/route-pattern.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"route-pattern.js","names":[],"sources":["../../src/routing/route-pattern.ts"],"sourcesContent":["import { decodeMatchedParams } from \"./utils\";\n\nexport type RoutePatternParams = Record<string, string | string[]>;\n\nfunction routePatternPart(segment: string): string {\n if (segment.startsWith(\"[[...\") && segment.endsWith(\"]]\")) {\n return `:${segment.slice(5, -2)}*`;\n }\n if (segment.startsWith(\"[...\") && segment.endsWith(\"]\")) {\n return `:${segment.slice(4, -1)}+`;\n }\n if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n return `:${segment.slice(1, -1)}`;\n }\n return segment;\n}\n\nexport function routePatternParts(pathname: string): string[] {\n return pathname.split(\"/\").filter(Boolean).map(routePatternPart);\n}\n\nexport function routePattern(pathname: string): string {\n const parts = routePatternParts(pathname);\n return parts.length > 0 ? `/${parts.join(\"/\")}` : \"\";\n}\n\nfunction appendParamValue(target: string[], value: string | string[]): void {\n if (Array.isArray(value)) {\n for (const entry of value) {\n target.push(entry);\n }\n return;\n }\n\n target.push(value);\n}\n\nexport function fillRoutePatternSegments(\n pathname: string,\n params: RoutePatternParams,\n): string | null {\n const segments = pathname.split(\"/\").filter(Boolean);\n const resolvedSegments: string[] = [];\n\n for (const segment of segments) {\n if (segment.startsWith(\"[[...\") && segment.endsWith(\"]]\")) {\n const paramName = segment.slice(5, -2);\n const value = params[paramName];\n if (value !== undefined && value !== \"\") {\n if (Array.isArray(value) && value.length === 0) {\n continue;\n }\n appendParamValue(resolvedSegments, value);\n }\n continue;\n }\n\n if (segment.startsWith(\"[...\") && segment.endsWith(\"]\")) {\n const paramName = segment.slice(4, -1);\n const value = params[paramName];\n if (value === undefined || (Array.isArray(value) ? value.length === 0 : value === \"\")) {\n return null;\n }\n appendParamValue(resolvedSegments, value);\n continue;\n }\n\n if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n const paramName = segment.slice(1, -1);\n const value = params[paramName];\n if (typeof value === \"string\") {\n resolvedSegments.push(value);\n continue;\n }\n if (Array.isArray(value) && value.length > 0) {\n if (value.length > 1) {\n return null;\n }\n resolvedSegments.push(value[0]);\n continue;\n }\n return null;\n }\n\n resolvedSegments.push(segment);\n }\n\n return resolvedSegments.length > 0 ? `/${resolvedSegments.join(\"/\")}` : \"/\";\n}\n\nexport function matchRoutePattern(\n urlParts: readonly string[],\n patternParts: readonly string[],\n): RoutePatternParams | null {\n const params: RoutePatternParams = Object.create(null);\n\n function matchFrom(urlIndex: number, patternIndex: number): boolean {\n if (patternIndex === patternParts.length) {\n return urlIndex === urlParts.length;\n }\n\n const patternPart = patternParts[patternIndex];\n if (patternPart.startsWith(\":\") && (patternPart.endsWith(\"+\") || patternPart.endsWith(\"*\"))) {\n const paramName = patternPart.slice(1, -1);\n const minLength = patternPart.endsWith(\"+\") ? 1 : 0;\n for (let endIndex = urlIndex + minLength; endIndex <= urlParts.length; endIndex++) {\n const value = urlParts.slice(urlIndex, endIndex);\n if (value.length > 0) {\n params[paramName] = value;\n } else {\n delete params[paramName];\n }\n if (matchFrom(endIndex, patternIndex + 1)) {\n return true;\n }\n }\n delete params[paramName];\n return false;\n }\n\n if (patternPart.startsWith(\":\")) {\n if (urlIndex >= urlParts.length) {\n return false;\n }\n const paramName = patternPart.slice(1);\n params[paramName] = urlParts[urlIndex];\n if (matchFrom(urlIndex + 1, patternIndex + 1)) {\n return true;\n }\n delete params[paramName];\n return false;\n }\n\n if (urlIndex >= urlParts.length || urlParts[urlIndex] !== patternPart) {\n return false;\n }\n return matchFrom(urlIndex + 1, patternIndex + 1);\n }\n\n if (!matchFrom(0, 0)) return null;\n decodeMatchedParams(params);\n return params;\n}\n"],"mappings":";;AAIA,SAAS,iBAAiB,SAAyB;AACjD,KAAI,QAAQ,WAAW,QAAQ,IAAI,QAAQ,SAAS,KAAK,CACvD,QAAO,IAAI,QAAQ,MAAM,GAAG,GAAG,CAAC;AAElC,KAAI,QAAQ,WAAW,OAAO,IAAI,QAAQ,SAAS,IAAI,CACrD,QAAO,IAAI,QAAQ,MAAM,GAAG,GAAG,CAAC;AAElC,KAAI,QAAQ,WAAW,IAAI,IAAI,QAAQ,SAAS,IAAI,CAClD,QAAO,IAAI,QAAQ,MAAM,GAAG,GAAG;AAEjC,QAAO;;AAGT,SAAgB,kBAAkB,UAA4B;AAC5D,QAAO,SAAS,MAAM,IAAI,CAAC,OAAO,QAAQ,C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
|
|
50
|
+
* Returns decoded param values — `decodeURIComponent` is applied to
|
|
51
|
+
* individual param entries so that `%2F` → `/`, `%23` → `#`, etc.
|
|
52
|
+
* Segment boundaries (the original `/` splits) are preserved by the
|
|
53
|
+
* upstream normalization layer; this step only decodes the captured
|
|
54
|
+
* param strings the caller sees.
|
|
55
|
+
*
|
|
56
|
+
* Mirrors Next.js route-matcher.ts:25-27.
|
|
57
|
+
*
|
|
50
58
|
* @param root - Trie root built by `buildRouteTrie`
|
|
51
59
|
* @param urlParts - Pre-split URL segments (no empty strings)
|
|
52
60
|
* @returns Match result with route and extracted params, or null
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { decodeMatchedParams } from "./utils.js";
|
|
1
2
|
//#region src/routing/route-trie.ts
|
|
2
3
|
function createNode() {
|
|
3
4
|
return {
|
|
@@ -78,12 +79,22 @@ function buildRouteTrie(routes) {
|
|
|
78
79
|
/**
|
|
79
80
|
* Match a URL against the trie.
|
|
80
81
|
*
|
|
82
|
+
* Returns decoded param values — `decodeURIComponent` is applied to
|
|
83
|
+
* individual param entries so that `%2F` → `/`, `%23` → `#`, etc.
|
|
84
|
+
* Segment boundaries (the original `/` splits) are preserved by the
|
|
85
|
+
* upstream normalization layer; this step only decodes the captured
|
|
86
|
+
* param strings the caller sees.
|
|
87
|
+
*
|
|
88
|
+
* Mirrors Next.js route-matcher.ts:25-27.
|
|
89
|
+
*
|
|
81
90
|
* @param root - Trie root built by `buildRouteTrie`
|
|
82
91
|
* @param urlParts - Pre-split URL segments (no empty strings)
|
|
83
92
|
* @returns Match result with route and extracted params, or null
|
|
84
93
|
*/
|
|
85
94
|
function trieMatch(root, urlParts) {
|
|
86
|
-
|
|
95
|
+
const result = match(root, urlParts, 0);
|
|
96
|
+
if (result) decodeMatchedParams(result.params);
|
|
97
|
+
return result;
|
|
87
98
|
}
|
|
88
99
|
function createParams() {
|
|
89
100
|
return Object.create(null);
|
|
@@ -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 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
|
|
1
|
+
{"version":3,"file":"route-trie.js","names":[],"sources":["../../src/routing/route-trie.ts"],"sourcesContent":["import { decodeMatchedParams } from \"./utils\";\n\n/**\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 * Returns decoded param values — `decodeURIComponent` is applied to\n * individual param entries so that `%2F` → `/`, `%23` → `#`, etc.\n * Segment boundaries (the original `/` splits) are preserved by the\n * upstream normalization layer; this step only decodes the captured\n * param strings the caller sees.\n *\n * Mirrors Next.js route-matcher.ts:25-27.\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 const result = match(root, urlParts, 0);\n if (result) {\n decodeMatchedParams(result.params);\n }\n return result;\n}\n\nfunction createParams(): Record<string, string | string[]> {\n return Object.create(null);\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: createParams() };\n }\n\n // Optional catch-all with 0 segments\n if (node.optionalCatchAllChild !== null) {\n return {\n route: node.optionalCatchAllChild.route,\n params: createParams(),\n };\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 = createParams();\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 = createParams();\n params[node.optionalCatchAllChild.paramName] = remaining;\n return { route: node.optionalCatchAllChild.route, params };\n }\n\n return null;\n}\n"],"mappings":";;AAwBA,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,kBAAkB,KACzB,MAAK,gBAAgB;KAAE;KAAW;KAAO;AAE3C;;AAIF,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,0BAA0B,KACjC,MAAK,wBAAwB;KAAE;KAAW;KAAO;AAEnD;;AAIF,OAAI,KAAK,WAAW,IAAI,EAAE;IACxB,MAAM,YAAY,KAAK,MAAM,EAAE;AAC/B,QAAI,KAAK,iBAAiB,KACxB,MAAK,eAAe;KAAE;KAAW,MAAM,YAAe;KAAE;AAE1D,WAAO,KAAK,aAAa;AAGzB,Q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AO;GAAQ;;AAIpD,KAAI,KAAK,0BAA0B,MAAM;EACvC,MAAM,YAAY,SAAS,MAAM,MAAM;EACvC,MAAM,SAAS,cAAc;AAC7B,SAAO,KAAK,sBAAsB,aAAa;AAC/C,SAAO;GAAE,OAAO,KAAK,sBAAsB;GAAO;GAAQ;;AAG5D,QAAO"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { removeTrailingSlash } from "../utils/base-path.js";
|
|
1
2
|
//#region src/routing/route-validation.ts
|
|
2
3
|
/**
|
|
3
4
|
* Dynamic route validation adapted from Next.js' sorted-routes implementation.
|
|
@@ -80,12 +81,10 @@ var UrlNode = class UrlNode {
|
|
|
80
81
|
};
|
|
81
82
|
function patternToNextFormat(pattern) {
|
|
82
83
|
if (pattern === "/") return "/";
|
|
83
|
-
return pattern.replace(/:([
|
|
84
|
+
return pattern.replace(/:([^/]+?)\+(?=\/|$)/g, "[...$1]").replace(/:([^/]+?)\*(?=\/|$)/g, "[[...$1]]").replace(/:([^/]+?)(?=\/|$)/g, "[$1]");
|
|
84
85
|
}
|
|
85
86
|
function normalizeRoutePattern(pattern) {
|
|
86
|
-
|
|
87
|
-
const normalized = pattern.replace(/\/+$/, "");
|
|
88
|
-
return normalized === "" ? "/" : normalized;
|
|
87
|
+
return removeTrailingSlash(pattern);
|
|
89
88
|
}
|
|
90
89
|
function validateRoutePatterns(patterns) {
|
|
91
90
|
const root = new UrlNode();
|