@shepai/cli 1.3.1 → 1.5.0
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/dist/src/infrastructure/services/port.service.d.ts +20 -0
- package/dist/src/infrastructure/services/port.service.d.ts.map +1 -0
- package/dist/src/infrastructure/services/port.service.js +47 -0
- package/dist/src/infrastructure/services/web-server.service.d.ts +43 -0
- package/dist/src/infrastructure/services/web-server.service.d.ts.map +1 -0
- package/dist/src/infrastructure/services/web-server.service.js +95 -0
- package/dist/src/presentation/cli/commands/settings/index.d.ts +15 -0
- package/dist/src/presentation/cli/commands/settings/index.d.ts.map +1 -0
- package/dist/src/presentation/cli/commands/settings/index.js +21 -0
- package/dist/src/presentation/cli/commands/settings/init.command.d.ts +15 -0
- package/dist/src/presentation/cli/commands/settings/init.command.d.ts.map +1 -0
- package/dist/src/presentation/cli/commands/settings/init.command.js +71 -0
- package/dist/src/presentation/cli/commands/settings/show.command.d.ts +16 -0
- package/dist/src/presentation/cli/commands/settings/show.command.d.ts.map +1 -0
- package/dist/src/presentation/cli/commands/settings/show.command.js +66 -0
- package/dist/src/presentation/cli/commands/ui.command.d.ts +22 -0
- package/dist/src/presentation/cli/commands/ui.command.d.ts.map +1 -0
- package/dist/src/presentation/cli/commands/ui.command.js +74 -0
- package/dist/src/presentation/cli/index.d.ts +1 -0
- package/dist/src/presentation/cli/index.d.ts.map +1 -1
- package/dist/src/presentation/cli/index.js +7 -2
- package/dist/src/presentation/cli/ui/index.d.ts +2 -0
- package/dist/src/presentation/cli/ui/index.d.ts.map +1 -1
- package/dist/src/presentation/cli/ui/index.js +2 -0
- package/dist/src/presentation/cli/ui/output.d.ts +33 -0
- package/dist/src/presentation/cli/ui/output.d.ts.map +1 -0
- package/dist/src/presentation/cli/ui/output.js +49 -0
- package/dist/src/presentation/cli/ui/tables.d.ts +19 -0
- package/dist/src/presentation/cli/ui/tables.d.ts.map +1 -0
- package/dist/src/presentation/cli/ui/tables.js +32 -0
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/package.json +7 -2
- package/web/.next/BUILD_ID +1 -0
- package/web/.next/app-path-routes-manifest.json +6 -0
- package/web/.next/build/chunks/[root-of-the-server]__0f2e5b60._.js +207 -0
- package/web/.next/build/chunks/[root-of-the-server]__0f2e5b60._.js.map +8 -0
- package/web/.next/build/chunks/[root-of-the-server]__52e8dcc7._.js +500 -0
- package/web/.next/build/chunks/[root-of-the-server]__52e8dcc7._.js.map +11 -0
- package/web/.next/build/chunks/[turbopack-node]_transforms_postcss_ts_4ffac355._.js +13 -0
- package/web/.next/build/chunks/[turbopack-node]_transforms_postcss_ts_4ffac355._.js.map +5 -0
- package/web/.next/build/chunks/[turbopack]_runtime.js +795 -0
- package/web/.next/build/chunks/[turbopack]_runtime.js.map +10 -0
- package/web/.next/build/chunks/node_modules__pnpm_806d01c0._.js +6758 -0
- package/web/.next/build/chunks/node_modules__pnpm_806d01c0._.js.map +47 -0
- package/web/.next/build/package.json +1 -0
- package/web/.next/build/postcss.js +6 -0
- package/web/.next/build/postcss.js.map +5 -0
- package/web/.next/build-manifest.json +20 -0
- package/web/.next/cache/.previewinfo +1 -0
- package/web/.next/cache/.rscinfo +1 -0
- package/web/.next/cache/.tsbuildinfo +1 -0
- package/web/.next/cache/config.json +7 -0
- package/web/.next/diagnostics/build-diagnostics.json +6 -0
- package/web/.next/diagnostics/framework.json +1 -0
- package/web/.next/export-marker.json +6 -0
- package/web/.next/fallback-build-manifest.json +12 -0
- package/web/.next/images-manifest.json +67 -0
- package/web/.next/next-minimal-server.js.nft.json +1 -0
- package/web/.next/next-server.js.nft.json +1 -0
- package/web/.next/package.json +1 -0
- package/web/.next/prerender-manifest.json +109 -0
- package/web/.next/required-server-files.js +320 -0
- package/web/.next/required-server-files.json +320 -0
- package/web/.next/routes-manifest.json +68 -0
- package/web/.next/server/app/_global-error/page/app-paths-manifest.json +3 -0
- package/web/.next/server/app/_global-error/page/build-manifest.json +17 -0
- package/web/.next/server/app/_global-error/page/next-font-manifest.json +6 -0
- package/web/.next/server/app/_global-error/page/react-loadable-manifest.json +1 -0
- package/web/.next/server/app/_global-error/page/server-reference-manifest.json +4 -0
- package/web/.next/server/app/_global-error/page.js +10 -0
- package/web/.next/server/app/_global-error/page.js.map +5 -0
- package/web/.next/server/app/_global-error/page.js.nft.json +1 -0
- package/web/.next/server/app/_global-error/page_client-reference-manifest.js +2 -0
- package/web/.next/server/app/_global-error.html +2 -0
- package/web/.next/server/app/_global-error.meta +15 -0
- package/web/.next/server/app/_global-error.rsc +12 -0
- package/web/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +5 -0
- package/web/.next/server/app/_global-error.segments/_full.segment.rsc +12 -0
- package/web/.next/server/app/_global-error.segments/_head.segment.rsc +5 -0
- package/web/.next/server/app/_global-error.segments/_index.segment.rsc +4 -0
- package/web/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -0
- package/web/.next/server/app/_not-found/page/app-paths-manifest.json +3 -0
- package/web/.next/server/app/_not-found/page/build-manifest.json +17 -0
- package/web/.next/server/app/_not-found/page/next-font-manifest.json +6 -0
- package/web/.next/server/app/_not-found/page/react-loadable-manifest.json +1 -0
- package/web/.next/server/app/_not-found/page/server-reference-manifest.json +4 -0
- package/web/.next/server/app/_not-found/page.js +13 -0
- package/web/.next/server/app/_not-found/page.js.map +5 -0
- package/web/.next/server/app/_not-found/page.js.nft.json +1 -0
- package/web/.next/server/app/_not-found/page_client-reference-manifest.js +2 -0
- package/web/.next/server/app/_not-found.html +11 -0
- package/web/.next/server/app/_not-found.meta +16 -0
- package/web/.next/server/app/_not-found.rsc +13 -0
- package/web/.next/server/app/_not-found.segments/_full.segment.rsc +13 -0
- package/web/.next/server/app/_not-found.segments/_head.segment.rsc +5 -0
- package/web/.next/server/app/_not-found.segments/_index.segment.rsc +5 -0
- package/web/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +5 -0
- package/web/.next/server/app/_not-found.segments/_not-found.segment.rsc +4 -0
- package/web/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -0
- package/web/.next/server/app/index.html +11 -0
- package/web/.next/server/app/index.meta +14 -0
- package/web/.next/server/app/index.rsc +14 -0
- package/web/.next/server/app/index.segments/__PAGE__.segment.rsc +6 -0
- package/web/.next/server/app/index.segments/_full.segment.rsc +14 -0
- package/web/.next/server/app/index.segments/_head.segment.rsc +5 -0
- package/web/.next/server/app/index.segments/_index.segment.rsc +5 -0
- package/web/.next/server/app/index.segments/_tree.segment.rsc +2 -0
- package/web/.next/server/app/page/app-paths-manifest.json +3 -0
- package/web/.next/server/app/page/build-manifest.json +17 -0
- package/web/.next/server/app/page/next-font-manifest.json +6 -0
- package/web/.next/server/app/page/react-loadable-manifest.json +1 -0
- package/web/.next/server/app/page/server-reference-manifest.json +4 -0
- package/web/.next/server/app/page.js +16 -0
- package/web/.next/server/app/page.js.map +5 -0
- package/web/.next/server/app/page.js.nft.json +1 -0
- package/web/.next/server/app/page_client-reference-manifest.js +2 -0
- package/web/.next/server/app/version/page/app-paths-manifest.json +3 -0
- package/web/.next/server/app/version/page/build-manifest.json +17 -0
- package/web/.next/server/app/version/page/next-font-manifest.json +6 -0
- package/web/.next/server/app/version/page/react-loadable-manifest.json +1 -0
- package/web/.next/server/app/version/page/server-reference-manifest.json +4 -0
- package/web/.next/server/app/version/page.js +15 -0
- package/web/.next/server/app/version/page.js.map +5 -0
- package/web/.next/server/app/version/page.js.nft.json +1 -0
- package/web/.next/server/app/version/page_client-reference-manifest.js +2 -0
- package/web/.next/server/app/version.html +11 -0
- package/web/.next/server/app/version.meta +15 -0
- package/web/.next/server/app/version.rsc +17 -0
- package/web/.next/server/app/version.segments/_full.segment.rsc +17 -0
- package/web/.next/server/app/version.segments/_head.segment.rsc +5 -0
- package/web/.next/server/app/version.segments/_index.segment.rsc +5 -0
- package/web/.next/server/app/version.segments/_tree.segment.rsc +2 -0
- package/web/.next/server/app/version.segments/version/__PAGE__.segment.rsc +9 -0
- package/web/.next/server/app/version.segments/version.segment.rsc +4 -0
- package/web/.next/server/app-paths-manifest.json +6 -0
- package/web/.next/server/chunks/ssr/403f9_next_dist_2ff794b1._.js +6 -0
- package/web/.next/server/chunks/ssr/403f9_next_dist_2ff794b1._.js.map +1 -0
- package/web/.next/server/chunks/ssr/403f9_next_dist_6c821c12._.js +4 -0
- package/web/.next/server/chunks/ssr/403f9_next_dist_6c821c12._.js.map +1 -0
- package/web/.next/server/chunks/ssr/403f9_next_dist_client_components_44deecdf._.js +3 -0
- package/web/.next/server/chunks/ssr/403f9_next_dist_client_components_44deecdf._.js.map +1 -0
- package/web/.next/server/chunks/ssr/403f9_next_dist_client_components_builtin_global-error_5fefc4d7.js +3 -0
- package/web/.next/server/chunks/ssr/403f9_next_dist_client_components_builtin_global-error_5fefc4d7.js.map +1 -0
- package/web/.next/server/chunks/ssr/403f9_next_dist_client_components_builtin_unauthorized_a2906ebd.js +3 -0
- package/web/.next/server/chunks/ssr/403f9_next_dist_client_components_builtin_unauthorized_a2906ebd.js.map +1 -0
- package/web/.next/server/chunks/ssr/403f9_next_dist_esm_build_templates_app-page_dbf21e04.js +4 -0
- package/web/.next/server/chunks/ssr/403f9_next_dist_esm_build_templates_app-page_dbf21e04.js.map +1 -0
- package/web/.next/server/chunks/ssr/[root-of-the-server]__01b8cb62._.js +3 -0
- package/web/.next/server/chunks/ssr/[root-of-the-server]__01b8cb62._.js.map +1 -0
- package/web/.next/server/chunks/ssr/[root-of-the-server]__205a2636._.js +3 -0
- package/web/.next/server/chunks/ssr/[root-of-the-server]__205a2636._.js.map +1 -0
- package/web/.next/server/chunks/ssr/[root-of-the-server]__5aff3b12._.js +3 -0
- package/web/.next/server/chunks/ssr/[root-of-the-server]__5aff3b12._.js.map +1 -0
- package/web/.next/server/chunks/ssr/[root-of-the-server]__7b98fb96._.js +3 -0
- package/web/.next/server/chunks/ssr/[root-of-the-server]__7b98fb96._.js.map +1 -0
- package/web/.next/server/chunks/ssr/[root-of-the-server]__8297ff30._.js +3 -0
- package/web/.next/server/chunks/ssr/[root-of-the-server]__8297ff30._.js.map +1 -0
- package/web/.next/server/chunks/ssr/[root-of-the-server]__c3694f82._.js +10 -0
- package/web/.next/server/chunks/ssr/[root-of-the-server]__c3694f82._.js.map +1 -0
- package/web/.next/server/chunks/ssr/[root-of-the-server]__d6257aad._.js +3 -0
- package/web/.next/server/chunks/ssr/[root-of-the-server]__d6257aad._.js.map +1 -0
- package/web/.next/server/chunks/ssr/[root-of-the-server]__d81095d0._.js +3 -0
- package/web/.next/server/chunks/ssr/[root-of-the-server]__d81095d0._.js.map +1 -0
- package/web/.next/server/chunks/ssr/[turbopack]_runtime.js +795 -0
- package/web/.next/server/chunks/ssr/[turbopack]_runtime.js.map +10 -0
- package/web/.next/server/chunks/ssr/_0f02ab66._.js +3 -0
- package/web/.next/server/chunks/ssr/_0f02ab66._.js.map +1 -0
- package/web/.next/server/chunks/ssr/_884ddade._.js +4 -0
- package/web/.next/server/chunks/ssr/_884ddade._.js.map +1 -0
- package/web/.next/server/chunks/ssr/_90bc0c33._.js +3 -0
- package/web/.next/server/chunks/ssr/_90bc0c33._.js.map +1 -0
- package/web/.next/server/chunks/ssr/_c536147b._.js +3 -0
- package/web/.next/server/chunks/ssr/_c536147b._.js.map +1 -0
- package/web/.next/server/chunks/ssr/_c5d377cc._.js +4 -0
- package/web/.next/server/chunks/ssr/_c5d377cc._.js.map +1 -0
- package/web/.next/server/chunks/ssr/_e519e92f._.js +3 -0
- package/web/.next/server/chunks/ssr/_e519e92f._.js.map +1 -0
- package/web/.next/server/chunks/ssr/b1a17_presentation_web__next-internal_server_app__global-error_page_actions_4fe4770f.js +3 -0
- package/web/.next/server/chunks/ssr/b1a17_presentation_web__next-internal_server_app__global-error_page_actions_4fe4770f.js.map +1 -0
- package/web/.next/server/chunks/ssr/node_modules__pnpm_03635e2b._.js +4 -0
- package/web/.next/server/chunks/ssr/node_modules__pnpm_03635e2b._.js.map +1 -0
- package/web/.next/server/chunks/ssr/node_modules__pnpm_522e4103._.js +3 -0
- package/web/.next/server/chunks/ssr/node_modules__pnpm_522e4103._.js.map +1 -0
- package/web/.next/server/chunks/ssr/src_presentation_web__next-internal_server_app__not-found_page_actions_a836bb2a.js +3 -0
- package/web/.next/server/chunks/ssr/src_presentation_web__next-internal_server_app__not-found_page_actions_a836bb2a.js.map +1 -0
- package/web/.next/server/chunks/ssr/src_presentation_web__next-internal_server_app_page_actions_a4e3cb6f.js +3 -0
- package/web/.next/server/chunks/ssr/src_presentation_web__next-internal_server_app_page_actions_a4e3cb6f.js.map +1 -0
- package/web/.next/server/chunks/ssr/src_presentation_web__next-internal_server_app_version_page_actions_ea925032.js +3 -0
- package/web/.next/server/chunks/ssr/src_presentation_web__next-internal_server_app_version_page_actions_ea925032.js.map +1 -0
- package/web/.next/server/chunks/ssr/src_presentation_web_app_layout_tsx_aa3a06bd._.js +13 -0
- package/web/.next/server/chunks/ssr/src_presentation_web_app_layout_tsx_aa3a06bd._.js.map +1 -0
- package/web/.next/server/chunks/ssr/src_presentation_web_app_not-found_tsx_64b86c46._.js +3 -0
- package/web/.next/server/chunks/ssr/src_presentation_web_app_not-found_tsx_64b86c46._.js.map +1 -0
- package/web/.next/server/chunks/ssr/src_presentation_web_app_version_page_tsx_1bab7370._.js +3 -0
- package/web/.next/server/chunks/ssr/src_presentation_web_app_version_page_tsx_1bab7370._.js.map +1 -0
- package/web/.next/server/functions-config-manifest.json +4 -0
- package/web/.next/server/interception-route-rewrite-manifest.js +1 -0
- package/web/.next/server/middleware-build-manifest.js +21 -0
- package/web/.next/server/middleware-manifest.json +6 -0
- package/web/.next/server/next-font-manifest.js +1 -0
- package/web/.next/server/next-font-manifest.json +6 -0
- package/web/.next/server/pages/404.html +11 -0
- package/web/.next/server/pages/500.html +2 -0
- package/web/.next/server/pages-manifest.json +4 -0
- package/web/.next/server/server-reference-manifest.js +1 -0
- package/web/.next/server/server-reference-manifest.json +5 -0
- package/web/.next/static/Z9XCmAv7-DjAFCpNEPaUt/_buildManifest.js +11 -0
- package/web/.next/static/Z9XCmAv7-DjAFCpNEPaUt/_clientMiddlewareManifest.json +1 -0
- package/web/.next/static/Z9XCmAv7-DjAFCpNEPaUt/_ssgManifest.js +1 -0
- package/web/.next/static/chunks/4d6504b9f2ca7e4d.js +1 -0
- package/web/.next/static/chunks/51816495a9eb288c.css +1 -0
- package/web/.next/static/chunks/52a5aeb86329ee2e.js +1 -0
- package/web/.next/static/chunks/70993ebedee7eab0.js +2 -0
- package/web/.next/static/chunks/71462f20e38a4262.js +4 -0
- package/web/.next/static/chunks/86484b9b4aa9f859.js +1 -0
- package/web/.next/static/chunks/a6dad97d9634a72d.js +1 -0
- package/web/.next/static/chunks/a6dad97d9634a72d.js.map +1 -0
- package/web/.next/static/chunks/ab02eec995295bef.js +1 -0
- package/web/.next/static/chunks/b3cc49b27e09fa39.js +1 -0
- package/web/.next/static/chunks/f3b4460b1496ef52.js +1 -0
- package/web/.next/static/chunks/turbopack-76ba02c6b131eee4.js +4 -0
- package/web/.next/trace +1 -0
- package/web/.next/trace-build +1 -0
- package/web/.next/turbopack +0 -0
- package/web/.next/types/link.d.ts +163 -0
- package/web/.next/types/routes.d.ts +58 -0
- package/web/.next/types/validator.ts +70 -0
- package/web/next.config.ts +14 -0
- package/web/package.json +38 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../node_modules/.pnpm/%40swc%2Bhelpers%400.5.15/node_modules/%40swc/helpers/cjs/_interop_require_wildcard.cjs","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/router/utils/querystring.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/router/utils/format-url.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/use-merged-ref.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/utils.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/router/utils/parse-path.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/router/utils/add-path-prefix.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/router/utils/remove-trailing-slash.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/normalize-trailing-slash.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/add-base-path.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/utils/warn-once.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/segment-cache/types.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/segment-cache/cache-key.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/app-router-types.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/match-segments.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/app-router-headers.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/router-reducer/router-reducer-types.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/is-thenable.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/use-action-queue.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/app-call-server.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/app-find-source-map-url.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/segment.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/segment-cache/segment-value-encoding.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/route-params.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/router-reducer/create-href-from-url.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/flight-data-helpers.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/app-build-id.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/hash.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/router/utils/cache-busting-search-param.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/router-reducer/set-cache-busting-search-param.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/deployment-id.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/router-reducer/fetch-server-response.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/segment-cache/lru.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/segment-cache/cache-map.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/segment-cache/vary-path.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/page-path/ensure-leading-slash.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/router/utils/app-paths.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/router/utils/interception-routes.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/router-reducer/compute-changed-path.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/router-reducer/handle-mutable.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/router-reducer/create-router-cache-key.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/router-reducer/is-navigating-to-new-root-layout.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/router-reducer/ppr-navigations.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/segment-cache/navigation.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/router-reducer/reducers/navigate-reducer.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/promise-with-resolvers.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/segment-cache/cache.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/segment-cache/scheduler.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/components/links.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/router/utils/path-has-prefix.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/has-base-path.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/router/utils/is-local-url.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/shared/lib/utils/error-once.ts","../../../../../../../node_modules/.pnpm/next%4016.1.6_%40babel%2Bcore%407.29.0_%40playwright%2Btest%401.58.1_react-dom%4019.2.4_react%4019.2.4__react%4019.2.4/node_modules/next/src/client/app-dir/link.tsx"],"sourcesContent":["\"use strict\";\n\nfunction _getRequireWildcardCache(nodeInterop) {\n if (typeof WeakMap !== \"function\") return null;\n\n var cacheBabelInterop = new WeakMap();\n var cacheNodeInterop = new WeakMap();\n\n return (_getRequireWildcardCache = function(nodeInterop) {\n return nodeInterop ? cacheNodeInterop : cacheBabelInterop;\n })(nodeInterop);\n}\nfunction _interop_require_wildcard(obj, nodeInterop) {\n if (!nodeInterop && obj && obj.__esModule) return obj;\n if (obj === null || typeof obj !== \"object\" && typeof obj !== \"function\") return { default: obj };\n\n var cache = _getRequireWildcardCache(nodeInterop);\n\n if (cache && cache.has(obj)) return cache.get(obj);\n\n var newObj = { __proto__: null };\n var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;\n\n for (var key in obj) {\n if (key !== \"default\" && Object.prototype.hasOwnProperty.call(obj, key)) {\n var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;\n if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc);\n else newObj[key] = obj[key];\n }\n }\n\n newObj.default = obj;\n\n if (cache) cache.set(obj, newObj);\n\n return newObj;\n}\nexports._ = _interop_require_wildcard;\n","import type { ParsedUrlQuery } from 'querystring'\n\nexport function searchParamsToUrlQuery(\n searchParams: URLSearchParams\n): ParsedUrlQuery {\n const query: ParsedUrlQuery = {}\n for (const [key, value] of searchParams.entries()) {\n const existing = query[key]\n if (typeof existing === 'undefined') {\n query[key] = value\n } else if (Array.isArray(existing)) {\n existing.push(value)\n } else {\n query[key] = [existing, value]\n }\n }\n return query\n}\n\nfunction stringifyUrlQueryParam(param: unknown): string {\n if (typeof param === 'string') {\n return param\n }\n\n if (\n (typeof param === 'number' && !isNaN(param)) ||\n typeof param === 'boolean'\n ) {\n return String(param)\n } else {\n return ''\n }\n}\n\nexport function urlQueryToSearchParams(query: ParsedUrlQuery): URLSearchParams {\n const searchParams = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n if (Array.isArray(value)) {\n for (const item of value) {\n searchParams.append(key, stringifyUrlQueryParam(item))\n }\n } else {\n searchParams.set(key, stringifyUrlQueryParam(value))\n }\n }\n return searchParams\n}\n\nexport function assign(\n target: URLSearchParams,\n ...searchParamsList: URLSearchParams[]\n): URLSearchParams {\n for (const searchParams of searchParamsList) {\n for (const key of searchParams.keys()) {\n target.delete(key)\n }\n\n for (const [key, value] of searchParams.entries()) {\n target.append(key, value)\n }\n }\n\n return target\n}\n","// Format function modified from nodejs\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport type { UrlObject } from 'url'\nimport type { ParsedUrlQuery } from 'querystring'\nimport * as querystring from './querystring'\n\nconst slashedProtocols = /https?|ftp|gopher|file/\n\nexport function formatUrl(urlObj: UrlObject) {\n let { auth, hostname } = urlObj\n let protocol = urlObj.protocol || ''\n let pathname = urlObj.pathname || ''\n let hash = urlObj.hash || ''\n let query = urlObj.query || ''\n let host: string | false = false\n\n auth = auth ? encodeURIComponent(auth).replace(/%3A/i, ':') + '@' : ''\n\n if (urlObj.host) {\n host = auth + urlObj.host\n } else if (hostname) {\n host = auth + (~hostname.indexOf(':') ? `[${hostname}]` : hostname)\n if (urlObj.port) {\n host += ':' + urlObj.port\n }\n }\n\n if (query && typeof query === 'object') {\n query = String(querystring.urlQueryToSearchParams(query as ParsedUrlQuery))\n }\n\n let search = urlObj.search || (query && `?${query}`) || ''\n\n if (protocol && !protocol.endsWith(':')) protocol += ':'\n\n if (\n urlObj.slashes ||\n ((!protocol || slashedProtocols.test(protocol)) && host !== false)\n ) {\n host = '//' + (host || '')\n if (pathname && pathname[0] !== '/') pathname = '/' + pathname\n } else if (!host) {\n host = ''\n }\n\n if (hash && hash[0] !== '#') hash = '#' + hash\n if (search && search[0] !== '?') search = '?' + search\n\n pathname = pathname.replace(/[?#]/g, encodeURIComponent)\n search = search.replace('#', '%23')\n\n return `${protocol}${host}${pathname}${search}${hash}`\n}\n\nexport const urlObjectKeys = [\n 'auth',\n 'hash',\n 'host',\n 'hostname',\n 'href',\n 'path',\n 'pathname',\n 'port',\n 'protocol',\n 'query',\n 'search',\n 'slashes',\n]\n\nexport function formatWithValidation(url: UrlObject): string {\n if (process.env.NODE_ENV === 'development') {\n if (url !== null && typeof url === 'object') {\n Object.keys(url).forEach((key) => {\n if (!urlObjectKeys.includes(key)) {\n console.warn(\n `Unknown key passed via urlObject into url.format: ${key}`\n )\n }\n })\n }\n }\n\n return formatUrl(url)\n}\n","import { useCallback, useRef, type Ref } from 'react'\n\n// This is a compatibility hook to support React 18 and 19 refs.\n// In 19, a cleanup function from refs may be returned.\n// In 18, returning a cleanup function creates a warning.\n// Since we take userspace refs, we don't know ahead of time if a cleanup function will be returned.\n// This implements cleanup functions with the old behavior in 18.\n// We know refs are always called alternating with `null` and then `T`.\n// So a call with `null` means we need to call the previous cleanup functions.\nexport function useMergedRef<TElement>(\n refA: Ref<TElement>,\n refB: Ref<TElement>\n): Ref<TElement> {\n const cleanupA = useRef<(() => void) | null>(null)\n const cleanupB = useRef<(() => void) | null>(null)\n\n // NOTE: In theory, we could skip the wrapping if only one of the refs is non-null.\n // (this happens often if the user doesn't pass a ref to Link/Form/Image)\n // But this can cause us to leak a cleanup-ref into user code (previously via `<Link legacyBehavior>`),\n // and the user might pass that ref into ref-merging library that doesn't support cleanup refs\n // (because it hasn't been updated for React 19)\n // which can then cause things to blow up, because a cleanup-returning ref gets called with `null`.\n // So in practice, it's safer to be defensive and always wrap the ref, even on React 19.\n return useCallback(\n (current: TElement | null): void => {\n if (current === null) {\n const cleanupFnA = cleanupA.current\n if (cleanupFnA) {\n cleanupA.current = null\n cleanupFnA()\n }\n const cleanupFnB = cleanupB.current\n if (cleanupFnB) {\n cleanupB.current = null\n cleanupFnB()\n }\n } else {\n if (refA) {\n cleanupA.current = applyRef(refA, current)\n }\n if (refB) {\n cleanupB.current = applyRef(refB, current)\n }\n }\n },\n [refA, refB]\n )\n}\n\nfunction applyRef<TElement>(\n refA: NonNullable<Ref<TElement>>,\n current: TElement\n) {\n if (typeof refA === 'function') {\n const cleanup = refA(current)\n if (typeof cleanup === 'function') {\n return cleanup\n } else {\n return () => refA(null)\n }\n } else {\n refA.current = current\n return () => {\n refA.current = null\n }\n }\n}\n","import type { HtmlProps } from './html-context.shared-runtime'\nimport type { ComponentType, JSX } from 'react'\nimport type { DomainLocale } from '../../server/config'\nimport type { Env } from '@next/env'\nimport type { IncomingMessage, ServerResponse } from 'http'\nimport type { NextRouter } from './router/router'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { PreviewData } from '../../types'\nimport type { COMPILER_NAMES } from './constants'\nimport type fs from 'fs'\n\nexport type NextComponentType<\n Context extends BaseContext = NextPageContext,\n InitialProps = {},\n Props = {},\n> = ComponentType<Props> & {\n /**\n * Used for initial page load data population. Data returned from `getInitialProps` is serialized when server rendered.\n * Make sure to return plain `Object` without using `Date`, `Map`, `Set`.\n * @param context Context of `page`\n */\n getInitialProps?(context: Context): InitialProps | Promise<InitialProps>\n}\n\nexport type DocumentType = NextComponentType<\n DocumentContext,\n DocumentInitialProps,\n DocumentProps\n>\n\nexport type AppType<P = {}> = NextComponentType<\n AppContextType,\n P,\n AppPropsType<any, P>\n>\n\nexport type AppTreeType = ComponentType<\n AppInitialProps & { [name: string]: any }\n>\n\n/**\n * Web vitals provided to _app.reportWebVitals by Core Web Vitals plugin developed by Google Chrome team.\n * https://nextjs.org/blog/next-9-4#integrated-web-vitals-reporting\n */\nexport const WEB_VITALS = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'] as const\nexport type NextWebVitalsMetric = {\n id: string\n startTime: number\n value: number\n attribution?: { [key: string]: unknown }\n} & (\n | {\n label: 'web-vital'\n name: (typeof WEB_VITALS)[number]\n }\n | {\n label: 'custom'\n name:\n | 'Next.js-hydration'\n | 'Next.js-route-change-to-render'\n | 'Next.js-render'\n }\n)\n\nexport type Enhancer<C> = (Component: C) => C\n\nexport type ComponentsEnhancer =\n | {\n enhanceApp?: Enhancer<AppType>\n enhanceComponent?: Enhancer<NextComponentType>\n }\n | Enhancer<NextComponentType>\n\nexport type RenderPageResult = {\n html: string\n head?: Array<JSX.Element | null>\n}\n\nexport type RenderPage = (\n options?: ComponentsEnhancer\n) => DocumentInitialProps | Promise<DocumentInitialProps>\n\nexport type BaseContext = {\n res?: ServerResponse\n [k: string]: any\n}\n\nexport type NEXT_DATA = {\n props: Record<string, any>\n page: string\n query: ParsedUrlQuery\n buildId: string\n assetPrefix?: string\n nextExport?: boolean\n autoExport?: boolean\n isFallback?: boolean\n isExperimentalCompile?: boolean\n dynamicIds?: (string | number)[]\n err?: Error & {\n statusCode?: number\n source?: typeof COMPILER_NAMES.server | typeof COMPILER_NAMES.edgeServer\n }\n gsp?: boolean\n gssp?: boolean\n customServer?: boolean\n gip?: boolean\n appGip?: boolean\n locale?: string\n locales?: readonly string[]\n defaultLocale?: string\n domainLocales?: readonly DomainLocale[]\n scriptLoader?: any[]\n isPreview?: boolean\n notFoundSrcPage?: string\n}\n\n/**\n * `Next` context\n */\nexport interface NextPageContext {\n /**\n * Error object if encountered during rendering\n */\n err?: (Error & { statusCode?: number }) | null\n /**\n * `HTTP` request object.\n */\n req?: IncomingMessage\n /**\n * `HTTP` response object.\n */\n res?: ServerResponse\n /**\n * Path section of `URL`.\n */\n pathname: string\n /**\n * Query string section of `URL` parsed as an object.\n */\n query: ParsedUrlQuery\n /**\n * `String` of the actual path including query.\n */\n asPath?: string\n /**\n * The currently active locale\n */\n locale?: string\n /**\n * All configured locales\n */\n locales?: readonly string[]\n /**\n * The configured default locale\n */\n defaultLocale?: string\n /**\n * `Component` the tree of the App to use if needing to render separately\n */\n AppTree: AppTreeType\n}\n\nexport type AppContextType<Router extends NextRouter = NextRouter> = {\n Component: NextComponentType<NextPageContext>\n AppTree: AppTreeType\n ctx: NextPageContext\n router: Router\n}\n\nexport type AppInitialProps<PageProps = any> = {\n pageProps: PageProps\n}\n\nexport type AppPropsType<\n Router extends NextRouter = NextRouter,\n PageProps = {},\n> = AppInitialProps<PageProps> & {\n Component: NextComponentType<NextPageContext, any, any>\n router: Router\n __N_SSG?: boolean\n __N_SSP?: boolean\n}\n\nexport type DocumentContext = NextPageContext & {\n renderPage: RenderPage\n defaultGetInitialProps(\n ctx: DocumentContext,\n options?: { nonce?: string }\n ): Promise<DocumentInitialProps>\n}\n\nexport type DocumentInitialProps = RenderPageResult & {\n styles?: React.ReactElement[] | Iterable<React.ReactNode> | JSX.Element\n}\n\nexport type DocumentProps = DocumentInitialProps & HtmlProps\n\n/**\n * Next `API` route request\n */\nexport interface NextApiRequest extends IncomingMessage {\n /**\n * Object of `query` values from url\n */\n query: Partial<{\n [key: string]: string | string[]\n }>\n /**\n * Object of `cookies` from header\n */\n cookies: Partial<{\n [key: string]: string\n }>\n\n body: any\n\n env: Env\n\n draftMode?: boolean\n\n preview?: boolean\n /**\n * Preview data set on the request, if any\n * */\n previewData?: PreviewData\n}\n\n/**\n * Send body of response\n */\ntype Send<T> = (body: T) => void\n\n/**\n * Next `API` route response\n */\nexport type NextApiResponse<Data = any> = ServerResponse & {\n /**\n * Send data `any` data in response\n */\n send: Send<Data>\n /**\n * Send data `json` data in response\n */\n json: Send<Data>\n status: (statusCode: number) => NextApiResponse<Data>\n redirect(url: string): NextApiResponse<Data>\n redirect(status: number, url: string): NextApiResponse<Data>\n\n /**\n * Set draft mode\n */\n setDraftMode: (options: { enable: boolean }) => NextApiResponse<Data>\n\n /**\n * Set preview data for Next.js' prerender mode\n */\n setPreviewData: (\n data: object | string,\n options?: {\n /**\n * Specifies the number (in seconds) for the preview session to last for.\n * The given number will be converted to an integer by rounding down.\n * By default, no maximum age is set and the preview session finishes\n * when the client shuts down (browser is closed).\n */\n maxAge?: number\n /**\n * Specifies the path for the preview session to work under. By default,\n * the path is considered the \"default path\", i.e., any pages under \"/\".\n */\n path?: string\n }\n ) => NextApiResponse<Data>\n\n /**\n * Clear preview data for Next.js' prerender mode\n */\n clearPreviewData: (options?: { path?: string }) => NextApiResponse<Data>\n\n /**\n * Revalidate a specific page and regenerate it using On-Demand Incremental\n * Static Regeneration.\n * The path should be an actual path, not a rewritten path. E.g. for\n * \"/blog/[slug]\" this should be \"/blog/post-1\".\n * @link https://nextjs.org/docs/app/building-your-application/data-fetching/incremental-static-regeneration#on-demand-revalidation-with-revalidatepath\n */\n revalidate: (\n urlPath: string,\n opts?: {\n unstable_onlyGenerated?: boolean\n }\n ) => Promise<void>\n}\n\n/**\n * Next `API` route handler\n */\nexport type NextApiHandler<T = any> = (\n req: NextApiRequest,\n res: NextApiResponse<T>\n) => unknown | Promise<unknown>\n\n/**\n * Utils\n */\nexport function execOnce<T extends (...args: any[]) => ReturnType<T>>(\n fn: T\n): T {\n let used = false\n let result: ReturnType<T>\n\n return ((...args: any[]) => {\n if (!used) {\n used = true\n result = fn(...args)\n }\n return result\n }) as T\n}\n\n// Scheme: https://tools.ietf.org/html/rfc3986#section-3.1\n// Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3\nconst ABSOLUTE_URL_REGEX = /^[a-zA-Z][a-zA-Z\\d+\\-.]*?:/\nexport const isAbsoluteUrl = (url: string) => ABSOLUTE_URL_REGEX.test(url)\n\nexport function getLocationOrigin() {\n const { protocol, hostname, port } = window.location\n return `${protocol}//${hostname}${port ? ':' + port : ''}`\n}\n\nexport function getURL() {\n const { href } = window.location\n const origin = getLocationOrigin()\n return href.substring(origin.length)\n}\n\nexport function getDisplayName<P>(Component: ComponentType<P>) {\n return typeof Component === 'string'\n ? Component\n : Component.displayName || Component.name || 'Unknown'\n}\n\nexport function isResSent(res: ServerResponse) {\n return res.finished || res.headersSent\n}\n\nexport function normalizeRepeatedSlashes(url: string) {\n const urlParts = url.split('?')\n const urlNoQuery = urlParts[0]\n\n return (\n urlNoQuery\n // first we replace any non-encoded backslashes with forward\n // then normalize repeated forward slashes\n .replace(/\\\\/g, '/')\n .replace(/\\/\\/+/g, '/') +\n (urlParts[1] ? `?${urlParts.slice(1).join('?')}` : '')\n )\n}\n\nexport async function loadGetInitialProps<\n C extends BaseContext,\n IP = {},\n P = {},\n>(App: NextComponentType<C, IP, P>, ctx: C): Promise<IP> {\n if (process.env.NODE_ENV !== 'production') {\n if (App.prototype?.getInitialProps) {\n const message = `\"${getDisplayName(\n App\n )}.getInitialProps()\" is defined as an instance method - visit https://nextjs.org/docs/messages/get-initial-props-as-an-instance-method for more information.`\n throw new Error(message)\n }\n }\n // when called from _app `ctx` is nested in `ctx`\n const res = ctx.res || (ctx.ctx && ctx.ctx.res)\n\n if (!App.getInitialProps) {\n if (ctx.ctx && ctx.Component) {\n // @ts-ignore pageProps default\n return {\n pageProps: await loadGetInitialProps(ctx.Component, ctx.ctx),\n }\n }\n return {} as IP\n }\n\n const props = await App.getInitialProps(ctx)\n\n if (res && isResSent(res)) {\n return props\n }\n\n if (!props) {\n const message = `\"${getDisplayName(\n App\n )}.getInitialProps()\" should resolve to an object. But found \"${props}\" instead.`\n throw new Error(message)\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (Object.keys(props).length === 0 && !ctx.ctx) {\n console.warn(\n `${getDisplayName(\n App\n )} returned an empty object from \\`getInitialProps\\`. This de-optimizes and prevents automatic static optimization. https://nextjs.org/docs/messages/empty-object-getInitialProps`\n )\n }\n }\n\n return props\n}\n\nexport const SP = typeof performance !== 'undefined'\nexport const ST =\n SP &&\n (['mark', 'measure', 'getEntriesByName'] as const).every(\n (method) => typeof performance[method] === 'function'\n )\n\nexport class DecodeError extends Error {}\nexport class NormalizeError extends Error {}\nexport class PageNotFoundError extends Error {\n code: string\n\n constructor(page: string) {\n super()\n this.code = 'ENOENT'\n this.name = 'PageNotFoundError'\n this.message = `Cannot find module for page: ${page}`\n }\n}\n\nexport class MissingStaticPage extends Error {\n constructor(page: string, message: string) {\n super()\n this.message = `Failed to load static file for page: ${page} ${message}`\n }\n}\n\nexport class MiddlewareNotFoundError extends Error {\n code: string\n constructor() {\n super()\n this.code = 'ENOENT'\n this.message = `Cannot find the middleware module`\n }\n}\n\nexport interface CacheFs {\n existsSync: typeof fs.existsSync\n readFile: typeof fs.promises.readFile\n readFileSync: typeof fs.readFileSync\n writeFile(f: string, d: any): Promise<void>\n mkdir(dir: string): Promise<void | string>\n stat(f: string): Promise<{ mtime: Date }>\n}\n\nexport function stringifyError(error: Error) {\n return JSON.stringify({ message: error.message, stack: error.stack })\n}\n","/**\n * Given a path this function will find the pathname, query and hash and return\n * them. This is useful to parse full paths on the client side.\n * @param path A path to parse e.g. /foo/bar?id=1#hash\n */\nexport function parsePath(path: string) {\n const hashIndex = path.indexOf('#')\n const queryIndex = path.indexOf('?')\n const hasQuery = queryIndex > -1 && (hashIndex < 0 || queryIndex < hashIndex)\n\n if (hasQuery || hashIndex > -1) {\n return {\n pathname: path.substring(0, hasQuery ? queryIndex : hashIndex),\n query: hasQuery\n ? path.substring(queryIndex, hashIndex > -1 ? hashIndex : undefined)\n : '',\n hash: hashIndex > -1 ? path.slice(hashIndex) : '',\n }\n }\n\n return { pathname: path, query: '', hash: '' }\n}\n","import { parsePath } from './parse-path'\n\n/**\n * Adds the provided prefix to the given path. It first ensures that the path\n * is indeed starting with a slash.\n */\nexport function addPathPrefix(path: string, prefix?: string) {\n if (!path.startsWith('/') || !prefix) {\n return path\n }\n\n const { pathname, query, hash } = parsePath(path)\n return `${prefix}${pathname}${query}${hash}`\n}\n","/**\n * Removes the trailing slash for a given route or page path. Preserves the\n * root page. Examples:\n * - `/foo/bar/` -> `/foo/bar`\n * - `/foo/bar` -> `/foo/bar`\n * - `/` -> `/`\n */\nexport function removeTrailingSlash(route: string) {\n return route.replace(/\\/$/, '') || '/'\n}\n","import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'\nimport { parsePath } from '../shared/lib/router/utils/parse-path'\n\n/**\n * Normalizes the trailing slash of a path according to the `trailingSlash` option\n * in `next.config.js`.\n */\nexport const normalizePathTrailingSlash = (path: string) => {\n if (!path.startsWith('/') || process.env.__NEXT_MANUAL_TRAILING_SLASH) {\n return path\n }\n\n const { pathname, query, hash } = parsePath(path)\n if (process.env.__NEXT_TRAILING_SLASH) {\n if (/\\.[^/]+\\/?$/.test(pathname)) {\n return `${removeTrailingSlash(pathname)}${query}${hash}`\n } else if (pathname.endsWith('/')) {\n return `${pathname}${query}${hash}`\n } else {\n return `${pathname}/${query}${hash}`\n }\n }\n\n return `${removeTrailingSlash(pathname)}${query}${hash}`\n}\n","import { addPathPrefix } from '../shared/lib/router/utils/add-path-prefix'\nimport { normalizePathTrailingSlash } from './normalize-trailing-slash'\n\nconst basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''\n\nexport function addBasePath(path: string, required?: boolean): string {\n return normalizePathTrailingSlash(\n process.env.__NEXT_MANUAL_CLIENT_BASE_PATH && !required\n ? path\n : addPathPrefix(path, basePath)\n )\n}\n","let warnOnce = (_: string) => {}\nif (process.env.NODE_ENV !== 'production') {\n const warnings = new Set<string>()\n warnOnce = (msg: string) => {\n if (!warnings.has(msg)) {\n console.warn(msg)\n }\n warnings.add(msg)\n }\n}\n\nexport { warnOnce }\n","/**\n * Shared types and constants for the Segment Cache.\n */\n\nexport const enum NavigationResultTag {\n MPA,\n Success,\n NoOp,\n Async,\n}\n\n/**\n * The priority of the prefetch task. Higher numbers are higher priority.\n */\nexport const enum PrefetchPriority {\n /**\n * Assigned to the most recently hovered/touched link. Special network\n * bandwidth is reserved for this task only. There's only ever one Intent-\n * priority task at a time; when a new Intent task is scheduled, the previous\n * one is bumped down to Default.\n */\n Intent = 2,\n /**\n * The default priority for prefetch tasks.\n */\n Default = 1,\n /**\n * Assigned to tasks when they spawn non-blocking background work, like\n * revalidating a partially cached entry to see if more data is available.\n */\n Background = 0,\n}\n\nexport const enum FetchStrategy {\n // Deliberately ordered so we can easily compare two segments\n // and determine if one segment is \"more specific\" than another\n // (i.e. if it's likely that it contains more data)\n LoadingBoundary = 0,\n PPR = 1,\n PPRRuntime = 2,\n Full = 3,\n}\n\n/**\n * A subset of fetch strategies used for prefetch tasks.\n * A prefetch task can't know if it should use `PPR` or `LoadingBoundary`\n * until we complete the initial tree prefetch request, so we use `PPR` to signal both cases\n * and adjust it based on the route when actually fetching.\n * */\nexport type PrefetchTaskFetchStrategy =\n | FetchStrategy.PPR\n | FetchStrategy.PPRRuntime\n | FetchStrategy.Full\n","// TypeScript trick to simulate opaque types, like in Flow.\ntype Opaque<K, T> = T & { __brand: K }\n\n// Only functions in this module should be allowed to create CacheKeys.\nexport type NormalizedPathname = Opaque<'NormalizedPathname', string>\nexport type NormalizedSearch = Opaque<'NormalizedSearch', string>\nexport type NormalizedNextUrl = Opaque<'NormalizedNextUrl', string>\n\nexport type RouteCacheKey = Opaque<\n 'RouteCacheKey',\n {\n pathname: NormalizedPathname\n search: NormalizedSearch\n nextUrl: NormalizedNextUrl | null\n\n // TODO: Eventually the dynamic params will be added here, too.\n }\n>\n\nexport function createCacheKey(\n originalHref: string,\n nextUrl: string | null\n): RouteCacheKey {\n const originalUrl = new URL(originalHref)\n const cacheKey = {\n pathname: originalUrl.pathname as NormalizedPathname,\n search: originalUrl.search as NormalizedSearch,\n nextUrl: nextUrl as NormalizedNextUrl | null,\n } as RouteCacheKey\n return cacheKey\n}\n","/**\n * App Router types - Client-safe types for the Next.js App Router\n *\n * This file contains type definitions that can be safely imported\n * by both client-side and server-side code without circular dependencies.\n */\n\nimport type React from 'react'\n\nexport type LoadingModuleData =\n | [React.JSX.Element, React.ReactNode, React.ReactNode]\n | null\n\n/** viewport metadata node */\nexport type HeadData = React.ReactNode\n\nexport type ChildSegmentMap = Map<string, CacheNode>\n\n/**\n * Cache node used in app-router / layout-router.\n */\n\nexport type CacheNode = {\n /**\n * When rsc is not null, it represents the RSC data for the\n * corresponding segment.\n *\n * `null` is a valid React Node but because segment data is always a\n * <LayoutRouter> component, we can use `null` to represent empty. When it is\n * null, it represents missing data, and rendering should suspend.\n */\n rsc: React.ReactNode\n\n /**\n * Represents a static version of the segment that can be shown immediately,\n * and may or may not contain dynamic holes. It's prefetched before a\n * navigation occurs.\n *\n * During rendering, we will choose whether to render `rsc` or `prefetchRsc`\n * with `useDeferredValue`. As with the `rsc` field, a value of `null` means\n * no value was provided. In this case, the LayoutRouter will go straight to\n * rendering the `rsc` value; if that one is also missing, it will suspend and\n * trigger a lazy fetch.\n */\n prefetchRsc: React.ReactNode\n\n prefetchHead: HeadData | null\n\n head: HeadData\n\n loading: LoadingModuleData | Promise<LoadingModuleData>\n\n parallelRoutes: Map<string, ChildSegmentMap>\n\n /**\n * The timestamp of the navigation that last updated the CacheNode's data. If\n * a CacheNode is reused from a previous navigation, this value is not\n * updated. Used to track the staleness of the data.\n */\n navigatedAt: number\n}\n\nexport type DynamicParamTypes =\n | 'catchall'\n | 'catchall-intercepted-(..)(..)'\n | 'catchall-intercepted-(.)'\n | 'catchall-intercepted-(..)'\n | 'catchall-intercepted-(...)'\n | 'optional-catchall'\n | 'dynamic'\n | 'dynamic-intercepted-(..)(..)'\n | 'dynamic-intercepted-(.)'\n | 'dynamic-intercepted-(..)'\n | 'dynamic-intercepted-(...)'\n\nexport type DynamicParamTypesShort =\n | 'c'\n | 'ci(..)(..)'\n | 'ci(.)'\n | 'ci(..)'\n | 'ci(...)'\n | 'oc'\n | 'd'\n | 'di(..)(..)'\n | 'di(.)'\n | 'di(..)'\n | 'di(...)'\n\nexport type Segment =\n | string\n | [\n // Param name\n paramName: string,\n // Param cache key (almost the same as the value, but arrays are\n // concatenated into strings)\n // TODO: We should change this to just be the value. Currently we convert\n // it back to a value when passing to useParams. It only needs to be\n // a string when converted to a a cache key, but that doesn't mean we\n // need to store it as that representation.\n paramCacheKey: string,\n // Dynamic param type\n dynamicParamType: DynamicParamTypesShort,\n ]\n\n/**\n * Router state\n */\nexport type FlightRouterState = [\n segment: Segment,\n parallelRoutes: { [parallelRouterKey: string]: FlightRouterState },\n url?: string | null,\n /**\n * \"refresh\" and \"refetch\", despite being similarly named, have different\n * semantics:\n * - \"refetch\" is used during a request to inform the server where rendering\n * should start from.\n *\n * - \"refresh\" is used by the client to mark that a segment should re-fetch the\n * data from the server for the current segment. It uses the \"url\" property\n * above to determine where to fetch from.\n *\n * - \"inside-shared-layout\" is used during a prefetch request to inform the\n * server that even if the segment matches, it should be treated as if it's\n * within the \"new\" part of a navigation — inside the shared layout. If\n * the segment doesn't match, then it has no effect, since it would be\n * treated as new regardless. If it does match, though, the server does not\n * need to render it, because the client already has it.\n *\n * - \"metadata-only\" instructs the server to skip rendering the segments and\n * only send the head data.\n *\n * A bit confusing, but that's because it has only one extremely narrow use\n * case — during a non-PPR prefetch, the server uses it to find the first\n * loading boundary beneath a shared layout.\n *\n * TODO: We should rethink the protocol for dynamic requests. It might not\n * make sense for the client to send a FlightRouterState, since this type is\n * overloaded with concerns.\n */\n refresh?:\n | 'refetch'\n | 'refresh'\n | 'inside-shared-layout'\n | 'metadata-only'\n | null,\n isRootLayout?: boolean,\n /**\n * Only present when responding to a tree prefetch request. Indicates whether\n * there is a loading boundary somewhere in the tree. The client cache uses\n * this to determine if it can skip the data prefetch request.\n */\n hasLoadingBoundary?: HasLoadingBoundary,\n]\n\nexport const enum HasLoadingBoundary {\n // There is a loading boundary in this particular segment\n SegmentHasLoadingBoundary = 1,\n // There is a loading boundary somewhere in the subtree (but not in\n // this segment)\n SubtreeHasLoadingBoundary = 2,\n // There is no loading boundary in this segment or any of its descendants\n SubtreeHasNoLoadingBoundary = 3,\n}\n\n/**\n * Individual Flight response path\n */\nexport type FlightSegmentPath =\n // Uses `any` as repeating pattern can't be typed.\n | any[]\n // Looks somewhat like this\n | [\n segment: Segment,\n parallelRouterKey: string,\n segment: Segment,\n parallelRouterKey: string,\n segment: Segment,\n parallelRouterKey: string,\n ]\n\n/**\n * Represents a tree of segments and the Flight data (i.e. React nodes) that\n * correspond to each one. The tree is isomorphic to the FlightRouterState;\n * however in the future we want to be able to fetch arbitrary partial segments\n * without having to fetch all its children. So this response format will\n * likely change.\n */\nexport type CacheNodeSeedData = [\n node: React.ReactNode | null,\n parallelRoutes: {\n [parallelRouterKey: string]: CacheNodeSeedData | null\n },\n loading: LoadingModuleData | Promise<LoadingModuleData>,\n isPartial: boolean,\n /** TODO: this doesn't feel like it belongs here, because it's only used during build, in `collectSegmentData` */\n hasRuntimePrefetch: boolean,\n]\n\nexport type FlightDataSegment = [\n /* segment of the rendered slice: */ Segment,\n /* treePatch */ FlightRouterState,\n /* cacheNodeSeedData */ CacheNodeSeedData | null, // Can be null during prefetch if there's no loading component\n /* head: viewport */ HeadData,\n /* isHeadPartial */ boolean,\n]\n\nexport type FlightDataPath =\n // Uses `any` as repeating pattern can't be typed.\n | any[]\n // Looks somewhat like this\n | [\n // Holds full path to the segment.\n ...FlightSegmentPath[],\n ...FlightDataSegment,\n ]\n\n/**\n * The Flight response data\n */\nexport type FlightData = Array<FlightDataPath> | string\n\nexport type ActionResult = Promise<any>\n\nexport type InitialRSCPayload = {\n /** buildId */\n b: string\n /** initialCanonicalUrlParts */\n c: string[]\n /** initialRenderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n /** initialFlightData */\n f: FlightDataPath[]\n /** missingSlots */\n m: Set<string> | undefined\n /** GlobalError */\n G: [React.ComponentType<any>, React.ReactNode | undefined]\n /** prerendered */\n S: boolean\n}\n\n// Response from `createFromFetch` for normal rendering\nexport type NavigationFlightResponse = {\n /** buildId */\n b: string\n /** flightData */\n f: FlightData\n /** prerendered */\n S: boolean\n /** renderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n /** runtimePrefetch - [isPartial, staleTime]. Only present in runtime prefetch responses. */\n rp?: [boolean, number]\n}\n\n// Response from `createFromFetch` for server actions. Action's flight data can be null\nexport type ActionFlightResponse = {\n /** actionResult */\n a: ActionResult\n /** buildId */\n b: string\n /** flightData */\n f: FlightData\n /** renderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n}\n\nexport type RSCPayload =\n | InitialRSCPayload\n | NavigationFlightResponse\n | ActionFlightResponse\n","import type { Segment } from '../../shared/lib/app-router-types'\n\nexport const matchSegment = (\n existingSegment: Segment,\n segment: Segment\n): boolean => {\n // segment is either Array or string\n if (typeof existingSegment === 'string') {\n if (typeof segment === 'string') {\n // Common case: segment is just a string\n return existingSegment === segment\n }\n return false\n }\n\n if (typeof segment === 'string') {\n return false\n }\n return existingSegment[0] === segment[0] && existingSegment[1] === segment[1]\n}\n","export const RSC_HEADER = 'rsc' as const\nexport const ACTION_HEADER = 'next-action' as const\n// TODO: Instead of sending the full router state, we only need to send the\n// segment path. Saves bytes. Then we could also use this field for segment\n// prefetches, which also need to specify a particular segment.\nexport const NEXT_ROUTER_STATE_TREE_HEADER = 'next-router-state-tree' as const\nexport const NEXT_ROUTER_PREFETCH_HEADER = 'next-router-prefetch' as const\n// This contains the path to the segment being prefetched.\n// TODO: If we change next-router-state-tree to be a segment path, we can use\n// that instead. Then next-router-prefetch and next-router-segment-prefetch can\n// be merged into a single enum.\nexport const NEXT_ROUTER_SEGMENT_PREFETCH_HEADER =\n 'next-router-segment-prefetch' as const\nexport const NEXT_HMR_REFRESH_HEADER = 'next-hmr-refresh' as const\nexport const NEXT_HMR_REFRESH_HASH_COOKIE = '__next_hmr_refresh_hash__' as const\nexport const NEXT_URL = 'next-url' as const\nexport const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const\n\nexport const FLIGHT_HEADERS = [\n RSC_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_ROUTER_PREFETCH_HEADER,\n NEXT_HMR_REFRESH_HEADER,\n NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n] as const\n\nexport const NEXT_RSC_UNION_QUERY = '_rsc' as const\n\nexport const NEXT_ROUTER_STALE_TIME_HEADER = 'x-nextjs-stale-time' as const\nexport const NEXT_DID_POSTPONE_HEADER = 'x-nextjs-postponed' as const\nexport const NEXT_REWRITTEN_PATH_HEADER = 'x-nextjs-rewritten-path' as const\nexport const NEXT_REWRITTEN_QUERY_HEADER = 'x-nextjs-rewritten-query' as const\nexport const NEXT_IS_PRERENDER_HEADER = 'x-nextjs-prerender' as const\nexport const NEXT_ACTION_NOT_FOUND_HEADER = 'x-nextjs-action-not-found' as const\nexport const NEXT_REQUEST_ID_HEADER = 'x-nextjs-request-id' as const\nexport const NEXT_HTML_REQUEST_ID_HEADER = 'x-nextjs-html-request-id' as const\n\n// TODO: Should this include nextjs in the name, like the others?\nexport const NEXT_ACTION_REVALIDATED_HEADER = 'x-action-revalidated' as const\n","import type { CacheNode } from '../../../shared/lib/app-router-types'\nimport type {\n FlightRouterState,\n FlightSegmentPath,\n} from '../../../shared/lib/app-router-types'\nimport type { NavigationSeed } from '../segment-cache/navigation'\nimport type { FetchServerResponseResult } from './fetch-server-response'\n\nexport const ACTION_REFRESH = 'refresh'\nexport const ACTION_NAVIGATE = 'navigate'\nexport const ACTION_RESTORE = 'restore'\nexport const ACTION_SERVER_PATCH = 'server-patch'\nexport const ACTION_HMR_REFRESH = 'hmr-refresh'\nexport const ACTION_SERVER_ACTION = 'server-action'\n\nexport type RouterChangeByServerResponse = ({\n navigatedAt,\n previousTree,\n serverResponse,\n}: {\n navigatedAt: number\n previousTree: FlightRouterState\n serverResponse: FetchServerResponseResult\n}) => void\n\nexport interface Mutable {\n mpaNavigation?: boolean\n patchedTree?: FlightRouterState\n renderedSearch?: string\n canonicalUrl?: string\n scrollableSegments?: FlightSegmentPath[]\n pendingPush?: boolean\n cache?: CacheNode\n hashFragment?: string\n shouldScroll?: boolean\n preserveCustomHistoryState?: boolean\n onlyHashChange?: boolean\n collectedDebugInfo?: Array<unknown>\n}\n\nexport interface ServerActionMutable extends Mutable {\n inFlightServerAction?: Promise<any> | null\n}\n\n/**\n * Refresh triggers a refresh of the full page data.\n * - fetches the Flight data and fills rsc at the root of the cache.\n * - The router state is updated at the root.\n */\nexport interface RefreshAction {\n type: typeof ACTION_REFRESH\n}\n\nexport interface HmrRefreshAction {\n type: typeof ACTION_HMR_REFRESH\n}\n\nexport type ServerActionDispatcher = (\n args: Omit<\n ServerActionAction,\n 'type' | 'mutable' | 'navigate' | 'changeByServerResponse' | 'cache'\n >\n) => void\n\nexport interface ServerActionAction {\n type: typeof ACTION_SERVER_ACTION\n actionId: string\n actionArgs: any[]\n resolve: (value: any) => void\n reject: (reason?: any) => void\n didRevalidate?: boolean\n}\n\n/**\n * Navigate triggers a navigation to the provided url. It supports two types: `push` and `replace`.\n *\n * `navigateType`:\n * - `push` - pushes a new history entry in the browser history\n * - `replace` - replaces the current history entry in the browser history\n *\n * Navigate has multiple cache heuristics:\n * - page was prefetched\n * - Apply router state tree from prefetch\n * - Apply Flight data from prefetch to the cache\n * - If Flight data is a string, it's a redirect and the state is updated to trigger a redirect\n * - Check if hard navigation is needed\n * - Hard navigation happens when a dynamic parameter below the common layout changed\n * - When hard navigation is needed the cache is invalidated below the flightSegmentPath\n * - The missing cache nodes of the page will be fetched in layout-router and trigger the SERVER_PATCH action\n * - If hard navigation is not needed\n * - The cache is reused\n * - If any cache nodes are missing they'll be fetched in layout-router and trigger the SERVER_PATCH action\n * - page was not prefetched\n * - The navigate was called from `next/router` (`router.push()` / `router.replace()`) / `next/link` without prefetched data available (e.g. the prefetch didn't come back from the server before clicking the link)\n * - Flight data is fetched in the reducer (suspends the reducer)\n * - Router state tree is created based on Flight data\n * - Cache is filled based on the Flight data\n *\n * Above steps explain 3 cases:\n * - `soft` - Reuses the existing cache and fetches missing nodes in layout-router.\n * - `hard` - Creates a new cache where cache nodes are removed below the common layout and fetches missing nodes in layout-router.\n * - `optimistic` (explicit no prefetch) - Creates a new cache and kicks off the data fetch in the reducer. The data fetch is awaited in the layout-router.\n */\nexport interface NavigateAction {\n type: typeof ACTION_NAVIGATE\n url: URL\n isExternalUrl: boolean\n locationSearch: Location['search']\n navigateType: 'push' | 'replace'\n shouldScroll: boolean\n}\n\n/**\n * Restore applies the provided router state.\n * - Used for `popstate` (back/forward navigation) where a known router state has to be applied.\n * - Also used when syncing the router state with `pushState`/`replaceState` calls.\n * - Router state is applied as-is from the history state, if available.\n * - If the history state does not contain the router state, the existing router state is used.\n * - If any cache node is missing it will be fetched in layout-router during rendering and the server-patch case.\n * - If existing cache nodes match these are used.\n */\nexport interface RestoreAction {\n type: typeof ACTION_RESTORE\n url: URL\n historyState: AppHistoryState | undefined\n}\n\nexport type AppHistoryState = {\n tree: FlightRouterState\n renderedSearch: string\n}\n\n/**\n * Server-patch applies the provided Flight data to the cache and router tree.\n */\nexport interface ServerPatchAction {\n type: typeof ACTION_SERVER_PATCH\n previousTree: FlightRouterState\n url: URL\n nextUrl: string | null\n seed: NavigationSeed | null\n mpa: boolean\n}\n\n/**\n * PrefetchKind defines the type of prefetching that should be done.\n * - `auto` - if the page is dynamic, prefetch the page data partially, if static prefetch the page data fully.\n * - `full` - prefetch the page data fully.\n */\n\nexport enum PrefetchKind {\n AUTO = 'auto',\n FULL = 'full',\n}\n\n/**\n * Prefetch adds the provided FlightData to the prefetch cache\n * - Creates the router state tree based on the patch in FlightData\n * - Adds the FlightData to the prefetch cache\n * - In ACTION_NAVIGATE the prefetch cache is checked and the router state tree and FlightData are applied.\n */\n\nexport interface PushRef {\n /**\n * If the app-router should push a new history entry in app-router's useEffect()\n */\n pendingPush: boolean\n /**\n * Multi-page navigation through location.href.\n */\n mpaNavigation: boolean\n /**\n * Skip applying the router state to the browser history state.\n */\n preserveCustomHistoryState: boolean\n}\n\nexport type FocusAndScrollRef = {\n /**\n * If focus and scroll should be set in the layout-router's useEffect()\n */\n apply: boolean\n /**\n * The hash fragment that should be scrolled to.\n */\n hashFragment: string | null\n /**\n * The paths of the segments that should be focused.\n */\n segmentPaths: FlightSegmentPath[]\n /**\n * If only the URLs hash fragment changed\n */\n onlyHashChange: boolean\n}\n\n/**\n * Handles keeping the state of app-router.\n */\nexport type AppRouterState = {\n /**\n * The router state, this is written into the history state in app-router using replaceState/pushState.\n * - Has to be serializable as it is written into the history state.\n * - Holds which segments and parallel routes are shown on the screen.\n */\n tree: FlightRouterState\n /**\n * The cache holds React nodes for every segment that is shown on screen as well as previously shown segments.\n * It also holds in-progress data requests.\n */\n cache: CacheNode\n /**\n * Decides if the update should create a new history entry and if the navigation has to trigger a browser navigation.\n */\n pushRef: PushRef\n /**\n * Decides if the update should apply scroll and focus management.\n */\n focusAndScrollRef: FocusAndScrollRef\n /**\n * The canonical url that is pushed/replaced.\n * - This is the url you see in the browser.\n */\n canonicalUrl: string\n renderedSearch: string\n /**\n * The underlying \"url\" representing the UI state, which is used for intercepting routes.\n */\n nextUrl: string | null\n\n /**\n * The previous next-url that was used previous to a dynamic navigation.\n */\n previousNextUrl: string | null\n\n debugInfo: Array<unknown> | null\n}\n\nexport type ReadonlyReducerState = Readonly<AppRouterState>\nexport type ReducerState =\n | (Promise<AppRouterState> & { _debugInfo?: Array<unknown> })\n | AppRouterState\nexport type ReducerActions = Readonly<\n | RefreshAction\n | NavigateAction\n | RestoreAction\n | ServerPatchAction\n | HmrRefreshAction\n | ServerActionAction\n>\n","/**\n * Check to see if a value is Thenable.\n *\n * @param promise the maybe-thenable value\n * @returns true if the value is thenable\n */\nexport function isThenable<T = unknown>(\n promise: Promise<T> | T\n): promise is Promise<T> {\n return (\n promise !== null &&\n typeof promise === 'object' &&\n 'then' in promise &&\n typeof promise.then === 'function'\n )\n}\n","import type { Dispatch } from 'react'\nimport React, { use, useMemo } from 'react'\nimport { isThenable } from '../../shared/lib/is-thenable'\nimport type { AppRouterActionQueue } from './app-router-instance'\nimport type {\n AppRouterState,\n ReducerActions,\n ReducerState,\n} from './router-reducer/router-reducer-types'\n\n// The app router state lives outside of React, so we can import the dispatch\n// method directly wherever we need it, rather than passing it around via props\n// or context.\nlet dispatch: Dispatch<ReducerActions> | null = null\n\nexport function dispatchAppRouterAction(action: ReducerActions) {\n if (dispatch === null) {\n throw new Error(\n 'Internal Next.js error: Router action dispatched before initialization.'\n )\n }\n dispatch(action)\n}\n\nconst __DEV__ = process.env.NODE_ENV !== 'production'\nconst promisesWithDebugInfo: WeakMap<\n Promise<AppRouterState>,\n Promise<AppRouterState> & { _debugInfo?: Array<unknown> }\n> = __DEV__ ? new WeakMap() : (null as any)\n\nexport function useActionQueue(\n actionQueue: AppRouterActionQueue\n): AppRouterState {\n const [state, setState] = React.useState<ReducerState>(actionQueue.state)\n\n // Because of a known issue that requires to decode Flight streams inside the\n // render phase, we have to be a bit clever and assign the dispatch method to\n // a module-level variable upon initialization. The useState hook in this\n // module only exists to synchronize state that lives outside of React.\n // Ideally, what we'd do instead is pass the state as a prop to root.render;\n // this is conceptually how we're modeling the app router state, despite the\n // weird implementation details.\n if (process.env.NODE_ENV !== 'production') {\n const { useAppDevRenderingIndicator } =\n require('../../next-devtools/userspace/use-app-dev-rendering-indicator') as typeof import('../../next-devtools/userspace/use-app-dev-rendering-indicator')\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const appDevRenderingIndicator = useAppDevRenderingIndicator()\n\n dispatch = (action: ReducerActions) => {\n appDevRenderingIndicator(() => {\n actionQueue.dispatch(action, setState)\n })\n }\n } else {\n dispatch = (action: ReducerActions) =>\n actionQueue.dispatch(action, setState)\n }\n\n // When navigating to a non-prefetched route, then App Router state will be\n // blocked until the server responds. We need to transfer the `_debugInfo`\n // from the underlying Flight response onto the top-level promise that is\n // passed to React (via `use`) so that the latency is accurately represented\n // in the React DevTools.\n const stateWithDebugInfo = useMemo(() => {\n if (!__DEV__) {\n return state\n }\n\n if (isThenable(state)) {\n // useMemo can't be used to cache a Promise since the memoized value is thrown\n // away when we suspend. So we use a WeakMap to cache the Promise with debug info.\n let promiseWithDebugInfo = promisesWithDebugInfo.get(state)\n if (promiseWithDebugInfo === undefined) {\n const debugInfo: Array<unknown> = []\n promiseWithDebugInfo = Promise.resolve(state).then((asyncState) => {\n if (asyncState.debugInfo !== null) {\n debugInfo.push(...asyncState.debugInfo)\n }\n return asyncState\n }) as Promise<AppRouterState> & { _debugInfo?: Array<unknown> }\n promiseWithDebugInfo._debugInfo = debugInfo\n\n promisesWithDebugInfo.set(state, promiseWithDebugInfo)\n }\n\n return promiseWithDebugInfo\n }\n return state\n }, [state])\n\n return isThenable(stateWithDebugInfo)\n ? use(stateWithDebugInfo)\n : stateWithDebugInfo\n}\n","import { startTransition } from 'react'\nimport { ACTION_SERVER_ACTION } from './components/router-reducer/router-reducer-types'\nimport { dispatchAppRouterAction } from './components/use-action-queue'\n\nexport async function callServer(actionId: string, actionArgs: any[]) {\n return new Promise((resolve, reject) => {\n startTransition(() => {\n dispatchAppRouterAction({\n type: ACTION_SERVER_ACTION,\n actionId,\n actionArgs,\n resolve,\n reject,\n })\n })\n })\n}\n","const basePath = process.env.__NEXT_ROUTER_BASEPATH || ''\nconst pathname = `${basePath}/__nextjs_source-map`\n\nexport const findSourceMapURL =\n process.env.NODE_ENV === 'development'\n ? function findSourceMapURL(filename: string): string | null {\n if (filename === '') {\n return null\n }\n\n if (\n filename.startsWith(document.location.origin) &&\n filename.includes('/_next/static')\n ) {\n // This is a request for a client chunk. This can only happen when\n // using Turbopack. In this case, since we control how those source\n // maps are generated, we can safely assume that the sourceMappingURL\n // is relative to the filename, with an added `.map` extension. The\n // browser can just request this file, and it gets served through the\n // normal dev server, without the need to route this through\n // the `/__nextjs_source-map` dev middleware.\n return `${filename}.map`\n }\n\n const url = new URL(pathname, document.location.origin)\n url.searchParams.set('filename', filename)\n\n return url.href\n }\n : undefined\n","import type { FlightRouterState, Segment } from './app-router-types'\n\nexport function getSegmentValue(segment: Segment) {\n return Array.isArray(segment) ? segment[1] : segment\n}\n\nexport function isGroupSegment(segment: string) {\n // Use array[0] for performant purpose\n return segment[0] === '(' && segment.endsWith(')')\n}\n\nexport function isParallelRouteSegment(segment: string) {\n return segment.startsWith('@') && segment !== '@children'\n}\n\nexport function addSearchParamsIfPageSegment(\n segment: Segment,\n searchParams: Record<string, string | string[] | undefined>\n) {\n const isPageSegment = segment.includes(PAGE_SEGMENT_KEY)\n\n if (isPageSegment) {\n const stringifiedQuery = JSON.stringify(searchParams)\n return stringifiedQuery !== '{}'\n ? PAGE_SEGMENT_KEY + '?' + stringifiedQuery\n : PAGE_SEGMENT_KEY\n }\n\n return segment\n}\n\nexport function computeSelectedLayoutSegment(\n segments: string[] | null,\n parallelRouteKey: string\n): string | null {\n if (!segments || segments.length === 0) {\n return null\n }\n\n // For 'children', use first segment; for other parallel routes, use last segment\n const rawSegment =\n parallelRouteKey === 'children'\n ? segments[0]\n : segments[segments.length - 1]\n\n // If the default slot is showing, return null since it's not technically \"selected\" (it's a fallback)\n // Returning an internal value like `__DEFAULT__` would be confusing\n return rawSegment === DEFAULT_SEGMENT_KEY ? null : rawSegment\n}\n\n/** Get the canonical parameters from the current level to the leaf node. */\nexport function getSelectedLayoutSegmentPath(\n tree: FlightRouterState,\n parallelRouteKey: string,\n first = true,\n segmentPath: string[] = []\n): string[] {\n let node: FlightRouterState\n if (first) {\n // Use the provided parallel route key on the first parallel route\n node = tree[1][parallelRouteKey]\n } else {\n // After first parallel route prefer children, if there's no children pick the first parallel route.\n const parallelRoutes = tree[1]\n node = parallelRoutes.children ?? Object.values(parallelRoutes)[0]\n }\n\n if (!node) return segmentPath\n const segment = node[0]\n\n let segmentValue = getSegmentValue(segment)\n\n if (!segmentValue || segmentValue.startsWith(PAGE_SEGMENT_KEY)) {\n return segmentPath\n }\n\n segmentPath.push(segmentValue)\n\n return getSelectedLayoutSegmentPath(\n node,\n parallelRouteKey,\n false,\n segmentPath\n )\n}\n\nexport const PAGE_SEGMENT_KEY = '__PAGE__'\nexport const DEFAULT_SEGMENT_KEY = '__DEFAULT__'\nexport const NOT_FOUND_SEGMENT_KEY = '/_not-found'\n","import { PAGE_SEGMENT_KEY } from '../segment'\nimport type { Segment as FlightRouterStateSegment } from '../app-router-types'\n\n// TypeScript trick to simulate opaque types, like in Flow.\ntype Opaque<K, T> = T & { __brand: K }\n\nexport type SegmentRequestKeyPart = Opaque<'SegmentRequestKeyPart', string>\nexport type SegmentRequestKey = Opaque<'SegmentRequestKey', string>\n\nexport const ROOT_SEGMENT_REQUEST_KEY = '' as SegmentRequestKey\n\nexport const HEAD_REQUEST_KEY = '/_head' as SegmentRequestKey\n\nexport function createSegmentRequestKeyPart(\n segment: FlightRouterStateSegment\n): SegmentRequestKeyPart {\n if (typeof segment === 'string') {\n if (segment.startsWith(PAGE_SEGMENT_KEY)) {\n // The Flight Router State type sometimes includes the search params in\n // the page segment. However, the Segment Cache tracks this as a separate\n // key. So, we strip the search params here, and then add them back when\n // the cache entry is turned back into a FlightRouterState. This is an\n // unfortunate consequence of the FlightRouteState being used both as a\n // transport type and as a cache key; we'll address this once more of the\n // Segment Cache implementation has settled.\n // TODO: We should hoist the search params out of the FlightRouterState\n // type entirely, This is our plan for dynamic route params, too.\n return PAGE_SEGMENT_KEY as SegmentRequestKeyPart\n }\n const safeName =\n // TODO: FlightRouterState encodes Not Found routes as \"/_not-found\".\n // But params typically don't include the leading slash. We should use\n // a different encoding to avoid this special case.\n segment === '/_not-found'\n ? '_not-found'\n : encodeToFilesystemAndURLSafeString(segment)\n // Since this is not a dynamic segment, it's fully encoded. It does not\n // need to be \"hydrated\" with a param value.\n return safeName as SegmentRequestKeyPart\n }\n\n const name = segment[0]\n const paramType = segment[2]\n const safeName = encodeToFilesystemAndURLSafeString(name)\n\n const encodedName = '$' + paramType + '$' + safeName\n return encodedName as SegmentRequestKeyPart\n}\n\nexport function appendSegmentRequestKeyPart(\n parentRequestKey: SegmentRequestKey,\n parallelRouteKey: string,\n childRequestKeyPart: SegmentRequestKeyPart\n): SegmentRequestKey {\n // Aside from being filesystem safe, segment keys are also designed so that\n // each segment and parallel route creates its own subdirectory. Roughly in\n // the same shape as the source app directory. This is mostly just for easier\n // debugging (you can open up the build folder and navigate the output); if\n // we wanted to do we could just use a flat structure.\n\n // Omit the parallel route key for children, since this is the most\n // common case. Saves some bytes (and it's what the app directory does).\n const slotKey =\n parallelRouteKey === 'children'\n ? childRequestKeyPart\n : `@${encodeToFilesystemAndURLSafeString(parallelRouteKey)}/${childRequestKeyPart}`\n return (parentRequestKey + '/' + slotKey) as SegmentRequestKey\n}\n\n// Define a regex pattern to match the most common characters found in a route\n// param. It excludes anything that might not be cross-platform filesystem\n// compatible, like |. It does not need to be precise because the fallback is to\n// just base64url-encode the whole parameter, which is fine; we just don't do it\n// by default for compactness, and for easier debugging.\nconst simpleParamValueRegex = /^[a-zA-Z0-9\\-_@]+$/\n\nfunction encodeToFilesystemAndURLSafeString(value: string) {\n if (simpleParamValueRegex.test(value)) {\n return value\n }\n // If there are any unsafe characters, base64url-encode the entire value.\n // We also add a ! prefix so it doesn't collide with the simple case.\n const base64url = btoa(value)\n .replace(/\\+/g, '-') // Replace '+' with '-'\n .replace(/\\//g, '_') // Replace '/' with '_'\n .replace(/=+$/, '') // Remove trailing '='\n return '!' + base64url\n}\n\nexport function convertSegmentPathToStaticExportFilename(\n segmentPath: string\n): string {\n return `__next${segmentPath.replace(/\\//g, '.')}.txt`\n}\n","import type { DynamicParamTypesShort } from '../shared/lib/app-router-types'\nimport {\n addSearchParamsIfPageSegment,\n DEFAULT_SEGMENT_KEY,\n PAGE_SEGMENT_KEY,\n} from '../shared/lib/segment'\nimport { ROOT_SEGMENT_REQUEST_KEY } from '../shared/lib/segment-cache/segment-value-encoding'\nimport {\n NEXT_REWRITTEN_PATH_HEADER,\n NEXT_REWRITTEN_QUERY_HEADER,\n NEXT_RSC_UNION_QUERY,\n} from './components/app-router-headers'\nimport type {\n NormalizedPathname,\n NormalizedSearch,\n} from './components/segment-cache/cache-key'\nimport type { RSCResponse } from './components/router-reducer/fetch-server-response'\nimport type { ParsedUrlQuery } from 'querystring'\n\nexport type RouteParamValue = string | Array<string> | null\n\nexport function getRenderedSearch(\n response: RSCResponse<unknown> | Response\n): NormalizedSearch {\n // If the server performed a rewrite, the search params used to render the\n // page will be different from the params in the request URL. In this case,\n // the response will include a header that gives the rewritten search query.\n const rewrittenQuery = response.headers.get(NEXT_REWRITTEN_QUERY_HEADER)\n if (rewrittenQuery !== null) {\n return (\n rewrittenQuery === '' ? '' : '?' + rewrittenQuery\n ) as NormalizedSearch\n }\n // If the header is not present, there was no rewrite, so we use the search\n // query of the response URL.\n return urlToUrlWithoutFlightMarker(new URL(response.url))\n .search as NormalizedSearch\n}\n\nexport function getRenderedPathname(\n response: RSCResponse<unknown> | Response\n): NormalizedPathname {\n // If the server performed a rewrite, the pathname used to render the\n // page will be different from the pathname in the request URL. In this case,\n // the response will include a header that gives the rewritten pathname.\n const rewrittenPath = response.headers.get(NEXT_REWRITTEN_PATH_HEADER)\n return (rewrittenPath ??\n urlToUrlWithoutFlightMarker(new URL(response.url))\n .pathname) as NormalizedPathname\n}\n\nexport function parseDynamicParamFromURLPart(\n paramType: DynamicParamTypesShort,\n pathnameParts: Array<string>,\n partIndex: number\n): RouteParamValue {\n // This needs to match the behavior in get-dynamic-param.ts.\n switch (paramType) {\n // Catchalls\n case 'c': {\n // Catchalls receive all the remaining URL parts. If there are no\n // remaining pathname parts, return an empty array.\n return partIndex < pathnameParts.length\n ? pathnameParts.slice(partIndex).map((s) => encodeURIComponent(s))\n : []\n }\n // Catchall intercepted\n case 'ci(..)(..)':\n case 'ci(.)':\n case 'ci(..)':\n case 'ci(...)': {\n const prefix = paramType.length - 2\n return partIndex < pathnameParts.length\n ? pathnameParts.slice(partIndex).map((s, i) => {\n if (i === 0) {\n return encodeURIComponent(s.slice(prefix))\n }\n\n return encodeURIComponent(s)\n })\n : []\n }\n // Optional catchalls\n case 'oc': {\n // Optional catchalls receive all the remaining URL parts, unless this is\n // the end of the pathname, in which case they return null.\n return partIndex < pathnameParts.length\n ? pathnameParts.slice(partIndex).map((s) => encodeURIComponent(s))\n : null\n }\n // Dynamic\n case 'd': {\n if (partIndex >= pathnameParts.length) {\n // The route tree expected there to be more parts in the URL than there\n // actually are. This could happen if the x-nextjs-rewritten-path header\n // is incorrectly set, or potentially due to bug in Next.js. TODO:\n // Should this be a hard error? During a prefetch, we can just abort.\n // During a client navigation, we could trigger a hard refresh. But if\n // it happens during initial render, we don't really have any\n // recovery options.\n return ''\n }\n return encodeURIComponent(pathnameParts[partIndex])\n }\n // Dynamic intercepted\n case 'di(..)(..)':\n case 'di(.)':\n case 'di(..)':\n case 'di(...)': {\n const prefix = paramType.length - 2\n if (partIndex >= pathnameParts.length) {\n // The route tree expected there to be more parts in the URL than there\n // actually are. This could happen if the x-nextjs-rewritten-path header\n // is incorrectly set, or potentially due to bug in Next.js. TODO:\n // Should this be a hard error? During a prefetch, we can just abort.\n // During a client navigation, we could trigger a hard refresh. But if\n // it happens during initial render, we don't really have any\n // recovery options.\n return ''\n }\n\n return encodeURIComponent(pathnameParts[partIndex].slice(prefix))\n }\n default:\n paramType satisfies never\n return ''\n }\n}\n\nexport function doesStaticSegmentAppearInURL(segment: string): boolean {\n // This is not a parameterized segment; however, we need to determine\n // whether or not this segment appears in the URL. For example, this route\n // groups do not appear in the URL, so they should be skipped. Any other\n // special cases must be handled here.\n // TODO: Consider encoding this directly into the router tree instead of\n // inferring it on the client based on the segment type. Something like\n // a `doesAppearInURL` flag in FlightRouterState.\n if (\n segment === ROOT_SEGMENT_REQUEST_KEY ||\n // For some reason, the loader tree sometimes includes extra __PAGE__\n // \"layouts\" when part of a parallel route. But it's not a leaf node.\n // Otherwise, we wouldn't need this special case because pages are\n // always leaf nodes.\n // TODO: Investigate why the loader produces these fake page segments.\n segment.startsWith(PAGE_SEGMENT_KEY) ||\n // Route groups.\n (segment[0] === '(' && segment.endsWith(')')) ||\n segment === DEFAULT_SEGMENT_KEY ||\n segment === '/_not-found'\n ) {\n return false\n } else {\n // All other segment types appear in the URL\n return true\n }\n}\n\nexport function getCacheKeyForDynamicParam(\n paramValue: RouteParamValue,\n renderedSearch: NormalizedSearch\n): string {\n // This needs to match the logic in get-dynamic-param.ts, until we're able to\n // unify the various implementations so that these are always computed on\n // the client.\n if (typeof paramValue === 'string') {\n // TODO: Refactor or remove this helper function to accept a string rather\n // than the whole segment type. Also we can probably just append the\n // search string instead of turning it into JSON.\n const pageSegmentWithSearchParams = addSearchParamsIfPageSegment(\n paramValue,\n Object.fromEntries(new URLSearchParams(renderedSearch))\n ) as string\n return pageSegmentWithSearchParams\n } else if (paramValue === null) {\n return ''\n } else {\n return paramValue.join('/')\n }\n}\n\nexport function urlToUrlWithoutFlightMarker(url: URL): URL {\n const urlWithoutFlightParameters = new URL(url)\n urlWithoutFlightParameters.searchParams.delete(NEXT_RSC_UNION_QUERY)\n if (process.env.NODE_ENV === 'production') {\n if (\n process.env.__NEXT_CONFIG_OUTPUT === 'export' &&\n urlWithoutFlightParameters.pathname.endsWith('.txt')\n ) {\n const { pathname } = urlWithoutFlightParameters\n const length = pathname.endsWith('/index.txt') ? 10 : 4\n // Slice off `/index.txt` or `.txt` from the end of the pathname\n urlWithoutFlightParameters.pathname = pathname.slice(0, -length)\n }\n }\n return urlWithoutFlightParameters\n}\n\nexport function getParamValueFromCacheKey(\n paramCacheKey: string,\n paramType: DynamicParamTypesShort\n) {\n // Turn the cache key string sent by the server (as part of FlightRouterState)\n // into a value that can be passed to `useParams` and client components.\n const isCatchAll = paramType === 'c' || paramType === 'oc'\n if (isCatchAll) {\n // Catch-all param keys are a concatenation of the path segments.\n // See equivalent logic in `getSelectedParams`.\n // TODO: We should just pass the array directly, rather than concatenate\n // it to a string and then split it back to an array. It needs to be an\n // array in some places, like when passing a key React, but we can convert\n // it at runtime in those places.\n return paramCacheKey.split('/')\n }\n return paramCacheKey\n}\n\nexport function urlSearchParamsToParsedUrlQuery(\n searchParams: URLSearchParams\n): ParsedUrlQuery {\n // Converts a URLSearchParams object to the same type used by the server when\n // creating search params props, i.e. the type returned by Node's\n // \"querystring\" module.\n const result: ParsedUrlQuery = {}\n for (const [key, value] of searchParams.entries()) {\n if (result[key] === undefined) {\n result[key] = value\n } else if (Array.isArray(result[key])) {\n result[key].push(value)\n } else {\n result[key] = [result[key], value]\n }\n }\n return result\n}\n","export function createHrefFromUrl(\n url: Pick<URL, 'pathname' | 'search' | 'hash'>,\n includeHash: boolean = true\n): string {\n return url.pathname + url.search + (includeHash ? url.hash : '')\n}\n","import type {\n CacheNodeSeedData,\n FlightData,\n FlightDataPath,\n FlightRouterState,\n FlightSegmentPath,\n Segment,\n HeadData,\n InitialRSCPayload,\n} from '../shared/lib/app-router-types'\nimport { PAGE_SEGMENT_KEY } from '../shared/lib/segment'\nimport type { NormalizedSearch } from './components/segment-cache/cache-key'\nimport {\n getCacheKeyForDynamicParam,\n parseDynamicParamFromURLPart,\n doesStaticSegmentAppearInURL,\n getRenderedPathname,\n getRenderedSearch,\n} from './route-params'\nimport { createHrefFromUrl } from './components/router-reducer/create-href-from-url'\n\nexport type NormalizedFlightData = {\n /**\n * The full `FlightSegmentPath` inclusive of the final `Segment`\n */\n segmentPath: FlightSegmentPath\n /**\n * The `FlightSegmentPath` exclusive of the final `Segment`\n */\n pathToSegment: FlightSegmentPath\n segment: Segment\n tree: FlightRouterState\n seedData: CacheNodeSeedData | null\n head: HeadData\n isHeadPartial: boolean\n isRootRender: boolean\n}\n\n// TODO: We should only have to export `normalizeFlightData`, however because the initial flight data\n// that gets passed to `createInitialRouterState` doesn't conform to the `FlightDataPath` type (it's missing the root segment)\n// we're currently exporting it so we can use it directly. This should be fixed as part of the unification of\n// the different ways we express `FlightSegmentPath`.\nexport function getFlightDataPartsFromPath(\n flightDataPath: FlightDataPath\n): NormalizedFlightData {\n // Pick the last 4 items from the `FlightDataPath` to get the [tree, seedData, viewport, isHeadPartial].\n const flightDataPathLength = 4\n // tree, seedData, and head are *always* the last three items in the `FlightDataPath`.\n const [tree, seedData, head, isHeadPartial] =\n flightDataPath.slice(-flightDataPathLength)\n // The `FlightSegmentPath` is everything except the last three items. For a root render, it won't be present.\n const segmentPath = flightDataPath.slice(0, -flightDataPathLength)\n\n return {\n // TODO: Unify these two segment path helpers. We are inconsistently pushing an empty segment (\"\")\n // to the start of the segment path in some places which makes it hard to use solely the segment path.\n // Look for \"// TODO-APP: remove ''\" in the codebase.\n pathToSegment: segmentPath.slice(0, -1),\n segmentPath,\n // if the `FlightDataPath` corresponds with the root, there'll be no segment path,\n // in which case we default to ''.\n segment: segmentPath[segmentPath.length - 1] ?? '',\n tree,\n seedData,\n head,\n isHeadPartial,\n isRootRender: flightDataPath.length === flightDataPathLength,\n }\n}\n\nexport function createInitialRSCPayloadFromFallbackPrerender(\n response: Response,\n fallbackInitialRSCPayload: InitialRSCPayload\n): InitialRSCPayload {\n // This is a static fallback page. In order to hydrate the page, we need to\n // parse the client params from the URL, but to account for the possibility\n // that the page was rewritten, we need to check the response headers\n // for x-nextjs-rewritten-path or x-nextjs-rewritten-query headers. Since\n // we can't access the headers of the initial document response, the client\n // performs a fetch request to the current location. Since it's possible that\n // the fetch request will be dynamically rewritten to a different path than\n // the initial document, this fetch request delivers _all_ the hydration data\n // for the page; it was not inlined into the document, like it normally\n // would be.\n //\n // TODO: Consider treating the case where fetch is rewritten to a different\n // path from the document as a special deopt case. We should optimistically\n // assume this won't happen, inline the data into the document, and perform\n // a minimal request (like a HEAD or range request) to verify that the\n // response matches. Tricky to get right because we need to account for\n // all the different deployment environments we support, like output:\n // \"export\" mode, where we currently don't assume that custom response\n // headers are present.\n\n // Patch the Flight data sent by the server with the correct params parsed\n // from the URL + response object.\n const renderedPathname = getRenderedPathname(response)\n const renderedSearch = getRenderedSearch(response)\n const canonicalUrl = createHrefFromUrl(new URL(location.href))\n const originalFlightDataPath = fallbackInitialRSCPayload.f[0]\n const originalFlightRouterState = originalFlightDataPath[0]\n return {\n b: fallbackInitialRSCPayload.b,\n c: canonicalUrl.split('/'),\n q: renderedSearch,\n i: fallbackInitialRSCPayload.i,\n f: [\n [\n fillInFallbackFlightRouterState(\n originalFlightRouterState,\n renderedPathname,\n renderedSearch as NormalizedSearch\n ),\n originalFlightDataPath[1],\n originalFlightDataPath[2],\n originalFlightDataPath[2],\n ],\n ],\n m: fallbackInitialRSCPayload.m,\n G: fallbackInitialRSCPayload.G,\n S: fallbackInitialRSCPayload.S,\n }\n}\n\nfunction fillInFallbackFlightRouterState(\n flightRouterState: FlightRouterState,\n renderedPathname: string,\n renderedSearch: NormalizedSearch\n): FlightRouterState {\n const pathnameParts = renderedPathname.split('/').filter((p) => p !== '')\n const index = 0\n return fillInFallbackFlightRouterStateImpl(\n flightRouterState,\n renderedSearch,\n pathnameParts,\n index\n )\n}\n\nfunction fillInFallbackFlightRouterStateImpl(\n flightRouterState: FlightRouterState,\n renderedSearch: NormalizedSearch,\n pathnameParts: Array<string>,\n pathnamePartsIndex: number\n): FlightRouterState {\n const originalSegment = flightRouterState[0]\n let newSegment: Segment\n let doesAppearInURL: boolean\n if (typeof originalSegment === 'string') {\n newSegment = originalSegment\n doesAppearInURL = doesStaticSegmentAppearInURL(originalSegment)\n } else {\n const paramName = originalSegment[0]\n const paramType = originalSegment[2]\n const paramValue = parseDynamicParamFromURLPart(\n paramType,\n pathnameParts,\n pathnamePartsIndex\n )\n const cacheKey = getCacheKeyForDynamicParam(paramValue, renderedSearch)\n newSegment = [paramName, cacheKey, paramType]\n doesAppearInURL = true\n }\n\n // Only increment the index if the segment appears in the URL. If it's a\n // \"virtual\" segment, like a route group, it remains the same.\n const childPathnamePartsIndex = doesAppearInURL\n ? pathnamePartsIndex + 1\n : pathnamePartsIndex\n\n const children = flightRouterState[1]\n const newChildren: { [key: string]: FlightRouterState } = {}\n for (let key in children) {\n const childFlightRouterState = children[key]\n newChildren[key] = fillInFallbackFlightRouterStateImpl(\n childFlightRouterState,\n renderedSearch,\n pathnameParts,\n childPathnamePartsIndex\n )\n }\n\n const newState: FlightRouterState = [\n newSegment,\n newChildren,\n null,\n flightRouterState[3],\n flightRouterState[4],\n ]\n return newState\n}\n\nexport function getNextFlightSegmentPath(\n flightSegmentPath: FlightSegmentPath\n): FlightSegmentPath {\n // Since `FlightSegmentPath` is a repeated tuple of `Segment` and `ParallelRouteKey`, we slice off two items\n // to get the next segment path.\n return flightSegmentPath.slice(2)\n}\n\nexport function normalizeFlightData(\n flightData: FlightData\n): NormalizedFlightData[] | string {\n // FlightData can be a string when the server didn't respond with a proper flight response,\n // or when a redirect happens, to signal to the client that it needs to perform an MPA navigation.\n if (typeof flightData === 'string') {\n return flightData\n }\n\n return flightData.map((flightDataPath) =>\n getFlightDataPartsFromPath(flightDataPath)\n )\n}\n\n/**\n * This function is used to prepare the flight router state for the request.\n * It removes markers that are not needed by the server, and are purely used\n * for stashing state on the client.\n * @param flightRouterState - The flight router state to prepare.\n * @param isHmrRefresh - Whether this is an HMR refresh request.\n * @returns The prepared flight router state.\n */\nexport function prepareFlightRouterStateForRequest(\n flightRouterState: FlightRouterState,\n isHmrRefresh?: boolean\n): string {\n // HMR requests need the complete, unmodified state for proper functionality\n if (isHmrRefresh) {\n return encodeURIComponent(JSON.stringify(flightRouterState))\n }\n\n return encodeURIComponent(\n JSON.stringify(stripClientOnlyDataFromFlightRouterState(flightRouterState))\n )\n}\n\n/**\n * Recursively strips client-only data from FlightRouterState while preserving\n * server-needed information for proper rendering decisions.\n */\nfunction stripClientOnlyDataFromFlightRouterState(\n flightRouterState: FlightRouterState\n): FlightRouterState {\n const [\n segment,\n parallelRoutes,\n _url, // Intentionally unused - URLs are client-only\n refreshMarker,\n isRootLayout,\n hasLoadingBoundary,\n ] = flightRouterState\n\n // __PAGE__ segments are always fetched from the server, so there's\n // no need to send them up\n const cleanedSegment = stripSearchParamsFromPageSegment(segment)\n\n // Recursively process parallel routes\n const cleanedParallelRoutes: { [key: string]: FlightRouterState } = {}\n for (const [key, childState] of Object.entries(parallelRoutes)) {\n cleanedParallelRoutes[key] =\n stripClientOnlyDataFromFlightRouterState(childState)\n }\n\n const result: FlightRouterState = [\n cleanedSegment,\n cleanedParallelRoutes,\n null, // URLs omitted - server reconstructs paths from segments\n shouldPreserveRefreshMarker(refreshMarker) ? refreshMarker : null,\n ]\n\n // Append optional fields if present\n if (isRootLayout !== undefined) {\n result[4] = isRootLayout\n }\n if (hasLoadingBoundary !== undefined) {\n result[5] = hasLoadingBoundary\n }\n\n return result\n}\n\n/**\n * Strips search parameters from __PAGE__ segments to prevent sensitive\n * client-side data from being sent to the server.\n */\nfunction stripSearchParamsFromPageSegment(segment: Segment): Segment {\n if (\n typeof segment === 'string' &&\n segment.startsWith(PAGE_SEGMENT_KEY + '?')\n ) {\n return PAGE_SEGMENT_KEY\n }\n return segment\n}\n\n/**\n * Determines whether the refresh marker should be sent to the server\n * Client-only markers like 'refresh' are stripped, while server-needed markers\n * like 'refetch' and 'inside-shared-layout' are preserved.\n */\nfunction shouldPreserveRefreshMarker(\n refreshMarker: FlightRouterState[3]\n): boolean {\n return Boolean(refreshMarker && refreshMarker !== 'refresh')\n}\n","// This gets assigned as a side-effect during app initialization. Because it\n// represents the build used to create the JS bundle, it should never change\n// after being set, so we store it in a global variable.\n//\n// When performing RSC requests, if the incoming data has a different build ID,\n// we perform an MPA navigation/refresh to load the updated build and ensure\n// that the client and server in sync.\n\n// Starts as an empty string. In practice, because setAppBuildId is called\n// during initialization before hydration starts, this will always get\n// reassigned to the actual build ID before it's ever needed by a navigation.\n// If for some reasons it didn't, due to a bug or race condition, then on\n// navigation the build comparision would fail and trigger an MPA navigation.\nlet globalBuildId: string = ''\n\nexport function setAppBuildId(buildId: string) {\n globalBuildId = buildId\n}\n\nexport function getAppBuildId(): string {\n return globalBuildId\n}\n","// http://www.cse.yorku.ca/~oz/hash.html\n// More specifically, 32-bit hash via djbxor\n// (ref: https://gist.github.com/eplawless/52813b1d8ad9af510d85?permalink_comment_id=3367765#gistcomment-3367765)\n// This is due to number type differences between rust for turbopack to js number types,\n// where rust does not have easy way to repreesnt js's 53-bit float number type for the matching\n// overflow behavior. This is more `correct` in terms of having canonical hash across different runtime / implementation\n// as can gaurantee determinstic output from 32bit hash.\nexport function djb2Hash(str: string) {\n let hash = 5381\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i)\n hash = ((hash << 5) + hash + char) & 0xffffffff\n }\n return hash >>> 0\n}\n\nexport function hexHash(str: string) {\n return djb2Hash(str).toString(36).slice(0, 5)\n}\n","import { hexHash } from '../../hash'\n\nexport function computeCacheBustingSearchParam(\n prefetchHeader: '1' | '2' | '0' | undefined,\n segmentPrefetchHeader: string | string[] | undefined,\n stateTreeHeader: string | string[] | undefined,\n nextUrlHeader: string | string[] | undefined\n): string {\n if (\n (prefetchHeader === undefined || prefetchHeader === '0') &&\n segmentPrefetchHeader === undefined &&\n stateTreeHeader === undefined &&\n nextUrlHeader === undefined\n ) {\n return ''\n }\n return hexHash(\n [\n prefetchHeader || '0',\n segmentPrefetchHeader || '0',\n stateTreeHeader || '0',\n nextUrlHeader || '0',\n ].join(',')\n )\n}\n","'use client'\n\nimport { computeCacheBustingSearchParam } from '../../../shared/lib/router/utils/cache-busting-search-param'\nimport {\n NEXT_ROUTER_PREFETCH_HEADER,\n NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_URL,\n NEXT_RSC_UNION_QUERY,\n} from '../app-router-headers'\nimport type { RequestHeaders } from './fetch-server-response'\n\n/**\n * Mutates the provided URL by adding a cache-busting search parameter for CDNs that don't\n * support custom headers. This helps avoid caching conflicts by making each request unique.\n *\n * Rather than relying on the Vary header which some CDNs ignore, we append a search param\n * to create a unique URL that forces a fresh request.\n *\n * Example:\n * URL before: https://example.com/path?query=1\n * URL after: https://example.com/path?query=1&_rsc=abc123\n *\n * Note: This function mutates the input URL directly and does not return anything.\n *\n * TODO: Since we need to use a search param anyway, we could simplify by removing the custom\n * headers approach entirely and just use search params.\n */\nexport const setCacheBustingSearchParam = (\n url: URL,\n headers: RequestHeaders\n): void => {\n const uniqueCacheKey = computeCacheBustingSearchParam(\n headers[NEXT_ROUTER_PREFETCH_HEADER],\n headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER],\n headers[NEXT_ROUTER_STATE_TREE_HEADER],\n headers[NEXT_URL]\n )\n setCacheBustingSearchParamWithHash(url, uniqueCacheKey)\n}\n\n/**\n * Sets a cache-busting search parameter on a URL using a provided hash value.\n *\n * This function performs the same logic as `setCacheBustingSearchParam` but accepts\n * a pre-computed hash instead of computing it from headers.\n *\n * Example:\n * URL before: https://example.com/path?query=1\n * hash: \"abc123\"\n * URL after: https://example.com/path?query=1&_rsc=abc123\n *\n * If the hash is null, we will set `_rsc` search param without a value.\n * Like this: https://example.com/path?query=1&_rsc\n *\n * Note: This function mutates the input URL directly and does not return anything.\n */\nexport const setCacheBustingSearchParamWithHash = (\n url: URL,\n hash: string\n): void => {\n /**\n * Note that we intentionally do not use `url.searchParams.set` here:\n *\n * const url = new URL('https://example.com/search?q=custom%20spacing');\n * url.searchParams.set('_rsc', 'abc123');\n * console.log(url.toString()); // Outputs: https://example.com/search?q=custom+spacing&_rsc=abc123\n * ^ <--- this is causing confusion\n * This is in fact intended based on https://url.spec.whatwg.org/#interface-urlsearchparams, but\n * we want to preserve the %20 as %20 if that's what the user passed in, hence the custom\n * logic below.\n */\n const existingSearch = url.search\n const rawQuery = existingSearch.startsWith('?')\n ? existingSearch.slice(1)\n : existingSearch\n\n // Always remove any existing cache busting param and add a fresh one to ensure\n // we have the correct value based on current request headers\n const pairs = rawQuery\n .split('&')\n .filter((pair) => pair && !pair.startsWith(`${NEXT_RSC_UNION_QUERY}=`))\n\n if (hash.length > 0) {\n pairs.push(`${NEXT_RSC_UNION_QUERY}=${hash}`)\n } else {\n pairs.push(`${NEXT_RSC_UNION_QUERY}`)\n }\n url.search = pairs.length ? `?${pairs.join('&')}` : ''\n}\n","// This could also be a variable instead of a function, but some unit tests want to change the ID at\n// runtime. Even though that would never happen in a real deployment.\nexport function getDeploymentId(): string | undefined {\n return process.env.NEXT_DEPLOYMENT_ID\n}\n\nexport function getDeploymentIdQueryOrEmptyString(): string {\n let deploymentId = getDeploymentId()\n if (deploymentId) {\n return `?dpl=${deploymentId}`\n }\n return ''\n}\n","'use client'\n\n// TODO: Explicitly import from client.browser\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n createFromReadableStream as createFromReadableStreamBrowser,\n createFromFetch as createFromFetchBrowser,\n} from 'react-server-dom-webpack/client'\n\nimport type {\n FlightRouterState,\n NavigationFlightResponse,\n} from '../../../shared/lib/app-router-types'\n\nimport {\n type NEXT_ROUTER_PREFETCH_HEADER,\n type NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_RSC_UNION_QUERY,\n NEXT_URL,\n RSC_HEADER,\n RSC_CONTENT_TYPE_HEADER,\n NEXT_HMR_REFRESH_HEADER,\n NEXT_DID_POSTPONE_HEADER,\n NEXT_ROUTER_STALE_TIME_HEADER,\n NEXT_HTML_REQUEST_ID_HEADER,\n NEXT_REQUEST_ID_HEADER,\n} from '../app-router-headers'\nimport { callServer } from '../../app-call-server'\nimport { findSourceMapURL } from '../../app-find-source-map-url'\nimport {\n normalizeFlightData,\n prepareFlightRouterStateForRequest,\n type NormalizedFlightData,\n} from '../../flight-data-helpers'\nimport { getAppBuildId } from '../../app-build-id'\nimport { setCacheBustingSearchParam } from './set-cache-busting-search-param'\nimport {\n getRenderedSearch,\n urlToUrlWithoutFlightMarker,\n} from '../../route-params'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\nimport { getDeploymentId } from '../../../shared/lib/deployment-id'\n\nconst createFromReadableStream =\n createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream']\nconst createFromFetch =\n createFromFetchBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromFetch']\n\nlet createDebugChannel:\n | typeof import('../../dev/debug-channel').createDebugChannel\n | undefined\n\nif (\n process.env.NODE_ENV !== 'production' &&\n process.env.__NEXT_REACT_DEBUG_CHANNEL\n) {\n createDebugChannel = (\n require('../../dev/debug-channel') as typeof import('../../dev/debug-channel')\n ).createDebugChannel\n}\n\nexport interface FetchServerResponseOptions {\n readonly flightRouterState: FlightRouterState\n readonly nextUrl: string | null\n readonly isHmrRefresh?: boolean\n}\n\ntype SpaFetchServerResponseResult = {\n flightData: NormalizedFlightData[]\n canonicalUrl: URL\n renderedSearch: NormalizedSearch\n couldBeIntercepted: boolean\n prerendered: boolean\n postponed: boolean\n staleTime: number\n debugInfo: Array<any> | null\n}\n\ntype MpaFetchServerResponseResult = string\n\nexport type FetchServerResponseResult =\n | MpaFetchServerResponseResult\n | SpaFetchServerResponseResult\n\nexport type RequestHeaders = {\n [RSC_HEADER]?: '1'\n [NEXT_ROUTER_STATE_TREE_HEADER]?: string\n [NEXT_URL]?: string\n [NEXT_ROUTER_PREFETCH_HEADER]?: '1' | '2'\n [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]?: string\n 'x-deployment-id'?: string\n [NEXT_HMR_REFRESH_HEADER]?: '1'\n // A header that is only added in test mode to assert on fetch priority\n 'Next-Test-Fetch-Priority'?: RequestInit['priority']\n [NEXT_HTML_REQUEST_ID_HEADER]?: string // dev-only\n [NEXT_REQUEST_ID_HEADER]?: string // dev-only\n}\n\nfunction doMpaNavigation(url: string): FetchServerResponseResult {\n return urlToUrlWithoutFlightMarker(new URL(url, location.origin)).toString()\n}\n\nlet isPageUnloading = false\n\nif (typeof window !== 'undefined') {\n // Track when the page is unloading, e.g. due to reloading the page or\n // performing hard navigations. This allows us to suppress error logging when\n // the browser cancels in-flight requests during page unload.\n window.addEventListener('pagehide', () => {\n isPageUnloading = true\n })\n\n // Reset the flag on pageshow, e.g. when navigating back and the JavaScript\n // execution context is restored by the browser.\n window.addEventListener('pageshow', () => {\n isPageUnloading = false\n })\n}\n\n/**\n * Fetch the flight data for the provided url. Takes in the current router state\n * to decide what to render server-side.\n */\nexport async function fetchServerResponse(\n url: URL,\n options: FetchServerResponseOptions\n): Promise<FetchServerResponseResult> {\n const { flightRouterState, nextUrl } = options\n\n const headers: RequestHeaders = {\n // Enable flight response\n [RSC_HEADER]: '1',\n // Provide the current router state\n [NEXT_ROUTER_STATE_TREE_HEADER]: prepareFlightRouterStateForRequest(\n flightRouterState,\n options.isHmrRefresh\n ),\n }\n\n if (process.env.NODE_ENV === 'development' && options.isHmrRefresh) {\n headers[NEXT_HMR_REFRESH_HEADER] = '1'\n }\n\n if (nextUrl) {\n headers[NEXT_URL] = nextUrl\n }\n\n // In static export mode, we need to modify the URL to request the .txt file,\n // but we should preserve the original URL for the canonical URL and error handling.\n const originalUrl = url\n\n try {\n if (process.env.NODE_ENV === 'production') {\n if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {\n // In \"output: export\" mode, we can't rely on headers to distinguish\n // between HTML and RSC requests. Instead, we append an extra prefix\n // to the request.\n url = new URL(url)\n if (url.pathname.endsWith('/')) {\n url.pathname += 'index.txt'\n } else {\n url.pathname += '.txt'\n }\n }\n }\n\n // Typically, during a navigation, we decode the response using Flight's\n // `createFromFetch` API, which accepts a `fetch` promise.\n // TODO: Remove this check once the old PPR flag is removed\n const isLegacyPPR =\n process.env.__NEXT_PPR && !process.env.__NEXT_CACHE_COMPONENTS\n const shouldImmediatelyDecode = !isLegacyPPR\n const res = await createFetch<NavigationFlightResponse>(\n url,\n headers,\n 'auto',\n shouldImmediatelyDecode\n )\n\n const responseUrl = urlToUrlWithoutFlightMarker(new URL(res.url))\n const canonicalUrl = res.redirected ? responseUrl : originalUrl\n\n const contentType = res.headers.get('content-type') || ''\n const interception = !!res.headers.get('vary')?.includes(NEXT_URL)\n const postponed = !!res.headers.get(NEXT_DID_POSTPONE_HEADER)\n const staleTimeHeaderSeconds = res.headers.get(\n NEXT_ROUTER_STALE_TIME_HEADER\n )\n const staleTime =\n staleTimeHeaderSeconds !== null\n ? parseInt(staleTimeHeaderSeconds, 10) * 1000\n : -1\n let isFlightResponse = contentType.startsWith(RSC_CONTENT_TYPE_HEADER)\n\n if (process.env.NODE_ENV === 'production') {\n if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {\n if (!isFlightResponse) {\n isFlightResponse = contentType.startsWith('text/plain')\n }\n }\n }\n\n // If fetch returns something different than flight response handle it like a mpa navigation\n // If the fetch was not 200, we also handle it like a mpa navigation\n if (!isFlightResponse || !res.ok || !res.body) {\n // in case the original URL came with a hash, preserve it before redirecting to the new URL\n if (url.hash) {\n responseUrl.hash = url.hash\n }\n\n return doMpaNavigation(responseUrl.toString())\n }\n\n // We may navigate to a page that requires a different Webpack runtime.\n // In prod, every page will have the same Webpack runtime.\n // In dev, the Webpack runtime is minimal for each page.\n // We need to ensure the Webpack runtime is updated before executing client-side JS of the new page.\n // TODO: This needs to happen in the Flight Client.\n // Or Webpack needs to include the runtime update in the Flight response as\n // a blocking script.\n if (process.env.NODE_ENV !== 'production' && !process.env.TURBOPACK) {\n await (\n require('../../dev/hot-reloader/app/hot-reloader-app') as typeof import('../../dev/hot-reloader/app/hot-reloader-app')\n ).waitForWebpackRuntimeHotUpdate()\n }\n\n let flightResponsePromise = res.flightResponse\n if (flightResponsePromise === null) {\n // Typically, `createFetch` would have already started decoding the\n // Flight response. If it hasn't, though, we need to decode it now.\n // TODO: This should only be reachable if legacy PPR is enabled (i.e. PPR\n // without Cache Components). Remove this branch once legacy PPR\n // is deleted.\n const flightStream = postponed\n ? createUnclosingPrefetchStream(res.body)\n : res.body\n flightResponsePromise =\n createFromNextReadableStream<NavigationFlightResponse>(\n flightStream,\n headers\n )\n }\n\n const flightResponse = await flightResponsePromise\n\n if (getAppBuildId() !== flightResponse.b) {\n return doMpaNavigation(res.url)\n }\n\n const normalizedFlightData = normalizeFlightData(flightResponse.f)\n if (typeof normalizedFlightData === 'string') {\n return doMpaNavigation(normalizedFlightData)\n }\n\n return {\n flightData: normalizedFlightData,\n canonicalUrl: canonicalUrl,\n renderedSearch: getRenderedSearch(res),\n couldBeIntercepted: interception,\n prerendered: flightResponse.S,\n postponed,\n staleTime,\n debugInfo: flightResponsePromise._debugInfo ?? null,\n }\n } catch (err) {\n if (!isPageUnloading) {\n console.error(\n `Failed to fetch RSC payload for ${originalUrl}. Falling back to browser navigation.`,\n err\n )\n }\n\n // If fetch fails handle it like a mpa navigation\n // TODO-APP: Add a test for the case where a CORS request fails, e.g. external url redirect coming from the response.\n // See https://github.com/vercel/next.js/issues/43605#issuecomment-1451617521 for a reproduction.\n return originalUrl.toString()\n }\n}\n\n// This is a subset of the standard Response type. We use a custom type for\n// this so we can limit which details about the response leak into the rest of\n// the codebase. For example, there's some custom logic for manually following\n// redirects, so \"redirected\" in this type could be a composite of multiple\n// browser fetch calls; however, this fact should not leak to the caller.\nexport type RSCResponse<T> = {\n ok: boolean\n redirected: boolean\n headers: Headers\n body: ReadableStream<Uint8Array> | null\n status: number\n url: string\n flightResponse: (Promise<T> & { _debugInfo?: Array<any> }) | null\n}\n\nexport async function createFetch<T>(\n url: URL,\n headers: RequestHeaders,\n fetchPriority: 'auto' | 'high' | 'low' | null,\n shouldImmediatelyDecode: boolean,\n signal?: AbortSignal\n): Promise<RSCResponse<T>> {\n // TODO: In output: \"export\" mode, the headers do nothing. Omit them (and the\n // cache busting search param) from the request so they're\n // maximally cacheable.\n\n if (process.env.__NEXT_TEST_MODE && fetchPriority !== null) {\n headers['Next-Test-Fetch-Priority'] = fetchPriority\n }\n\n const deploymentId = getDeploymentId()\n if (deploymentId) {\n headers['x-deployment-id'] = deploymentId\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (self.__next_r) {\n headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r\n }\n\n // Create a new request ID for the server action request. The server uses\n // this to tag debug information sent via WebSocket to the client, which\n // then routes those chunks to the debug channel associated with this ID.\n headers[NEXT_REQUEST_ID_HEADER] = crypto\n .getRandomValues(new Uint32Array(1))[0]\n .toString(16)\n }\n\n const fetchOptions: RequestInit = {\n // Backwards compat for older browsers. `same-origin` is the default in modern browsers.\n credentials: 'same-origin',\n headers,\n priority: fetchPriority || undefined,\n signal,\n }\n // `fetchUrl` is slightly different from `url` because we add a cache-busting\n // search param to it. This should not leak outside of this function, so we\n // track them separately.\n let fetchUrl = new URL(url)\n setCacheBustingSearchParam(fetchUrl, headers)\n let fetchPromise = fetch(fetchUrl, fetchOptions)\n // Immediately pass the fetch promise to the Flight client so that the debug\n // info includes the latency from the client to the server. The internal timer\n // in React starts as soon as `createFromFetch` is called.\n //\n // The only case where we don't do this is during a prefetch, because we have\n // to do some extra processing of the response stream (see\n // `createUnclosingPrefetchStream`). But this is fine, because a top-level\n // prefetch response never blocks a navigation; if it hasn't already been\n // written into the cache by the time the navigation happens, the router will\n // go straight to a dynamic request.\n let flightResponsePromise = shouldImmediatelyDecode\n ? createFromNextFetch<T>(fetchPromise, headers)\n : null\n let browserResponse = await fetchPromise\n\n // If the server responds with a redirect (e.g. 307), and the redirected\n // location does not contain the cache busting search param set in the\n // original request, the response is likely invalid — when following the\n // redirect, the browser forwards the request headers, but since the cache\n // busting search param is missing, the server will reject the request due to\n // a mismatch.\n //\n // Ideally, we would be able to intercept the redirect response and perform it\n // manually, instead of letting the browser automatically follow it, but this\n // is not allowed by the fetch API.\n //\n // So instead, we must \"replay\" the redirect by fetching the new location\n // again, but this time we'll append the cache busting search param to prevent\n // a mismatch.\n //\n // TODO: We can optimize Next.js's built-in middleware APIs by returning a\n // custom status code, to prevent the browser from automatically following it.\n //\n // This does not affect Server Action-based redirects; those are encoded\n // differently, as part of the Flight body. It only affects redirects that\n // occur in a middleware or a third-party proxy.\n\n let redirected = browserResponse.redirected\n if (process.env.__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS) {\n // This is to prevent a redirect loop. Same limit used by Chrome.\n const MAX_REDIRECTS = 20\n for (let n = 0; n < MAX_REDIRECTS; n++) {\n if (!browserResponse.redirected) {\n // The server did not perform a redirect.\n break\n }\n const responseUrl = new URL(browserResponse.url, fetchUrl)\n if (responseUrl.origin !== fetchUrl.origin) {\n // The server redirected to an external URL. The rest of the logic below\n // is not relevant, because it only applies to internal redirects.\n break\n }\n if (\n responseUrl.searchParams.get(NEXT_RSC_UNION_QUERY) ===\n fetchUrl.searchParams.get(NEXT_RSC_UNION_QUERY)\n ) {\n // The redirected URL already includes the cache busting search param.\n // This was probably intentional. Regardless, there's no reason to\n // issue another request to this URL because it already has the param\n // value that we would have added below.\n break\n }\n // The RSC request was redirected. Assume the response is invalid.\n //\n // Append the cache busting search param to the redirected URL and\n // fetch again.\n // TODO: We should abort the previous request.\n fetchUrl = new URL(responseUrl)\n setCacheBustingSearchParam(fetchUrl, headers)\n fetchPromise = fetch(fetchUrl, fetchOptions)\n flightResponsePromise = shouldImmediatelyDecode\n ? createFromNextFetch<T>(fetchPromise, headers)\n : null\n browserResponse = await fetchPromise\n // We just performed a manual redirect, so this is now true.\n redirected = true\n }\n }\n\n // Remove the cache busting search param from the response URL, to prevent it\n // from leaking outside of this function.\n const responseUrl = new URL(browserResponse.url, fetchUrl)\n responseUrl.searchParams.delete(NEXT_RSC_UNION_QUERY)\n\n const rscResponse: RSCResponse<T> = {\n url: responseUrl.href,\n\n // This is true if any redirects occurred, either automatically by the\n // browser, or manually by us. So it's different from\n // `browserResponse.redirected`, which only tells us whether the browser\n // followed a redirect, and only for the last response in the chain.\n redirected,\n\n // These can be copied from the last browser response we received. We\n // intentionally only expose the subset of fields that are actually used\n // elsewhere in the codebase.\n ok: browserResponse.ok,\n headers: browserResponse.headers,\n body: browserResponse.body,\n status: browserResponse.status,\n\n // This is the exact promise returned by `createFromFetch`. It contains\n // debug information that we need to transfer to any derived promises that\n // are later rendered by React.\n flightResponse: flightResponsePromise,\n }\n\n return rscResponse\n}\n\nexport function createFromNextReadableStream<T>(\n flightStream: ReadableStream<Uint8Array>,\n requestHeaders: RequestHeaders\n): Promise<T> {\n return createFromReadableStream(flightStream, {\n callServer,\n findSourceMapURL,\n debugChannel: createDebugChannel && createDebugChannel(requestHeaders),\n })\n}\n\nfunction createFromNextFetch<T>(\n promiseForResponse: Promise<Response>,\n requestHeaders: RequestHeaders\n): Promise<T> & { _debugInfo?: Array<any> } {\n return createFromFetch(promiseForResponse, {\n callServer,\n findSourceMapURL,\n debugChannel: createDebugChannel && createDebugChannel(requestHeaders),\n })\n}\n\nfunction createUnclosingPrefetchStream(\n originalFlightStream: ReadableStream<Uint8Array>\n): ReadableStream<Uint8Array> {\n // When PPR is enabled, prefetch streams may contain references that never\n // resolve, because that's how we encode dynamic data access. In the decoded\n // object returned by the Flight client, these are reified into hanging\n // promises that suspend during render, which is effectively what we want.\n // The UI resolves when it switches to the dynamic data stream\n // (via useDeferredValue(dynamic, static)).\n //\n // However, the Flight implementation currently errors if the server closes\n // the response before all the references are resolved. As a cheat to work\n // around this, we wrap the original stream in a new stream that never closes,\n // and therefore doesn't error.\n const reader = originalFlightStream.getReader()\n return new ReadableStream({\n async pull(controller) {\n while (true) {\n const { done, value } = await reader.read()\n if (!done) {\n // Pass to the target stream and keep consuming the Flight response\n // from the server.\n controller.enqueue(value)\n continue\n }\n // The server stream has closed. Exit, but intentionally do not close\n // the target stream.\n return\n }\n },\n })\n}\n","import { deleteMapEntry } from './cache-map'\nimport type { UnknownMapEntry } from './cache-map'\n\n// We use an LRU for memory management. We must update this whenever we add or\n// remove a new cache entry, or when an entry changes size.\n\nlet head: UnknownMapEntry | null = null\nlet didScheduleCleanup: boolean = false\nlet lruSize: number = 0\n\n// TODO: I chose the max size somewhat arbitrarily. Consider setting this based\n// on navigator.deviceMemory, or some other heuristic. We should make this\n// customizable via the Next.js config, too.\nconst maxLruSize = 50 * 1024 * 1024 // 50 MB\n\nexport function lruPut(node: UnknownMapEntry) {\n if (head === node) {\n // Already at the head\n return\n }\n const prev = node.prev\n const next = node.next\n if (next === null || prev === null) {\n // This is an insertion\n lruSize += node.size\n // Whenever we add an entry, we need to check if we've exceeded the\n // max size. We don't evict entries immediately; they're evicted later in\n // an asynchronous task.\n ensureCleanupIsScheduled()\n } else {\n // This is a move. Remove from its current position.\n prev.next = next\n next.prev = prev\n }\n\n // Move to the front of the list\n if (head === null) {\n // This is the first entry\n node.prev = node\n node.next = node\n } else {\n // Add to the front of the list\n const tail = head.prev\n node.prev = tail\n // In practice, this is never null, but that isn't encoded in the type\n if (tail !== null) {\n tail.next = node\n }\n node.next = head\n head.prev = node\n }\n head = node\n}\n\nexport function updateLruSize(node: UnknownMapEntry, newNodeSize: number) {\n // This is a separate function from `put` so that we can resize the entry\n // regardless of whether it's currently being tracked by the LRU.\n const prevNodeSize = node.size\n node.size = newNodeSize\n if (node.next === null) {\n // This entry is not currently being tracked by the LRU.\n return\n }\n // Update the total LRU size\n lruSize = lruSize - prevNodeSize + newNodeSize\n ensureCleanupIsScheduled()\n}\n\nexport function deleteFromLru(deleted: UnknownMapEntry) {\n const next = deleted.next\n const prev = deleted.prev\n if (next !== null && prev !== null) {\n lruSize -= deleted.size\n\n deleted.next = null\n deleted.prev = null\n\n // Remove from the list\n if (head === deleted) {\n // Update the head\n if (next === head) {\n // This was the last entry\n head = null\n } else {\n head = next\n prev.next = next\n next.prev = prev\n }\n } else {\n prev.next = next\n next.prev = prev\n }\n } else {\n // Already deleted\n }\n}\n\nfunction ensureCleanupIsScheduled() {\n if (didScheduleCleanup || lruSize <= maxLruSize) {\n return\n }\n didScheduleCleanup = true\n requestCleanupCallback(cleanup)\n}\n\nfunction cleanup() {\n didScheduleCleanup = false\n\n // Evict entries until we're at 90% capacity. We can assume this won't\n // infinite loop because even if `maxLruSize` were 0, eventually\n // `deleteFromLru` sets `head` to `null` when we run out entries.\n const ninetyPercentMax = maxLruSize * 0.9\n while (lruSize > ninetyPercentMax && head !== null) {\n const tail = head.prev\n // In practice, this is never null, but that isn't encoded in the type\n if (tail !== null) {\n // Delete the entry from the map. In turn, this will remove it from\n // the LRU.\n deleteMapEntry(tail)\n }\n }\n}\n\nconst requestCleanupCallback =\n typeof requestIdleCallback === 'function'\n ? requestIdleCallback\n : (cb: () => void) => setTimeout(cb, 0)\n","import type { VaryPath } from './vary-path'\nimport { lruPut, updateLruSize, deleteFromLru } from './lru'\n\n/**\n * A specialized data type for storing multi-key cache entries.\n *\n * The basic structure is a map whose keys are tuples, called the keypath.\n * When querying the cache, keypaths are compared per-element.\n *\n * Example:\n * set(map, ['https://localhost', 'foo/bar/baz'], 'yay');\n * get(map, ['https://localhost', 'foo/bar/baz']) -> 'yay'\n *\n * NOTE: Array syntax is used in these examples for illustration purposes, but\n * in reality the paths are lists.\n * \n * The parts of the keypath represent the different inputs that contribute\n * to the entry value. To illustrate, if you were to use this data type to store\n * HTTP responses, the keypath would include the URL and everything listed by\n * the Vary header.\n * \n * See vary-path.ts for more details.\n *\n * The order of elements in a keypath must be consistent between lookups to\n * be considered the same, but besides that, the order of the keys is not\n * semantically meaningful.\n *\n * Keypaths may include a special kind of key called Fallback. When an entry is\n * stored with Fallback as part of its keypath, it means that the entry does not\n * vary by that key. When querying the cache, if an exact match is not found for\n * a keypath, the cache will check for a Fallback match instead. Each element of\n * the keypath may have a Fallback, so retrieval is an O(n ^ 2) operation, but\n * it's expected that keypaths are relatively short.\n *\n * Example:\n * set(cacheMap, ['store', 'product', 1], PRODUCT_PAGE_1);\n * set(cacheMap, ['store', 'product', Fallback], GENERIC_PRODUCT_PAGE);\n *\n * // Exact match\n * get(cacheMap, ['store', 'product', 1]) -> PRODUCT_PAGE_1\n *\n * // Fallback match\n * get(cacheMap, ['store', 'product', 2]) -> GENERIC_PRODUCT_PAGE\n *\n * Because we have the Fallback mechanism, we can impose a constraint that\n * regular JS maps do not have: a value cannot be stored at multiple keypaths\n * simultaneously. These cases should be expressed with Fallback keys instead.\n *\n * Additionally, because values only exist at a single keypath at a time, we\n * can optimize successive lookups by caching the internal map entry on the\n * value itself, using the `ref` field. This is especially useful because it\n * lets us skip the O(n ^ 2) lookup that occurs when Fallback entries\n * are present.\n *\n\n * How to decide if stuff belongs in here, or in cache.ts?\n * -------------------------------------------------------\n * \n * Anything to do with retrival, lifetimes, or eviction needs to go in this\n * module because it affects the fallback algorithm. For example, when\n * performing a lookup, if an entry is stale, it needs to be treated as\n * semantically equivalent to if the entry was not present at all.\n * \n * If there's logic that's not related to the fallback algorithm, though, we\n * should prefer to put it in cache.ts.\n */\n\n// The protocol that values must implement. In practice, the only two types that\n// we ever actually deal with in this module are RouteCacheEntry and\n// SegmentCacheEntry; this is just to keep track of the coupling so we don't\n// leak concerns between the modules unnecessarily.\nexport interface MapValue {\n ref: UnknownMapEntry | null\n size: number\n staleAt: number\n version: number\n}\n\n/**\n * Represents a node in the cache map and LRU.\n * MapEntry<V> structurally satisfies this interface for any V extends MapValue.\n *\n * The LRU can contain entries of different value types\n * (e.g., both RouteCacheEntry and SegmentCacheEntry). This interface captures\n * the common structure needed for cache map and LRU operations without\n * requiring knowledge of the specific value type.\n */\nexport interface MapEntry<V extends MapValue> {\n // Cache map structure fields\n parent: MapEntry<V> | null\n key: unknown\n map: Map<unknown, MapEntry<V>> | null\n value: V | null\n\n // LRU linked list fields\n prev: MapEntry<V> | null\n next: MapEntry<V> | null\n size: number\n}\n\n/**\n * A looser type for MapEntry\n * This allows the LRU to work with entries of different\n * value types while still providing type safety.\n *\n * The `map` field lets Map<unknown, MapEntry<V>> be assignable to this\n * type since we're only reading from the map, not inserting into it.\n */\nexport type UnknownMapEntry = {\n parent: UnknownMapEntry | null\n key: unknown\n map: Pick<Map<unknown, UnknownMapEntry>, 'get' | 'delete' | 'size'> | null\n value: MapValue | null\n\n prev: UnknownMapEntry | null\n next: UnknownMapEntry | null\n size: number\n}\n\n// The CacheMap type is just the root entry of the map.\nexport type CacheMap<V extends MapValue> = MapEntry<V>\n\nexport type FallbackType = { __brand: 'Fallback' }\nexport const Fallback = {} as FallbackType\n\n// This is a special internal key that is used for \"revalidation\" entries. It's\n// an implementation detail that shouldn't leak outside of this module.\nconst Revalidation = {}\n\nexport function createCacheMap<V extends MapValue>(): CacheMap<V> {\n const cacheMap: MapEntry<V> = {\n parent: null,\n key: null,\n value: null,\n map: null,\n\n // LRU-related fields\n prev: null,\n next: null,\n size: 0,\n }\n return cacheMap\n}\n\nfunction getOrInitialize<V extends MapValue>(\n cacheMap: CacheMap<V>,\n keys: VaryPath,\n isRevalidation: boolean\n): MapEntry<V> {\n // Go through each level of keys until we find the entry that matches, or\n // create a new entry if one doesn't exist.\n //\n // This function will only return entries that match the keypath _exactly_.\n // Unlike getWithFallback, it will not access fallback entries unless it's\n // explicitly part of the keypath.\n let entry = cacheMap\n let remainingKeys: VaryPath | null = keys\n let key: unknown | null = null\n while (true) {\n const previousKey = key\n if (remainingKeys !== null) {\n key = remainingKeys.value\n remainingKeys = remainingKeys.parent\n } else if (isRevalidation && previousKey !== Revalidation) {\n // During a revalidation, we append an internal \"Revalidation\" key to\n // the end of the keypath. The \"normal\" entry is its parent.\n\n // However, if the parent entry is currently empty, we don't need to store\n // this as a revalidation entry. Just insert the revalidation into the\n // normal slot.\n if (entry.value === null) {\n return entry\n }\n\n // Otheriwse, create a child entry.\n key = Revalidation\n } else {\n // There are no more keys. This is the terminal entry.\n break\n }\n\n let map = entry.map\n if (map !== null) {\n const existingEntry = map.get(key)\n if (existingEntry !== undefined) {\n // Found a match. Keep going.\n entry = existingEntry\n continue\n }\n } else {\n map = new Map()\n entry.map = map\n }\n // No entry exists yet at this level. Create a new one.\n const newEntry: MapEntry<V> = {\n parent: entry,\n key,\n value: null,\n map: null,\n\n // LRU-related fields\n prev: null,\n next: null,\n size: 0,\n }\n map.set(key, newEntry)\n entry = newEntry\n }\n\n return entry\n}\n\nexport function getFromCacheMap<V extends MapValue>(\n now: number,\n currentCacheVersion: number,\n rootEntry: CacheMap<V>,\n keys: VaryPath,\n isRevalidation: boolean\n): V | null {\n const entry = getEntryWithFallbackImpl(\n now,\n currentCacheVersion,\n rootEntry,\n keys,\n isRevalidation,\n 0\n )\n if (entry === null || entry.value === null) {\n return null\n }\n // This is an LRU access. Move the entry to the front of the list.\n lruPut(entry)\n return entry.value\n}\n\nexport function isValueExpired(\n now: number,\n currentCacheVersion: number,\n value: MapValue\n): boolean {\n return value.staleAt <= now || value.version < currentCacheVersion\n}\n\nfunction lazilyEvictIfNeeded<V extends MapValue>(\n now: number,\n currentCacheVersion: number,\n entry: MapEntry<V>\n) {\n // We have a matching entry, but before we can return it, we need to check if\n // it's still fresh. Otherwise it should be treated the same as a cache miss.\n\n if (entry.value === null) {\n // This entry has no value, so there's nothing to evict.\n return entry\n }\n\n const value = entry.value\n if (isValueExpired(now, currentCacheVersion, value)) {\n // The value expired. Lazily evict it from the cache, and return null. This\n // is conceptually the same as a cache miss.\n deleteMapEntry(entry)\n return null\n }\n\n // The matched entry has not expired. Return it.\n return entry\n}\n\nfunction getEntryWithFallbackImpl<V extends MapValue>(\n now: number,\n currentCacheVersion: number,\n entry: MapEntry<V>,\n keys: VaryPath | null,\n isRevalidation: boolean,\n previousKey: unknown | null\n): MapEntry<V> | null {\n // This is similar to getExactEntry, but if an exact match is not found for\n // a key, it will return the fallback entry instead. This is recursive at\n // every level, e.g. an entry with keypath [a, Fallback, c, Fallback] is\n // valid match for [a, b, c, d].\n //\n // It will return the most specific match available.\n let key\n let remainingKeys: VaryPath | null\n if (keys !== null) {\n key = keys.value\n remainingKeys = keys.parent\n } else if (isRevalidation && previousKey !== Revalidation) {\n // During a revalidation, we append an internal \"Revalidation\" key to\n // the end of the keypath.\n key = Revalidation\n remainingKeys = null\n } else {\n // There are no more keys. This is the terminal entry.\n\n // TODO: When performing a lookup during a navigation, as opposed to a\n // prefetch, we may want to skip entries that are Pending if there's also\n // a Fulfilled fallback entry. Tricky to say, though, since if it's\n // already pending, it's likely to stream in soon. Maybe we could do this\n // just on slow connections and offline mode.\n\n return lazilyEvictIfNeeded(now, currentCacheVersion, entry)\n }\n const map = entry.map\n if (map !== null) {\n const existingEntry = map.get(key)\n if (existingEntry !== undefined) {\n // Found an exact match for this key. Keep searching.\n const result = getEntryWithFallbackImpl(\n now,\n currentCacheVersion,\n existingEntry,\n remainingKeys,\n isRevalidation,\n key\n )\n if (result !== null) {\n return result\n }\n }\n // No match found for this key. Check if there's a fallback.\n const fallbackEntry = map.get(Fallback)\n if (fallbackEntry !== undefined) {\n // Found a fallback for this key. Keep searching.\n return getEntryWithFallbackImpl(\n now,\n currentCacheVersion,\n fallbackEntry,\n remainingKeys,\n isRevalidation,\n key\n )\n }\n }\n return null\n}\n\nexport function setInCacheMap<V extends MapValue>(\n cacheMap: CacheMap<V>,\n keys: VaryPath,\n value: V,\n isRevalidation: boolean\n): void {\n // Add a value to the map at the given keypath. If the value is already\n // part of the map, it's removed from its previous keypath. (NOTE: This is\n // unlike a regular JS map, but the behavior is intentional.)\n const entry = getOrInitialize(cacheMap, keys, isRevalidation)\n setMapEntryValue(entry, value)\n\n // This is an LRU access. Move the entry to the front of the list.\n lruPut(entry)\n updateLruSize(entry, value.size)\n}\n\nfunction setMapEntryValue(entry: UnknownMapEntry, value: MapValue): void {\n if (entry.value !== null) {\n // There's already a value at the given keypath. Disconnect the old value\n // from the map. We're not calling `deleteMapEntry` here because the\n // entry itself is still in the map. We just want to overwrite its value.\n dropRef(entry.value)\n entry.value = null\n }\n\n // This value may already be in the map at a different keypath.\n // Grab a reference before we overwrite it.\n const oldEntry = value.ref\n\n entry.value = value\n value.ref = entry\n\n updateLruSize(entry, value.size)\n\n if (oldEntry !== null && oldEntry !== entry && oldEntry.value === value) {\n // This value is already in the map at a different keypath in the map.\n // Values only exist at a single keypath at a time. Remove it from the\n // previous keypath.\n //\n // Note that only the internal map entry is garbage collected; we don't\n // call `dropRef` here because it's still in the map, just\n // at a new keypath (the one we just set, above).\n deleteMapEntry(oldEntry)\n }\n}\n\nexport function deleteFromCacheMap(value: MapValue): void {\n const entry = value.ref\n if (entry === null) {\n // This value is not a member of any map.\n return\n }\n\n dropRef(value)\n deleteMapEntry(entry)\n}\n\nfunction dropRef(value: MapValue): void {\n // Drop the value from the map by setting its `ref` backpointer to\n // null. This is a separate operation from `deleteMapEntry` because when\n // re-keying a value we need to be able to delete the old, internal map\n // entry without garbage collecting the value itself.\n value.ref = null\n}\n\nexport function deleteMapEntry(entry: UnknownMapEntry): void {\n // Delete the entry from the cache.\n entry.value = null\n\n deleteFromLru(entry)\n\n // Check if we can garbage collect the entry.\n const map = entry.map\n if (map === null) {\n // Since this entry has no value, and also no child entries, we can\n // garbage collect it. Remove it from its parent, and keep garbage\n // collecting the parents until we reach a non-empty entry.\n let parent = entry.parent\n let key = entry.key\n while (parent !== null) {\n const parentMap = parent.map\n if (parentMap !== null) {\n parentMap.delete(key)\n if (parentMap.size === 0) {\n // We just removed the last entry in the parent map.\n parent.map = null\n if (parent.value === null) {\n // The parent node has no child entries, nor does it have a value\n // on itself. It can be garbage collected. Keep going.\n key = parent.key\n parent = parent.parent\n continue\n }\n }\n }\n // The parent is not empty. Stop garbage collecting.\n break\n }\n } else {\n // Check if there's a revalidating entry. If so, promote it to a\n // \"normal\" entry, since the normal one was just deleted.\n const revalidatingEntry = map.get(Revalidation)\n if (revalidatingEntry !== undefined && revalidatingEntry.value !== null) {\n setMapEntryValue(entry, revalidatingEntry.value)\n }\n }\n}\n\nexport function setSizeInCacheMap<V extends MapValue>(\n value: V,\n size: number\n): void {\n const entry = value.ref\n if (entry === null) {\n // This value is not a member of any map.\n return\n }\n // Except during initialization (when the size is set to 0), this is the only\n // place the `size` field should be updated, to ensure it's in sync with the\n // the LRU.\n value.size = size\n updateLruSize(entry, size)\n}\n","import { FetchStrategy } from './types'\nimport type {\n NormalizedPathname,\n NormalizedSearch,\n NormalizedNextUrl,\n} from './cache-key'\nimport type { RouteTree } from './cache'\nimport { Fallback, type FallbackType } from './cache-map'\nimport { HEAD_REQUEST_KEY } from '../../../shared/lib/segment-cache/segment-value-encoding'\n\ntype Opaque<T, K> = T & { __brand: K }\n\n/**\n * A linked-list of all the params (or other param-like) inputs that a cache\n * entry may vary by. This is used by the CacheMap module to reuse cache entries\n * across different param values. If a param has a value of Fallback, it means\n * the cache entry is reusable for all possible values of that param. See\n * cache-map.ts for details.\n *\n * A segment's vary path is a pure function of a segment's position in a\n * particular route tree and the (post-rewrite) URL that is being queried. More\n * concretely, successive queries of the cache for the same segment always use\n * the same vary path.\n *\n * A route's vary path is simpler: it's comprised of the pathname, search\n * string, and Next-URL header.\n */\nexport type VaryPath = {\n value: string | null | FallbackType\n parent: VaryPath | null\n}\n\n// Because it's so important for vary paths to line up across cache accesses,\n// we use opaque type aliases to ensure these are only created within\n// this module.\n\n// requestKey -> searchParams -> nextUrl\nexport type RouteVaryPath = Opaque<\n {\n value: NormalizedPathname\n parent: {\n value: NormalizedSearch\n parent: {\n value: NormalizedNextUrl | null | FallbackType\n parent: null\n }\n }\n },\n 'RouteVaryPath'\n>\n\n// requestKey -> pathParams\nexport type LayoutVaryPath = Opaque<\n {\n value: string\n parent: PartialSegmentVaryPath | null\n },\n 'LayoutVaryPath'\n>\n\n// requestKey -> searchParams -> pathParams\nexport type PageVaryPath = Opaque<\n {\n value: string\n parent: {\n value: NormalizedSearch | FallbackType\n parent: PartialSegmentVaryPath | null\n }\n },\n 'PageVaryPath'\n>\n\nexport type SegmentVaryPath = LayoutVaryPath | PageVaryPath\n\n// Intermediate type used when building a vary path during a recursive traversal\n// of the route tree.\nexport type PartialSegmentVaryPath = Opaque<VaryPath, 'PartialSegmentVaryPath'>\n\nexport function getRouteVaryPath(\n pathname: NormalizedPathname,\n search: NormalizedSearch,\n nextUrl: NormalizedNextUrl | null\n): RouteVaryPath {\n // requestKey -> searchParams -> nextUrl\n const varyPath: VaryPath = {\n value: pathname,\n parent: {\n value: search,\n parent: {\n value: nextUrl,\n parent: null,\n },\n },\n }\n return varyPath as RouteVaryPath\n}\n\nexport function getFulfilledRouteVaryPath(\n pathname: NormalizedPathname,\n search: NormalizedSearch,\n nextUrl: NormalizedNextUrl | null,\n couldBeIntercepted: boolean\n): RouteVaryPath {\n // This is called when a route's data is fulfilled. The cache entry will be\n // re-keyed based on which inputs the response varies by.\n // requestKey -> searchParams -> nextUrl\n const varyPath: VaryPath = {\n value: pathname,\n parent: {\n value: search,\n parent: {\n value: couldBeIntercepted ? nextUrl : Fallback,\n parent: null,\n },\n },\n }\n return varyPath as RouteVaryPath\n}\n\nexport function appendLayoutVaryPath(\n parentPath: PartialSegmentVaryPath | null,\n cacheKey: string\n): PartialSegmentVaryPath {\n const varyPathPart: VaryPath = {\n value: cacheKey,\n parent: parentPath,\n }\n return varyPathPart as PartialSegmentVaryPath\n}\n\nexport function finalizeLayoutVaryPath(\n requestKey: string,\n varyPath: PartialSegmentVaryPath | null\n): LayoutVaryPath {\n const layoutVaryPath: VaryPath = {\n value: requestKey,\n parent: varyPath,\n }\n return layoutVaryPath as LayoutVaryPath\n}\n\nexport function finalizePageVaryPath(\n requestKey: string,\n renderedSearch: NormalizedSearch,\n varyPath: PartialSegmentVaryPath | null\n): PageVaryPath {\n // Unlike layouts, a page segment's vary path also includes the search string.\n // requestKey -> searchParams -> pathParams\n const pageVaryPath: VaryPath = {\n value: requestKey,\n parent: {\n value: renderedSearch,\n parent: varyPath,\n },\n }\n return pageVaryPath as PageVaryPath\n}\n\nexport function finalizeMetadataVaryPath(\n pageRequestKey: string,\n renderedSearch: NormalizedSearch,\n varyPath: PartialSegmentVaryPath | null\n): PageVaryPath {\n // The metadata \"segment\" is not a real segment because it doesn't exist in\n // the normal structure of the route tree, but in terms of caching, it\n // behaves like a page segment because it varies by all the same params as\n // a page.\n //\n // To keep the protocol for querying the server simple, the request key for\n // the metadata does not include any path information. It's unnecessary from\n // the server's perspective, because unlike page segments, there's only one\n // metadata response per URL, i.e. there's no need to distinguish multiple\n // parallel pages.\n //\n // However, this means the metadata request key is insufficient for\n // caching the the metadata in the client cache, because on the client we\n // use the request key to distinguish the metadata entry from all other\n // page's metadata entries.\n //\n // So instead we create a simulated request key based on the page segment.\n // Conceptually this is equivalent to the request key the server would have\n // assigned the metadata segment if it treated it as part of the actual\n // route structure.\n\n // If there are multiple parallel pages, we use whichever is the first one.\n // This is fine because the only difference between request keys for\n // different parallel pages are things like route groups and parallel\n // route slots. As long as it's always the same one, it doesn't matter.\n const pageVaryPath: VaryPath = {\n // Append the actual metadata request key to the page request key. Note\n // that we're not using a separate vary path part; it's unnecessary because\n // these are not conceptually separate inputs.\n value: pageRequestKey + HEAD_REQUEST_KEY,\n parent: {\n value: renderedSearch,\n parent: varyPath,\n },\n }\n return pageVaryPath as PageVaryPath\n}\n\nexport function getSegmentVaryPathForRequest(\n fetchStrategy: FetchStrategy,\n tree: RouteTree\n): SegmentVaryPath {\n // This is used for storing pending requests in the cache. We want to choose\n // the most generic vary path based on the strategy used to fetch it, i.e.\n // static/PPR versus runtime prefetching, so that it can be reused as much\n // as possible.\n //\n // We may be able to re-key the response to something even more generic once\n // we receive it — for example, if the server tells us that the response\n // doesn't vary on a particular param — but even before we send the request,\n // we know some params are reusable based on the fetch strategy alone. For\n // example, a static prefetch will never vary on search params.\n //\n // The original vary path with all the params filled in is stored on the\n // route tree object. We will clone this one to create a new vary path\n // where certain params are replaced with Fallback.\n //\n // This result of this function is not stored anywhere. It's only used to\n // access the cache a single time.\n //\n // TODO: Rather than create a new list object just to access the cache, the\n // plan is to add the concept of a \"vary mask\". This will represent all the\n // params that can be treated as Fallback. (Or perhaps the inverse.)\n const originalVaryPath = tree.varyPath\n\n // Only page segments (and the special \"metadata\" segment, which is treated\n // like a page segment for the purposes of caching) may contain search\n // params. There's no reason to include them in the vary path otherwise.\n if (tree.isPage) {\n // Only a runtime prefetch will include search params in the vary path.\n // Static prefetches never include search params, so they can be reused\n // across all possible search param values.\n const doesVaryOnSearchParams =\n fetchStrategy === FetchStrategy.Full ||\n fetchStrategy === FetchStrategy.PPRRuntime\n\n if (!doesVaryOnSearchParams) {\n // The response from the the server will not vary on search params. Clone\n // the end of the original vary path to replace the search params\n // with Fallback.\n //\n // requestKey -> searchParams -> pathParams\n // ^ This part gets replaced with Fallback\n const searchParamsVaryPath = (originalVaryPath as PageVaryPath).parent\n const pathParamsVaryPath = searchParamsVaryPath.parent\n const patchedVaryPath: VaryPath = {\n value: originalVaryPath.value,\n parent: {\n value: Fallback,\n parent: pathParamsVaryPath,\n },\n }\n return patchedVaryPath as SegmentVaryPath\n }\n }\n\n // The request does vary on search params. We don't need to modify anything.\n return originalVaryPath as SegmentVaryPath\n}\n\nexport function clonePageVaryPathWithNewSearchParams(\n originalVaryPath: PageVaryPath,\n newSearch: NormalizedSearch\n): PageVaryPath {\n // requestKey -> searchParams -> pathParams\n // ^ This part gets replaced with newSearch\n const searchParamsVaryPath = originalVaryPath.parent\n const clonedVaryPath: VaryPath = {\n value: originalVaryPath.value,\n parent: {\n value: newSearch,\n parent: searchParamsVaryPath.parent,\n },\n }\n return clonedVaryPath as PageVaryPath\n}\n","/**\n * For a given page path, this function ensures that there is a leading slash.\n * If there is not a leading slash, one is added, otherwise it is noop.\n */\nexport function ensureLeadingSlash(path: string) {\n return path.startsWith('/') ? path : `/${path}`\n}\n","import { ensureLeadingSlash } from '../../page-path/ensure-leading-slash'\nimport { isGroupSegment } from '../../segment'\n\n/**\n * Normalizes an app route so it represents the actual request path. Essentially\n * performing the following transformations:\n *\n * - `/(dashboard)/user/[id]/page` to `/user/[id]`\n * - `/(dashboard)/account/page` to `/account`\n * - `/user/[id]/page` to `/user/[id]`\n * - `/account/page` to `/account`\n * - `/page` to `/`\n * - `/(dashboard)/user/[id]/route` to `/user/[id]`\n * - `/(dashboard)/account/route` to `/account`\n * - `/user/[id]/route` to `/user/[id]`\n * - `/account/route` to `/account`\n * - `/route` to `/`\n * - `/` to `/`\n *\n * @param route the app route to normalize\n * @returns the normalized pathname\n */\nexport function normalizeAppPath(route: string) {\n return ensureLeadingSlash(\n route.split('/').reduce((pathname, segment, index, segments) => {\n // Empty segments are ignored.\n if (!segment) {\n return pathname\n }\n\n // Groups are ignored.\n if (isGroupSegment(segment)) {\n return pathname\n }\n\n // Parallel segments are ignored.\n if (segment[0] === '@') {\n return pathname\n }\n\n // The last segment (if it's a leaf) should be ignored.\n if (\n (segment === 'page' || segment === 'route') &&\n index === segments.length - 1\n ) {\n return pathname\n }\n\n return `${pathname}/${segment}`\n }, '')\n )\n}\n\n/**\n * Strips the `.rsc` extension if it's in the pathname.\n * Since this function is used on full urls it checks `?` for searchParams handling.\n */\nexport function normalizeRscURL(url: string) {\n return url.replace(\n /\\.rsc($|\\?)/,\n // $1 ensures `?` is preserved\n '$1'\n )\n}\n","import { normalizeAppPath } from './app-paths'\n\n// order matters here, the first match will be used\nexport const INTERCEPTION_ROUTE_MARKERS = [\n '(..)(..)',\n '(.)',\n '(..)',\n '(...)',\n] as const\n\nexport type InterceptionMarker = (typeof INTERCEPTION_ROUTE_MARKERS)[number]\n\nexport function isInterceptionRouteAppPath(path: string): boolean {\n // TODO-APP: add more serious validation\n return (\n path\n .split('/')\n .find((segment) =>\n INTERCEPTION_ROUTE_MARKERS.find((m) => segment.startsWith(m))\n ) !== undefined\n )\n}\n\ntype InterceptionRouteInformation = {\n /**\n * The intercepting route. This is the route that is being intercepted or the\n * route that the user was coming from. This is matched by the Next-Url\n * header.\n */\n interceptingRoute: string\n\n /**\n * The intercepted route. This is the route that is being intercepted or the\n * route that the user is going to. This is matched by the request pathname.\n */\n interceptedRoute: string\n}\n\nexport function extractInterceptionRouteInformation(\n path: string\n): InterceptionRouteInformation {\n let interceptingRoute: string | undefined\n let marker: (typeof INTERCEPTION_ROUTE_MARKERS)[number] | undefined\n let interceptedRoute: string | undefined\n\n for (const segment of path.split('/')) {\n marker = INTERCEPTION_ROUTE_MARKERS.find((m) => segment.startsWith(m))\n if (marker) {\n ;[interceptingRoute, interceptedRoute] = path.split(marker, 2)\n break\n }\n }\n\n if (!interceptingRoute || !marker || !interceptedRoute) {\n throw new Error(\n `Invalid interception route: ${path}. Must be in the format /<intercepting route>/(..|...|..)(..)/<intercepted route>`\n )\n }\n\n interceptingRoute = normalizeAppPath(interceptingRoute) // normalize the path, e.g. /(blog)/feed -> /feed\n\n switch (marker) {\n case '(.)':\n // (.) indicates that we should match with sibling routes, so we just need to append the intercepted route to the intercepting route\n if (interceptingRoute === '/') {\n interceptedRoute = `/${interceptedRoute}`\n } else {\n interceptedRoute = interceptingRoute + '/' + interceptedRoute\n }\n break\n case '(..)':\n // (..) indicates that we should match at one level up, so we need to remove the last segment of the intercepting route\n if (interceptingRoute === '/') {\n throw new Error(\n `Invalid interception route: ${path}. Cannot use (..) marker at the root level, use (.) instead.`\n )\n }\n interceptedRoute = interceptingRoute\n .split('/')\n .slice(0, -1)\n .concat(interceptedRoute)\n .join('/')\n break\n case '(...)':\n // (...) will match the route segment in the root directory, so we need to use the root directory to prepend the intercepted route\n interceptedRoute = '/' + interceptedRoute\n break\n case '(..)(..)':\n // (..)(..) indicates that we should match at two levels up, so we need to remove the last two segments of the intercepting route\n\n const splitInterceptingRoute = interceptingRoute.split('/')\n if (splitInterceptingRoute.length <= 2) {\n throw new Error(\n `Invalid interception route: ${path}. Cannot use (..)(..) marker at the root level or one level up.`\n )\n }\n\n interceptedRoute = splitInterceptingRoute\n .slice(0, -2)\n .concat(interceptedRoute)\n .join('/')\n break\n default:\n throw new Error('Invariant: unexpected marker')\n }\n\n return { interceptingRoute, interceptedRoute }\n}\n","import type {\n FlightRouterState,\n Segment,\n} from '../../../shared/lib/app-router-types'\nimport { INTERCEPTION_ROUTE_MARKERS } from '../../../shared/lib/router/utils/interception-routes'\nimport type { Params } from '../../../server/request/params'\nimport {\n isGroupSegment,\n DEFAULT_SEGMENT_KEY,\n PAGE_SEGMENT_KEY,\n} from '../../../shared/lib/segment'\nimport { matchSegment } from '../match-segments'\n\nconst removeLeadingSlash = (segment: string): string => {\n return segment[0] === '/' ? segment.slice(1) : segment\n}\n\nconst segmentToPathname = (segment: Segment): string => {\n if (typeof segment === 'string') {\n // 'children' is not a valid path -- it's technically a parallel route that corresponds with the current segment's page\n // if we don't skip it, then the computed pathname might be something like `/children` which doesn't make sense.\n if (segment === 'children') return ''\n\n return segment\n }\n\n return segment[1]\n}\n\nfunction normalizeSegments(segments: string[]): string {\n return (\n segments.reduce((acc, segment) => {\n segment = removeLeadingSlash(segment)\n if (segment === '' || isGroupSegment(segment)) {\n return acc\n }\n\n return `${acc}/${segment}`\n }, '') || '/'\n )\n}\n\nexport function extractPathFromFlightRouterState(\n flightRouterState: FlightRouterState\n): string | undefined {\n const segment = Array.isArray(flightRouterState[0])\n ? flightRouterState[0][1]\n : flightRouterState[0]\n\n if (\n segment === DEFAULT_SEGMENT_KEY ||\n INTERCEPTION_ROUTE_MARKERS.some((m) => segment.startsWith(m))\n )\n return undefined\n\n if (segment.startsWith(PAGE_SEGMENT_KEY)) return ''\n\n const segments = [segmentToPathname(segment)]\n const parallelRoutes = flightRouterState[1] ?? {}\n\n const childrenPath = parallelRoutes.children\n ? extractPathFromFlightRouterState(parallelRoutes.children)\n : undefined\n\n if (childrenPath !== undefined) {\n segments.push(childrenPath)\n } else {\n for (const [key, value] of Object.entries(parallelRoutes)) {\n if (key === 'children') continue\n\n const childPath = extractPathFromFlightRouterState(value)\n\n if (childPath !== undefined) {\n segments.push(childPath)\n }\n }\n }\n\n return normalizeSegments(segments)\n}\n\nfunction computeChangedPathImpl(\n treeA: FlightRouterState,\n treeB: FlightRouterState\n): string | null {\n const [segmentA, parallelRoutesA] = treeA\n const [segmentB, parallelRoutesB] = treeB\n\n const normalizedSegmentA = segmentToPathname(segmentA)\n const normalizedSegmentB = segmentToPathname(segmentB)\n\n if (\n INTERCEPTION_ROUTE_MARKERS.some(\n (m) =>\n normalizedSegmentA.startsWith(m) || normalizedSegmentB.startsWith(m)\n )\n ) {\n return ''\n }\n\n if (!matchSegment(segmentA, segmentB)) {\n // once we find where the tree changed, we compute the rest of the path by traversing the tree\n return extractPathFromFlightRouterState(treeB) ?? ''\n }\n\n for (const parallelRouterKey in parallelRoutesA) {\n if (parallelRoutesB[parallelRouterKey]) {\n const changedPath = computeChangedPathImpl(\n parallelRoutesA[parallelRouterKey],\n parallelRoutesB[parallelRouterKey]\n )\n if (changedPath !== null) {\n return `${segmentToPathname(segmentB)}/${changedPath}`\n }\n }\n }\n\n return null\n}\n\nexport function computeChangedPath(\n treeA: FlightRouterState,\n treeB: FlightRouterState\n): string | null {\n const changedPath = computeChangedPathImpl(treeA, treeB)\n\n if (changedPath == null || changedPath === '/') {\n return changedPath\n }\n\n // lightweight normalization to remove route groups\n return normalizeSegments(changedPath.split('/'))\n}\n\n/**\n * Recursively extracts dynamic parameters from FlightRouterState.\n */\nexport function getSelectedParams(\n currentTree: FlightRouterState,\n params: Params = {}\n): Params {\n const parallelRoutes = currentTree[1]\n\n for (const parallelRoute of Object.values(parallelRoutes)) {\n const segment = parallelRoute[0]\n const isDynamicParameter = Array.isArray(segment)\n const segmentValue = isDynamicParameter ? segment[1] : segment\n if (!segmentValue || segmentValue.startsWith(PAGE_SEGMENT_KEY)) continue\n\n // Ensure catchAll and optional catchall are turned into an array\n const isCatchAll =\n isDynamicParameter && (segment[2] === 'c' || segment[2] === 'oc')\n\n if (isCatchAll) {\n params[segment[0]] = segment[1].split('/')\n } else if (isDynamicParameter) {\n params[segment[0]] = segment[1]\n }\n\n params = getSelectedParams(parallelRoute, params)\n }\n\n return params\n}\n","import { computeChangedPath } from './compute-changed-path'\nimport type {\n Mutable,\n ReadonlyReducerState,\n ReducerState,\n} from './router-reducer-types'\n\nfunction isNotUndefined<T>(value: T): value is Exclude<T, undefined> {\n return typeof value !== 'undefined'\n}\n\nexport function handleMutable(\n state: ReadonlyReducerState,\n mutable: Mutable\n): ReducerState {\n // shouldScroll is true by default, can override to false.\n const shouldScroll = mutable.shouldScroll ?? true\n\n let previousNextUrl = state.previousNextUrl\n let nextUrl = state.nextUrl\n\n if (isNotUndefined(mutable.patchedTree)) {\n // If we received a patched tree, we need to compute the changed path.\n const changedPath = computeChangedPath(state.tree, mutable.patchedTree)\n if (changedPath) {\n // If the tree changed, we need to update the nextUrl\n previousNextUrl = nextUrl\n nextUrl = changedPath\n } else if (!nextUrl) {\n // if the tree ends up being the same (ie, no changed path), and we don't have a nextUrl, then we should use the canonicalUrl\n nextUrl = state.canonicalUrl\n }\n // otherwise this will be a no-op and continue to use the existing nextUrl\n }\n\n return {\n // Set href.\n canonicalUrl: mutable.canonicalUrl ?? state.canonicalUrl,\n renderedSearch: mutable.renderedSearch ?? state.renderedSearch,\n pushRef: {\n pendingPush: isNotUndefined(mutable.pendingPush)\n ? mutable.pendingPush\n : state.pushRef.pendingPush,\n mpaNavigation: isNotUndefined(mutable.mpaNavigation)\n ? mutable.mpaNavigation\n : state.pushRef.mpaNavigation,\n preserveCustomHistoryState: isNotUndefined(\n mutable.preserveCustomHistoryState\n )\n ? mutable.preserveCustomHistoryState\n : state.pushRef.preserveCustomHistoryState,\n },\n // All navigation requires scroll and focus management to trigger.\n focusAndScrollRef: {\n apply: shouldScroll\n ? isNotUndefined(mutable?.scrollableSegments)\n ? true\n : state.focusAndScrollRef.apply\n : // If shouldScroll is false then we should not apply scroll and focus management.\n false,\n onlyHashChange: mutable.onlyHashChange || false,\n hashFragment: shouldScroll\n ? // Empty hash should trigger default behavior of scrolling layout into view.\n // #top is handled in layout-router.\n mutable.hashFragment && mutable.hashFragment !== ''\n ? // Remove leading # and decode hash to make non-latin hashes work.\n decodeURIComponent(mutable.hashFragment.slice(1))\n : state.focusAndScrollRef.hashFragment\n : // If shouldScroll is false then we should not apply scroll and focus management.\n null,\n segmentPaths: shouldScroll\n ? (mutable?.scrollableSegments ?? state.focusAndScrollRef.segmentPaths)\n : // If shouldScroll is false then we should not apply scroll and focus management.\n [],\n },\n // Apply cache.\n cache: mutable.cache ? mutable.cache : state.cache,\n // Apply patched router state.\n tree: isNotUndefined(mutable.patchedTree)\n ? mutable.patchedTree\n : state.tree,\n nextUrl,\n previousNextUrl: previousNextUrl,\n debugInfo: mutable.collectedDebugInfo ?? null,\n }\n}\n","import type { Segment } from '../../../shared/lib/app-router-types'\nimport { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'\n\nexport function createRouterCacheKey(\n segment: Segment,\n withoutSearchParameters: boolean = false\n) {\n // if the segment is an array, it means it's a dynamic segment\n // for example, ['lang', 'en', 'd']. We need to convert it to a string to store it as a cache node key.\n if (Array.isArray(segment)) {\n return `${segment[0]}|${segment[1]}|${segment[2]}`\n }\n\n // Page segments might have search parameters, ie __PAGE__?foo=bar\n // When `withoutSearchParameters` is true, we only want to return the page segment\n if (withoutSearchParameters && segment.startsWith(PAGE_SEGMENT_KEY)) {\n return PAGE_SEGMENT_KEY\n }\n\n return segment\n}\n","import type { FlightRouterState } from '../../../shared/lib/app-router-types'\n\nexport function isNavigatingToNewRootLayout(\n currentTree: FlightRouterState,\n nextTree: FlightRouterState\n): boolean {\n // Compare segments\n const currentTreeSegment = currentTree[0]\n const nextTreeSegment = nextTree[0]\n\n // If any segment is different before we find the root layout, the root layout has changed.\n // E.g. /same/(group1)/layout.js -> /same/(group2)/layout.js\n // First segment is 'same' for both, keep looking. (group1) changed to (group2) before the root layout was found, it must have changed.\n if (Array.isArray(currentTreeSegment) && Array.isArray(nextTreeSegment)) {\n // Compare dynamic param name and type but ignore the value, different values would not affect the current root layout\n // /[name] - /slug1 and /slug2, both values (slug1 & slug2) still has the same layout /[name]/layout.js\n if (\n currentTreeSegment[0] !== nextTreeSegment[0] ||\n currentTreeSegment[2] !== nextTreeSegment[2]\n ) {\n return true\n }\n } else if (currentTreeSegment !== nextTreeSegment) {\n return true\n }\n\n // Current tree root layout found\n if (currentTree[4]) {\n // If the next tree doesn't have the root layout flag, it must have changed.\n return !nextTree[4]\n }\n // Current tree didn't have its root layout here, must have changed.\n if (nextTree[4]) {\n return true\n }\n // We can't assume it's `parallelRoutes.children` here in case the root layout is `app/@something/layout.js`\n // But it's not possible to be more than one parallelRoutes before the root layout is found\n // TODO-APP: change to traverse all parallel routes\n const currentTreeChild = Object.values(currentTree[1])[0]\n const nextTreeChild = Object.values(nextTree[1])[0]\n if (!currentTreeChild || !nextTreeChild) return true\n return isNavigatingToNewRootLayout(currentTreeChild, nextTreeChild)\n}\n","import type {\n CacheNodeSeedData,\n FlightRouterState,\n FlightSegmentPath,\n} from '../../../shared/lib/app-router-types'\nimport type {\n ChildSegmentMap,\n CacheNode,\n} from '../../../shared/lib/app-router-types'\nimport type {\n HeadData,\n LoadingModuleData,\n} from '../../../shared/lib/app-router-types'\nimport {\n DEFAULT_SEGMENT_KEY,\n NOT_FOUND_SEGMENT_KEY,\n} from '../../../shared/lib/segment'\nimport { matchSegment } from '../match-segments'\nimport { createHrefFromUrl } from './create-href-from-url'\nimport { createRouterCacheKey } from './create-router-cache-key'\nimport { fetchServerResponse } from './fetch-server-response'\nimport { dispatchAppRouterAction } from '../use-action-queue'\nimport {\n ACTION_SERVER_PATCH,\n type ServerPatchAction,\n} from './router-reducer-types'\nimport { isNavigatingToNewRootLayout } from './is-navigating-to-new-root-layout'\nimport { DYNAMIC_STALETIME_MS } from './reducers/navigate-reducer'\nimport {\n convertServerPatchToFullTree,\n type NavigationSeed,\n} from '../segment-cache/navigation'\n\n// This is yet another tree type that is used to track pending promises that\n// need to be fulfilled once the dynamic data is received. The terminal nodes of\n// this tree represent the new Cache Node trees that were created during this\n// request. We can't use the Cache Node tree or Route State tree directly\n// because those include reused nodes, too. This tree is discarded as soon as\n// the navigation response is received.\nexport type NavigationTask = {\n status: NavigationTaskStatus\n // The router state that corresponds to the tree that this Task represents.\n route: FlightRouterState\n // The CacheNode that corresponds to the tree that this Task represents.\n node: CacheNode\n // The tree sent to the server during the dynamic request. If all the segments\n // are static, then this will be null, and no server request is required.\n // Otherwise, this is the same as `route`, except with the `refetch` marker\n // set on the top-most segment that needs to be fetched.\n dynamicRequestTree: FlightRouterState | null\n // The URL that should be used to fetch the dynamic data. This is only set\n // when the segment cannot be refetched from the current route, because it's\n // part of a \"default\" parallel slot that was reused during a navigation.\n refreshUrl: string | null\n children: Map<string, NavigationTask> | null\n}\n\nexport const enum FreshnessPolicy {\n Default,\n Hydration,\n HistoryTraversal,\n RefreshAll,\n HMRRefresh,\n}\n\nconst enum NavigationTaskStatus {\n Pending,\n Fulfilled,\n Rejected,\n}\n\n/**\n * When a NavigationTask finishes, there may or may not be data still missing,\n * necessitating a retry.\n */\nconst enum NavigationTaskExitStatus {\n /**\n * No additional navigation is required.\n */\n Done = 0,\n /**\n * Some data failed to load, presumably due to a route tree mismatch. Perform\n * a soft retry to reload the entire tree.\n */\n SoftRetry = 1,\n /**\n * Some data failed to load in an unrecoverable way, e.g. in an inactive\n * parallel route. Fall back to a hard (MPA-style) retry.\n */\n HardRetry = 2,\n}\n\nexport type NavigationRequestAccumulation = {\n scrollableSegments: Array<FlightSegmentPath> | null\n separateRefreshUrls: Set<string> | null\n}\n\nconst noop = () => {}\n\nexport function createInitialCacheNodeForHydration(\n navigatedAt: number,\n initialTree: FlightRouterState,\n seedData: CacheNodeSeedData | null,\n seedHead: HeadData\n): CacheNode {\n // Create the initial cache node tree, using the data embedded into the\n // HTML document.\n const accumulation: NavigationRequestAccumulation = {\n scrollableSegments: null,\n separateRefreshUrls: null,\n }\n const task = createCacheNodeOnNavigation(\n navigatedAt,\n initialTree,\n undefined,\n FreshnessPolicy.Hydration,\n seedData,\n seedHead,\n null,\n null,\n false,\n null,\n null,\n false,\n accumulation\n )\n\n // NOTE: We intentionally don't check if any data needs to be fetched from the\n // server. We assume the initial hydration payload is sufficient to render\n // the page.\n //\n // The completeness of the initial data is an important property that we rely\n // on as a last-ditch mechanism for recovering the app; we must always be able\n // to reload a fresh HTML document to get to a consistent state.\n //\n // In the future, there may be cases where the server intentionally sends\n // partial data and expects the client to fill in the rest, in which case this\n // logic may change. (There already is a similar case where the server sends\n // _no_ hydration data in the HTML document at all, and the client fetches it\n // separately, but that's different because we still end up hydrating with a\n // complete tree.)\n\n return task.node\n}\n\n// Creates a new Cache Node tree (i.e. copy-on-write) that represents the\n// optimistic result of a navigation, using both the current Cache Node tree and\n// data that was prefetched prior to navigation.\n//\n// At the moment we call this function, we haven't yet received the navigation\n// response from the server. It could send back something completely different\n// from the tree that was prefetched — due to rewrites, default routes, parallel\n// routes, etc.\n//\n// But in most cases, it will return the same tree that we prefetched, just with\n// the dynamic holes filled in. So we optimistically assume this will happen,\n// and accept that the real result could be arbitrarily different.\n//\n// We'll reuse anything that was already in the previous tree, since that's what\n// the server does.\n//\n// New segments (ones that don't appear in the old tree) are assigned an\n// unresolved promise. The data for these promises will be fulfilled later, when\n// the navigation response is received.\n//\n// The tree can be rendered immediately after it is created (that's why this is\n// a synchronous function). Any new trees that do not have prefetch data will\n// suspend during rendering, until the dynamic data streams in.\n//\n// Returns a Task object, which contains both the updated Cache Node and a path\n// to the pending subtrees that need to be resolved by the navigation response.\n//\n// A return value of `null` means there were no changes, and the previous tree\n// can be reused without initiating a server request.\nexport function startPPRNavigation(\n navigatedAt: number,\n oldUrl: URL,\n oldCacheNode: CacheNode | null,\n oldRouterState: FlightRouterState,\n newRouterState: FlightRouterState,\n freshness: FreshnessPolicy,\n seedData: CacheNodeSeedData | null,\n seedHead: HeadData | null,\n prefetchData: CacheNodeSeedData | null,\n prefetchHead: HeadData | null,\n isPrefetchHeadPartial: boolean,\n isSamePageNavigation: boolean,\n accumulation: NavigationRequestAccumulation\n): NavigationTask | null {\n const didFindRootLayout = false\n const parentNeedsDynamicRequest = false\n const parentRefreshUrl = null\n return updateCacheNodeOnNavigation(\n navigatedAt,\n oldUrl,\n oldCacheNode !== null ? oldCacheNode : undefined,\n oldRouterState,\n newRouterState,\n freshness,\n didFindRootLayout,\n seedData,\n seedHead,\n prefetchData,\n prefetchHead,\n isPrefetchHeadPartial,\n isSamePageNavigation,\n null,\n null,\n parentNeedsDynamicRequest,\n parentRefreshUrl,\n accumulation\n )\n}\n\nfunction updateCacheNodeOnNavigation(\n navigatedAt: number,\n oldUrl: URL,\n oldCacheNode: CacheNode | void,\n oldRouterState: FlightRouterState,\n newRouterState: FlightRouterState,\n freshness: FreshnessPolicy,\n didFindRootLayout: boolean,\n seedData: CacheNodeSeedData | null,\n seedHead: HeadData | null,\n prefetchData: CacheNodeSeedData | null,\n prefetchHead: HeadData | null,\n isPrefetchHeadPartial: boolean,\n isSamePageNavigation: boolean,\n parentSegmentPath: FlightSegmentPath | null,\n parentParallelRouteKey: string | null,\n parentNeedsDynamicRequest: boolean,\n parentRefreshUrl: string | null,\n accumulation: NavigationRequestAccumulation\n): NavigationTask | null {\n // Check if this segment matches the one in the previous route.\n const oldSegment = oldRouterState[0]\n const newSegment = newRouterState[0]\n if (!matchSegment(newSegment, oldSegment)) {\n // This segment does not match the previous route. We're now entering the\n // new part of the target route. Switch to the \"create\" path.\n if (\n // Check if the route tree changed before we reached a layout. (The\n // highest-level layout in a route tree is referred to as the \"root\"\n // layout.) This could mean that we're navigating between two different\n // root layouts. When this happens, we perform a full-page (MPA-style)\n // navigation.\n //\n // However, the algorithm for deciding where to start rendering a route\n // (i.e. the one performed in order to reach this function) is stricter\n // than the one used to detect a change in the root layout. So just\n // because we're re-rendering a segment outside of the root layout does\n // not mean we should trigger a full-page navigation.\n //\n // Specifically, we handle dynamic parameters differently: two segments\n // are considered the same even if their parameter values are different.\n //\n // Refer to isNavigatingToNewRootLayout for details.\n //\n // Note that we only have to perform this extra traversal if we didn't\n // already discover a root layout in the part of the tree that is\n // unchanged. We also only need to compare the subtree that is not\n // shared. In the common case, this branch is skipped completely.\n (!didFindRootLayout &&\n isNavigatingToNewRootLayout(oldRouterState, newRouterState)) ||\n // The global Not Found route (app/global-not-found.tsx) is a special\n // case, because it acts like a root layout, but in the router tree, it\n // is rendered in the same position as app/layout.tsx.\n //\n // Any navigation to the global Not Found route should trigger a\n // full-page navigation.\n //\n // TODO: We should probably model this by changing the key of the root\n // segment when this happens. Then the root layout check would work\n // as expected, without a special case.\n newSegment === NOT_FOUND_SEGMENT_KEY\n ) {\n return null\n }\n if (parentSegmentPath === null || parentParallelRouteKey === null) {\n // The root should never mismatch. If it does, it suggests an internal\n // Next.js error, or a malformed server response. Trigger a full-\n // page navigation.\n return null\n }\n return createCacheNodeOnNavigation(\n navigatedAt,\n newRouterState,\n oldCacheNode,\n freshness,\n seedData,\n seedHead,\n prefetchData,\n prefetchHead,\n isPrefetchHeadPartial,\n parentSegmentPath,\n parentParallelRouteKey,\n parentNeedsDynamicRequest,\n accumulation\n )\n }\n\n // TODO: The segment paths are tracked so that LayoutRouter knows which\n // segments to scroll to after a navigation. But we should just mark this\n // information on the CacheNode directly. It used to be necessary to do this\n // separately because CacheNodes were created lazily during render, not when\n // rather than when creating the route tree.\n const segmentPath =\n parentParallelRouteKey !== null && parentSegmentPath !== null\n ? parentSegmentPath.concat([parentParallelRouteKey, newSegment])\n : // NOTE: The root segment is intentionally omitted from the segment path\n []\n\n const newRouterStateChildren = newRouterState[1]\n const oldRouterStateChildren = oldRouterState[1]\n const seedDataChildren = seedData !== null ? seedData[1] : null\n const prefetchDataChildren = prefetchData !== null ? prefetchData[1] : null\n\n // We're currently traversing the part of the tree that was also part of\n // the previous route. If we discover a root layout, then we don't need to\n // trigger an MPA navigation.\n const isRootLayout = newRouterState[4] === true\n const childDidFindRootLayout = didFindRootLayout || isRootLayout\n\n const oldParallelRoutes =\n oldCacheNode !== undefined ? oldCacheNode.parallelRoutes : undefined\n\n // Clone the current set of segment children, even if they aren't active in\n // the new tree.\n // TODO: We currently retain all the inactive segments indefinitely, until\n // there's an explicit refresh, or a parent layout is lazily refreshed. We\n // rely on this for popstate navigations, which update the Router State Tree\n // but do not eagerly perform a data fetch, because they expect the segment\n // data to already be in the Cache Node tree. For highly static sites that\n // are mostly read-only, this may happen only rarely, causing memory to\n // leak. We should figure out a better model for the lifetime of inactive\n // segments, so we can maintain instant back/forward navigations without\n // leaking memory indefinitely.\n let shouldDropSiblingCaches: boolean = false\n let shouldRefreshDynamicData: boolean = false\n switch (freshness) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.HistoryTraversal:\n case FreshnessPolicy.Hydration: // <- shouldn't happen during client nav\n // We should never drop dynamic data in shared layouts, except during\n // a refresh.\n shouldDropSiblingCaches = false\n shouldRefreshDynamicData = false\n break\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n shouldDropSiblingCaches = true\n shouldRefreshDynamicData = true\n break\n default:\n freshness satisfies never\n break\n }\n const newParallelRoutes = new Map(\n shouldDropSiblingCaches ? undefined : oldParallelRoutes\n )\n\n // TODO: We're not consistent about how we do this check. Some places\n // check if the segment starts with PAGE_SEGMENT_KEY, but most seem to\n // check if there any any children, which is why I'm doing it here. We\n // should probably encode an empty children set as `null` though. Either\n // way, we should update all the checks to be consistent.\n const isLeafSegment = Object.keys(newRouterStateChildren).length === 0\n\n // Get the data for this segment. Since it was part of the previous route,\n // usually we just clone the data from the old CacheNode. However, during a\n // refresh or a revalidation, there won't be any existing CacheNode. So we\n // may need to consult the prefetch cache, like we would for a new segment.\n let newCacheNode: CacheNode\n let needsDynamicRequest: boolean\n if (\n oldCacheNode !== undefined &&\n !shouldRefreshDynamicData &&\n // During a same-page navigation, we always refetch the page segments\n !(isLeafSegment && isSamePageNavigation)\n ) {\n // Reuse the existing CacheNode\n const dropPrefetchRsc = false\n newCacheNode = reuseDynamicCacheNode(\n dropPrefetchRsc,\n oldCacheNode,\n newParallelRoutes\n )\n needsDynamicRequest = false\n } else if (seedData !== null && seedData[0] !== null) {\n // If this navigation was the result of an action, then check if the\n // server sent back data in the action response. We should favor using\n // that, rather than performing a separate request. This is both better\n // for performance and it's more likely to be consistent with any\n // writes that were just performed by the action, compared to a\n // separate request.\n const seedRsc = seedData[0]\n const seedLoading = seedData[2]\n const isSeedRscPartial = false\n const isSeedHeadPartial = seedHead === null\n newCacheNode = readCacheNodeFromSeedData(\n seedRsc,\n seedLoading,\n isSeedRscPartial,\n seedHead,\n isSeedHeadPartial,\n isLeafSegment,\n newParallelRoutes,\n navigatedAt\n )\n needsDynamicRequest = isLeafSegment && isSeedHeadPartial\n } else if (prefetchData !== null) {\n // Consult the prefetch cache.\n const prefetchRsc = prefetchData[0]\n const prefetchLoading = prefetchData[2]\n const isPrefetchRSCPartial = prefetchData[3]\n newCacheNode = readCacheNodeFromSeedData(\n prefetchRsc,\n prefetchLoading,\n isPrefetchRSCPartial,\n prefetchHead,\n isPrefetchHeadPartial,\n isLeafSegment,\n newParallelRoutes,\n navigatedAt\n )\n needsDynamicRequest =\n isPrefetchRSCPartial || (isLeafSegment && isPrefetchHeadPartial)\n } else {\n // Spawn a request to fetch new data from the server.\n newCacheNode = spawnNewCacheNode(\n newParallelRoutes,\n isLeafSegment,\n navigatedAt,\n freshness\n )\n needsDynamicRequest = true\n }\n\n // During a refresh navigation, there's a special case that happens when\n // entering a \"default\" slot. The default slot may not be part of the\n // current route; it may have been reused from an older route. If so,\n // we need to fetch its data from the old route's URL rather than current\n // route's URL. Keep track of this as we traverse the tree.\n const href = newRouterState[2]\n const refreshUrl =\n typeof href === 'string' && newRouterState[3] === 'refresh'\n ? // This segment is not present in the current route. Track its\n // refresh URL as we continue traversing the tree.\n href\n : // Inherit the refresh URL from the parent.\n parentRefreshUrl\n\n // If this segment itself needs to fetch new data from the server, then by\n // definition it is being refreshed. Track its refresh URL so we know which\n // URL to request the data from.\n if (needsDynamicRequest && refreshUrl !== null) {\n accumulateRefreshUrl(accumulation, refreshUrl)\n }\n\n // As we diff the trees, we may sometimes modify (copy-on-write, not mutate)\n // the Route Tree that was returned by the server — for example, in the case\n // of default parallel routes, we preserve the currently active segment. To\n // avoid mutating the original tree, we clone the router state children along\n // the return path.\n let patchedRouterStateChildren: {\n [parallelRouteKey: string]: FlightRouterState\n } = {}\n let taskChildren = null\n\n // Most navigations require a request to fetch additional data from the\n // server, either because the data was not already prefetched, or because the\n // target route contains dynamic data that cannot be prefetched.\n //\n // However, if the target route is fully static, and it's already completely\n // loaded into the segment cache, then we can skip the server request.\n //\n // This starts off as `false`, and is set to `true` if any of the child\n // routes requires a dynamic request.\n let childNeedsDynamicRequest = false\n // As we traverse the children, we'll construct a FlightRouterState that can\n // be sent to the server to request the dynamic data. If it turns out that\n // nothing in the subtree is dynamic (i.e. childNeedsDynamicRequest is false\n // at the end), then this will be discarded.\n // TODO: We can probably optimize the format of this data structure to only\n // include paths that are dynamic. Instead of reusing the\n // FlightRouterState type.\n let dynamicRequestTreeChildren: {\n [parallelRouteKey: string]: FlightRouterState\n } = {}\n\n for (let parallelRouteKey in newRouterStateChildren) {\n let newRouterStateChild: FlightRouterState =\n newRouterStateChildren[parallelRouteKey]\n const oldRouterStateChild: FlightRouterState | void =\n oldRouterStateChildren[parallelRouteKey]\n if (oldRouterStateChild === undefined) {\n // This should never happen, but if it does, it suggests a malformed\n // server response. Trigger a full-page navigation.\n return null\n }\n const oldSegmentMapChild =\n oldParallelRoutes !== undefined\n ? oldParallelRoutes.get(parallelRouteKey)\n : undefined\n\n let seedDataChild: CacheNodeSeedData | void | null =\n seedDataChildren !== null ? seedDataChildren[parallelRouteKey] : null\n let prefetchDataChild: CacheNodeSeedData | void | null =\n prefetchDataChildren !== null\n ? prefetchDataChildren[parallelRouteKey]\n : null\n\n let newSegmentChild = newRouterStateChild[0]\n let seedHeadChild = seedHead\n let prefetchHeadChild = prefetchHead\n let isPrefetchHeadPartialChild = isPrefetchHeadPartial\n if (\n // Skip this branch during a history traversal. We restore the tree that\n // was stashed in the history entry as-is.\n freshness !== FreshnessPolicy.HistoryTraversal &&\n newSegmentChild === DEFAULT_SEGMENT_KEY\n ) {\n // This is a \"default\" segment. These are never sent by the server during\n // a soft navigation; instead, the client reuses whatever segment was\n // already active in that slot on the previous route.\n newRouterStateChild = reuseActiveSegmentInDefaultSlot(\n oldUrl,\n oldRouterStateChild\n )\n newSegmentChild = newRouterStateChild[0]\n\n // Since we're switching to a different route tree, these are no\n // longer valid, because they correspond to the outer tree.\n seedDataChild = null\n seedHeadChild = null\n prefetchDataChild = null\n prefetchHeadChild = null\n isPrefetchHeadPartialChild = false\n }\n\n const newSegmentKeyChild = createRouterCacheKey(newSegmentChild)\n const oldCacheNodeChild =\n oldSegmentMapChild !== undefined\n ? oldSegmentMapChild.get(newSegmentKeyChild)\n : undefined\n\n const taskChild = updateCacheNodeOnNavigation(\n navigatedAt,\n oldUrl,\n oldCacheNodeChild,\n oldRouterStateChild,\n newRouterStateChild,\n freshness,\n childDidFindRootLayout,\n seedDataChild ?? null,\n seedHeadChild,\n prefetchDataChild ?? null,\n prefetchHeadChild,\n isPrefetchHeadPartialChild,\n isSamePageNavigation,\n segmentPath,\n parallelRouteKey,\n parentNeedsDynamicRequest || needsDynamicRequest,\n refreshUrl,\n accumulation\n )\n\n if (taskChild === null) {\n // One of the child tasks discovered a change to the root layout.\n // Immediately unwind from this recursive traversal. This will trigger a\n // full-page navigation.\n return null\n }\n\n // Recursively propagate up the child tasks.\n if (taskChildren === null) {\n taskChildren = new Map()\n }\n taskChildren.set(parallelRouteKey, taskChild)\n const newCacheNodeChild = taskChild.node\n if (newCacheNodeChild !== null) {\n const newSegmentMapChild: ChildSegmentMap = new Map(\n shouldDropSiblingCaches ? undefined : oldSegmentMapChild\n )\n newSegmentMapChild.set(newSegmentKeyChild, newCacheNodeChild)\n newParallelRoutes.set(parallelRouteKey, newSegmentMapChild)\n }\n\n // The child tree's route state may be different from the prefetched\n // route sent by the server. We need to clone it as we traverse back up\n // the tree.\n const taskChildRoute = taskChild.route\n patchedRouterStateChildren[parallelRouteKey] = taskChildRoute\n\n const dynamicRequestTreeChild = taskChild.dynamicRequestTree\n if (dynamicRequestTreeChild !== null) {\n // Something in the child tree is dynamic.\n childNeedsDynamicRequest = true\n dynamicRequestTreeChildren[parallelRouteKey] = dynamicRequestTreeChild\n } else {\n dynamicRequestTreeChildren[parallelRouteKey] = taskChildRoute\n }\n }\n\n return {\n status: needsDynamicRequest\n ? NavigationTaskStatus.Pending\n : NavigationTaskStatus.Fulfilled,\n route: patchRouterStateWithNewChildren(\n newRouterState,\n patchedRouterStateChildren\n ),\n node: newCacheNode,\n dynamicRequestTree: createDynamicRequestTree(\n newRouterState,\n dynamicRequestTreeChildren,\n needsDynamicRequest,\n childNeedsDynamicRequest,\n parentNeedsDynamicRequest\n ),\n refreshUrl,\n children: taskChildren,\n }\n}\n\nfunction createCacheNodeOnNavigation(\n navigatedAt: number,\n newRouterState: FlightRouterState,\n oldCacheNode: CacheNode | void,\n freshness: FreshnessPolicy,\n seedData: CacheNodeSeedData | null,\n seedHead: HeadData | null,\n prefetchData: CacheNodeSeedData | null,\n prefetchHead: HeadData | null,\n isPrefetchHeadPartial: boolean,\n parentSegmentPath: FlightSegmentPath | null,\n parentParallelRouteKey: string | null,\n parentNeedsDynamicRequest: boolean,\n accumulation: NavigationRequestAccumulation\n): NavigationTask {\n // Same traversal as updateCacheNodeNavigation, but simpler. We switch to this\n // path once we reach the part of the tree that was not in the previous route.\n // We don't need to diff against the old tree, we just need to create a new\n // one. We also don't need to worry about any refresh-related logic.\n //\n // For the most part, this is a subset of updateCacheNodeOnNavigation, so any\n // change that happens in this function likely needs to be applied to that\n // one, too. However there are some places where the behavior intentionally\n // diverges, which is why we keep them separate.\n\n const newSegment = newRouterState[0]\n const segmentPath =\n parentParallelRouteKey !== null && parentSegmentPath !== null\n ? parentSegmentPath.concat([parentParallelRouteKey, newSegment])\n : // NOTE: The root segment is intentionally omitted from the segment path\n []\n\n const newRouterStateChildren = newRouterState[1]\n const prefetchDataChildren = prefetchData !== null ? prefetchData[1] : null\n const seedDataChildren = seedData !== null ? seedData[1] : null\n const oldParallelRoutes =\n oldCacheNode !== undefined ? oldCacheNode.parallelRoutes : undefined\n\n let shouldDropSiblingCaches: boolean = false\n let shouldRefreshDynamicData: boolean = false\n let dropPrefetchRsc: boolean = false\n switch (freshness) {\n case FreshnessPolicy.Default:\n // We should never drop dynamic data in sibling caches except during\n // a refresh.\n shouldDropSiblingCaches = false\n\n // Only reuse the dynamic data if experimental.staleTimes.dynamic config\n // is set, and the data is not stale. (This is not a recommended API with\n // Cache Components, but it's supported for backwards compatibility. Use\n // cacheLife instead.)\n //\n // DYNAMIC_STALETIME_MS defaults to 0, but it can be increased.\n shouldRefreshDynamicData =\n oldCacheNode === undefined ||\n navigatedAt - oldCacheNode.navigatedAt >= DYNAMIC_STALETIME_MS\n\n dropPrefetchRsc = false\n break\n case FreshnessPolicy.Hydration:\n // During hydration, we assume the data sent by the server is both\n // consistent and complete.\n shouldRefreshDynamicData = false\n shouldDropSiblingCaches = false\n dropPrefetchRsc = false\n break\n case FreshnessPolicy.HistoryTraversal:\n // During back/forward navigations, we reuse the dynamic data regardless\n // of how stale it may be.\n shouldRefreshDynamicData = false\n shouldRefreshDynamicData = false\n\n // Only show prefetched data if the dynamic data is still pending. This\n // avoids a flash back to the prefetch state in a case where it's highly\n // likely to have already streamed in.\n //\n // Tehnically, what we're actually checking is whether the dynamic network\n // response was received. But since it's a streaming response, this does\n // not mean that all the dynamic data has fully streamed in. It just means\n // that _some_ of the dynamic data was received. But as a heuristic, we\n // assume that the rest dynamic data will stream in quickly, so it's still\n // better to skip the prefetch state.\n if (oldCacheNode !== undefined) {\n const oldRsc = oldCacheNode.rsc\n const oldRscDidResolve =\n !isDeferredRsc(oldRsc) || oldRsc.status !== 'pending'\n dropPrefetchRsc = oldRscDidResolve\n } else {\n dropPrefetchRsc = false\n }\n break\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n // Drop all dynamic data.\n shouldRefreshDynamicData = true\n shouldDropSiblingCaches = true\n dropPrefetchRsc = false\n break\n default:\n freshness satisfies never\n break\n }\n\n const newParallelRoutes = new Map(\n shouldDropSiblingCaches ? undefined : oldParallelRoutes\n )\n const isLeafSegment = Object.keys(newRouterStateChildren).length === 0\n\n if (isLeafSegment) {\n // The segment path of every leaf segment (i.e. page) is collected into\n // a result array. This is used by the LayoutRouter to scroll to ensure that\n // new pages are visible after a navigation.\n //\n // This only happens for new pages, not for refreshed pages.\n //\n // TODO: We should use a string to represent the segment path instead of\n // an array. We already use a string representation for the path when\n // accessing the Segment Cache, so we can use the same one.\n if (accumulation.scrollableSegments === null) {\n accumulation.scrollableSegments = []\n }\n accumulation.scrollableSegments.push(segmentPath)\n }\n\n let newCacheNode: CacheNode\n let needsDynamicRequest: boolean\n if (!shouldRefreshDynamicData && oldCacheNode !== undefined) {\n // Reuse the existing CacheNode\n newCacheNode = reuseDynamicCacheNode(\n dropPrefetchRsc,\n oldCacheNode,\n newParallelRoutes\n )\n needsDynamicRequest = false\n } else if (seedData !== null && seedData[0] !== null) {\n // If this navigation was the result of an action, then check if the\n // server sent back data in the action response. We should favor using\n // that, rather than performing a separate request. This is both better\n // for performance and it's more likely to be consistent with any\n // writes that were just performed by the action, compared to a\n // separate request.\n const seedRsc = seedData[0]\n const seedLoading = seedData[2]\n const isSeedRscPartial = false\n const isSeedHeadPartial =\n seedHead === null && freshness !== FreshnessPolicy.Hydration\n newCacheNode = readCacheNodeFromSeedData(\n seedRsc,\n seedLoading,\n isSeedRscPartial,\n seedHead,\n isSeedHeadPartial,\n isLeafSegment,\n newParallelRoutes,\n navigatedAt\n )\n needsDynamicRequest = isLeafSegment && isSeedHeadPartial\n } else if (\n freshness === FreshnessPolicy.Hydration &&\n isLeafSegment &&\n seedHead !== null\n ) {\n // This is another weird case related to \"not found\" pages and hydration.\n // There will be a head sent by the server, but no page seed data.\n // TODO: We really should get rid of all these \"not found\" specific quirks\n // and make sure the tree is always consistent.\n const seedRsc = null\n const seedLoading = null\n const isSeedRscPartial = false\n const isSeedHeadPartial = false\n newCacheNode = readCacheNodeFromSeedData(\n seedRsc,\n seedLoading,\n isSeedRscPartial,\n seedHead,\n isSeedHeadPartial,\n isLeafSegment,\n newParallelRoutes,\n navigatedAt\n )\n needsDynamicRequest = false\n } else if (freshness !== FreshnessPolicy.Hydration && prefetchData !== null) {\n // Consult the prefetch cache.\n const prefetchRsc = prefetchData[0]\n const prefetchLoading = prefetchData[2]\n const isPrefetchRSCPartial = prefetchData[3]\n newCacheNode = readCacheNodeFromSeedData(\n prefetchRsc,\n prefetchLoading,\n isPrefetchRSCPartial,\n prefetchHead,\n isPrefetchHeadPartial,\n isLeafSegment,\n newParallelRoutes,\n navigatedAt\n )\n needsDynamicRequest =\n isPrefetchRSCPartial || (isLeafSegment && isPrefetchHeadPartial)\n } else {\n // Spawn a request to fetch new data from the server.\n newCacheNode = spawnNewCacheNode(\n newParallelRoutes,\n isLeafSegment,\n navigatedAt,\n freshness\n )\n needsDynamicRequest = true\n }\n\n let patchedRouterStateChildren: {\n [parallelRouteKey: string]: FlightRouterState\n } = {}\n let taskChildren = null\n\n let childNeedsDynamicRequest = false\n let dynamicRequestTreeChildren: {\n [parallelRouteKey: string]: FlightRouterState\n } = {}\n\n for (let parallelRouteKey in newRouterStateChildren) {\n const newRouterStateChild: FlightRouterState =\n newRouterStateChildren[parallelRouteKey]\n const oldSegmentMapChild =\n oldParallelRoutes !== undefined\n ? oldParallelRoutes.get(parallelRouteKey)\n : undefined\n const seedDataChild: CacheNodeSeedData | void | null =\n seedDataChildren !== null ? seedDataChildren[parallelRouteKey] : null\n const prefetchDataChild: CacheNodeSeedData | void | null =\n prefetchDataChildren !== null\n ? prefetchDataChildren[parallelRouteKey]\n : null\n\n const newSegmentChild = newRouterStateChild[0]\n const newSegmentKeyChild = createRouterCacheKey(newSegmentChild)\n\n const oldCacheNodeChild =\n oldSegmentMapChild !== undefined\n ? oldSegmentMapChild.get(newSegmentKeyChild)\n : undefined\n\n const taskChild = createCacheNodeOnNavigation(\n navigatedAt,\n newRouterStateChild,\n oldCacheNodeChild,\n freshness,\n seedDataChild ?? null,\n seedHead,\n prefetchDataChild ?? null,\n prefetchHead,\n isPrefetchHeadPartial,\n segmentPath,\n parallelRouteKey,\n parentNeedsDynamicRequest || needsDynamicRequest,\n accumulation\n )\n\n if (taskChildren === null) {\n taskChildren = new Map()\n }\n taskChildren.set(parallelRouteKey, taskChild)\n const newCacheNodeChild = taskChild.node\n if (newCacheNodeChild !== null) {\n const newSegmentMapChild: ChildSegmentMap = new Map(\n shouldDropSiblingCaches ? undefined : oldSegmentMapChild\n )\n newSegmentMapChild.set(newSegmentKeyChild, newCacheNodeChild)\n newParallelRoutes.set(parallelRouteKey, newSegmentMapChild)\n }\n\n const taskChildRoute = taskChild.route\n patchedRouterStateChildren[parallelRouteKey] = taskChildRoute\n\n const dynamicRequestTreeChild = taskChild.dynamicRequestTree\n if (dynamicRequestTreeChild !== null) {\n childNeedsDynamicRequest = true\n dynamicRequestTreeChildren[parallelRouteKey] = dynamicRequestTreeChild\n } else {\n dynamicRequestTreeChildren[parallelRouteKey] = taskChildRoute\n }\n }\n\n return {\n status: needsDynamicRequest\n ? NavigationTaskStatus.Pending\n : NavigationTaskStatus.Fulfilled,\n route: patchRouterStateWithNewChildren(\n newRouterState,\n patchedRouterStateChildren\n ),\n node: newCacheNode,\n dynamicRequestTree: createDynamicRequestTree(\n newRouterState,\n dynamicRequestTreeChildren,\n needsDynamicRequest,\n childNeedsDynamicRequest,\n parentNeedsDynamicRequest\n ),\n // This route is not part of the current tree, so there's no reason to\n // track the refresh URL.\n refreshUrl: null,\n children: taskChildren,\n }\n}\n\nfunction patchRouterStateWithNewChildren(\n baseRouterState: FlightRouterState,\n newChildren: { [parallelRouteKey: string]: FlightRouterState }\n): FlightRouterState {\n const clone: FlightRouterState = [baseRouterState[0], newChildren]\n // Based on equivalent logic in apply-router-state-patch-to-tree, but should\n // confirm whether we need to copy all of these fields. Not sure the server\n // ever sends, e.g. the refetch marker.\n if (2 in baseRouterState) {\n clone[2] = baseRouterState[2]\n }\n if (3 in baseRouterState) {\n clone[3] = baseRouterState[3]\n }\n if (4 in baseRouterState) {\n clone[4] = baseRouterState[4]\n }\n return clone\n}\n\nfunction createDynamicRequestTree(\n newRouterState: FlightRouterState,\n dynamicRequestTreeChildren: Record<string, FlightRouterState>,\n needsDynamicRequest: boolean,\n childNeedsDynamicRequest: boolean,\n parentNeedsDynamicRequest: boolean\n): FlightRouterState | null {\n // Create a FlightRouterState that instructs the server how to render the\n // requested segment.\n //\n // Or, if neither this segment nor any of the children require a new data,\n // then we return `null` to skip the request.\n let dynamicRequestTree: FlightRouterState | null = null\n if (needsDynamicRequest) {\n dynamicRequestTree = patchRouterStateWithNewChildren(\n newRouterState,\n dynamicRequestTreeChildren\n )\n // The \"refetch\" marker is set on the top-most segment that requires new\n // data. We can omit it if a parent was already marked.\n if (!parentNeedsDynamicRequest) {\n dynamicRequestTree[3] = 'refetch'\n }\n } else if (childNeedsDynamicRequest) {\n // This segment does not request new data, but at least one of its\n // children does.\n dynamicRequestTree = patchRouterStateWithNewChildren(\n newRouterState,\n dynamicRequestTreeChildren\n )\n } else {\n dynamicRequestTree = null\n }\n return dynamicRequestTree\n}\n\nfunction accumulateRefreshUrl(\n accumulation: NavigationRequestAccumulation,\n refreshUrl: string\n) {\n // This is a refresh navigation, and we're inside a \"default\" slot that's\n // not part of the current route; it was reused from an older route. In\n // order to get fresh data for this reused route, we need to issue a\n // separate request using the old route's URL.\n //\n // Track these extra URLs in the accumulated result. Later, we'll construct\n // an appropriate request for each unique URL in the final set. The reason\n // we don't do it immediately here is so we can deduplicate multiple\n // instances of the same URL into a single request. See\n // listenForDynamicRequest for more details.\n const separateRefreshUrls = accumulation.separateRefreshUrls\n if (separateRefreshUrls === null) {\n accumulation.separateRefreshUrls = new Set([refreshUrl])\n } else {\n separateRefreshUrls.add(refreshUrl)\n }\n}\n\nfunction reuseActiveSegmentInDefaultSlot(\n oldUrl: URL,\n oldRouterState: FlightRouterState\n): FlightRouterState {\n // This is a \"default\" segment. These are never sent by the server during a\n // soft navigation; instead, the client reuses whatever segment was already\n // active in that slot on the previous route. This means if we later need to\n // refresh the segment, it will have to be refetched from the previous route's\n // URL. We store it in the Flight Router State.\n //\n // TODO: We also mark the segment with a \"refresh\" marker but I think we can\n // get rid of that eventually by making sure we only add URLs to page segments\n // that are reused. Then the presence of the URL alone is enough.\n let reusedRouterState\n\n const oldRefreshMarker = oldRouterState[3]\n if (oldRefreshMarker === 'refresh') {\n // This segment was already reused from an even older route. Keep its\n // existing URL and refresh marker.\n reusedRouterState = oldRouterState\n } else {\n // This segment was not previously reused, and it's not on the new route.\n // So it must have been delivered in the old route.\n reusedRouterState = patchRouterStateWithNewChildren(\n oldRouterState,\n oldRouterState[1]\n )\n reusedRouterState[2] = createHrefFromUrl(oldUrl)\n reusedRouterState[3] = 'refresh'\n }\n\n return reusedRouterState\n}\n\nfunction reuseDynamicCacheNode(\n dropPrefetchRsc: boolean,\n existingCacheNode: CacheNode,\n parallelRoutes: Map<string, ChildSegmentMap>\n): CacheNode {\n // Clone an existing CacheNode's data, with (possibly) new children.\n const cacheNode: CacheNode = {\n rsc: existingCacheNode.rsc,\n prefetchRsc: dropPrefetchRsc ? null : existingCacheNode.prefetchRsc,\n head: existingCacheNode.head,\n prefetchHead: dropPrefetchRsc ? null : existingCacheNode.prefetchHead,\n loading: existingCacheNode.loading,\n\n parallelRoutes,\n\n // Don't update the navigatedAt timestamp, since we're reusing\n // existing data.\n navigatedAt: existingCacheNode.navigatedAt,\n }\n return cacheNode\n}\n\nfunction readCacheNodeFromSeedData(\n seedRsc: React.ReactNode,\n seedLoading: LoadingModuleData | Promise<LoadingModuleData>,\n isSeedRscPartial: boolean,\n seedHead: HeadData | null,\n isSeedHeadPartial: boolean,\n isPageSegment: boolean,\n parallelRoutes: Map<string, ChildSegmentMap>,\n navigatedAt: number\n): CacheNode {\n // TODO: Currently this is threaded through the navigation logic using the\n // CacheNodeSeedData type, but in the future this will read directly from\n // the Segment Cache. See readRenderSnapshotFromCache.\n\n let rsc: React.ReactNode\n let prefetchRsc: React.ReactNode\n if (isSeedRscPartial) {\n // The prefetched data contains dynamic holes. Create a pending promise that\n // will be fulfilled when the dynamic data is received from the server.\n prefetchRsc = seedRsc\n rsc = createDeferredRsc()\n } else {\n // The prefetched data is complete. Use it directly.\n prefetchRsc = null\n rsc = seedRsc\n }\n\n // If this is a page segment, also read the head.\n let prefetchHead: HeadData | null\n let head: HeadData | null\n if (isPageSegment) {\n if (isSeedHeadPartial) {\n prefetchHead = seedHead\n head = createDeferredRsc()\n } else {\n prefetchHead = null\n head = seedHead\n }\n } else {\n prefetchHead = null\n head = null\n }\n\n const cacheNode: CacheNode = {\n rsc,\n prefetchRsc,\n head,\n prefetchHead,\n // TODO: Technically, a loading boundary could contain dynamic data. We\n // should have separate `loading` and `prefetchLoading` fields to handle\n // this, like we do for the segment data and head.\n loading: seedLoading,\n parallelRoutes,\n navigatedAt,\n }\n\n return cacheNode\n}\n\nfunction spawnNewCacheNode(\n parallelRoutes: Map<string, ChildSegmentMap>,\n isLeafSegment: boolean,\n navigatedAt: number,\n freshness: FreshnessPolicy\n): CacheNode {\n // We should never spawn network requests during hydration. We must treat the\n // initial payload as authoritative, because the initial page load is used\n // as a last-ditch mechanism for recovering the app.\n //\n // This is also an important safety check because if this leaks into the\n // server rendering path (which theoretically it never should because\n // the server payload should be consistent), the server would hang because\n // these promises would never resolve.\n //\n // TODO: There is an existing case where the global \"not found\" boundary\n // triggers this path. But it does render correctly despite that. That's an\n // unusual render path so it's not surprising, but we should look into\n // modeling it in a more consistent way. See also the /_notFound special\n // case in updateCacheNodeOnNavigation.\n const isHydration = freshness === FreshnessPolicy.Hydration\n\n const cacheNode: CacheNode = {\n rsc: !isHydration ? createDeferredRsc() : null,\n prefetchRsc: null,\n head: !isHydration && isLeafSegment ? createDeferredRsc() : null,\n prefetchHead: null,\n loading: !isHydration ? createDeferredRsc<LoadingModuleData>() : null,\n parallelRoutes,\n navigatedAt,\n }\n return cacheNode\n}\n\n// Represents whether the previuos navigation resulted in a route tree mismatch.\n// A mismatch results in a refresh of the page. If there are two successive\n// mismatches, we will fall back to an MPA navigation, to prevent a retry loop.\nlet previousNavigationDidMismatch = false\n\n// Writes a dynamic server response into the tree created by\n// updateCacheNodeOnNavigation. All pending promises that were spawned by the\n// navigation will be resolved, either with dynamic data from the server, or\n// `null` to indicate that the data is missing.\n//\n// A `null` value will trigger a lazy fetch during render, which will then patch\n// up the tree using the same mechanism as the non-PPR implementation\n// (serverPatchReducer).\n//\n// Usually, the server will respond with exactly the subset of data that we're\n// waiting for — everything below the nearest shared layout. But technically,\n// the server can return anything it wants.\n//\n// This does _not_ create a new tree; it modifies the existing one in place.\n// Which means it must follow the Suspense rules of cache safety.\nexport function spawnDynamicRequests(\n task: NavigationTask,\n primaryUrl: URL,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n accumulation: NavigationRequestAccumulation\n): void {\n const dynamicRequestTree = task.dynamicRequestTree\n if (dynamicRequestTree === null) {\n // This navigation was fully cached. There are no dynamic requests to spawn.\n previousNavigationDidMismatch = false\n return\n }\n\n // This is intentionally not an async function to discourage the caller from\n // awaiting the result. Any subsequent async operations spawned by this\n // function should result in a separate navigation task, rather than\n // block the original one.\n //\n // In this function we spawn (but do not await) all the network requests that\n // block the navigation, and collect the promises. The next function,\n // `finishNavigationTask`, can await the promises in any order without\n // accidentally introducing a network waterfall.\n const primaryRequestPromise = fetchMissingDynamicData(\n task,\n dynamicRequestTree,\n primaryUrl,\n nextUrl,\n freshnessPolicy\n )\n\n const separateRefreshUrls = accumulation.separateRefreshUrls\n let refreshRequestPromises: Array<\n ReturnType<typeof fetchMissingDynamicData>\n > | null = null\n if (separateRefreshUrls !== null) {\n // There are multiple URLs that we need to request the data from. This\n // happens when a \"default\" parallel route slot is present in the tree, and\n // its data cannot be fetched from the current route. We need to split the\n // combined dynamic request tree into separate requests per URL.\n\n // TODO: Create a scoped dynamic request tree that omits anything that\n // is not relevant to the given URL. Without doing this, the server may\n // sometimes render more data than necessary; this is not a regression\n // compared to the pre-Segment Cache implementation, though, just an\n // optimization we can make in the future.\n\n // Construct a request tree for each additional refresh URL. This will\n // prune away everything except the parts of the tree that match the\n // given refresh URL.\n refreshRequestPromises = []\n const canonicalUrl = createHrefFromUrl(primaryUrl)\n for (const refreshUrl of separateRefreshUrls) {\n if (refreshUrl === canonicalUrl) {\n // We already initiated a request for the this URL, above. Skip it.\n // TODO: This only happens because the main URL is not tracked as\n // part of the separateRefreshURLs set. There's probably a better way\n // to structure this so this case doesn't happen.\n continue\n }\n // TODO: Create a scoped dynamic request tree that omits anything that\n // is not relevant to the given URL. Without doing this, the server may\n // sometimes render more data than necessary; this is not a regression\n // compared to the pre-Segment Cache implementation, though, just an\n // optimization we can make in the future.\n // const scopedDynamicRequestTree = splitTaskByURL(task, refreshUrl)\n const scopedDynamicRequestTree = dynamicRequestTree\n if (scopedDynamicRequestTree !== null) {\n refreshRequestPromises.push(\n fetchMissingDynamicData(\n task,\n scopedDynamicRequestTree,\n new URL(refreshUrl, location.origin),\n // TODO: Just noticed that this should actually the Next-Url at the\n // time the refresh URL was set, not the current Next-Url. Need to\n // start tracking this alongside the refresh URL. In the meantime,\n // if a refresh fails due to a mismatch, it will trigger a\n // hard refresh.\n nextUrl,\n freshnessPolicy\n )\n )\n }\n }\n }\n\n // Further async operations are moved into this separate function to\n // discourage sequential network requests.\n const voidPromise = finishNavigationTask(\n task,\n nextUrl,\n primaryRequestPromise,\n refreshRequestPromises\n )\n // `finishNavigationTask` is responsible for error handling, so we can attach\n // noop callbacks to this promise.\n voidPromise.then(noop, noop)\n}\n\nasync function finishNavigationTask(\n task: NavigationTask,\n nextUrl: string | null,\n primaryRequestPromise: ReturnType<typeof fetchMissingDynamicData>,\n refreshRequestPromises: Array<\n ReturnType<typeof fetchMissingDynamicData>\n > | null\n): Promise<void> {\n // Wait for all the requests to finish, or for the first one to fail.\n let exitStatus = await waitForRequestsToFinish(\n primaryRequestPromise,\n refreshRequestPromises\n )\n\n // Once the all the requests have finished, check the tree for any remaining\n // pending tasks. If anything is still pending, it means the server response\n // does not match the client, and we must refresh to get back to a consistent\n // state. We can skip this step if we already detected a mismatch during the\n // first phase; it doesn't matter in that case because we're going to refresh\n // the whole tree regardless.\n if (exitStatus === NavigationTaskExitStatus.Done) {\n exitStatus = abortRemainingPendingTasks(task, null, null)\n }\n\n switch (exitStatus) {\n case NavigationTaskExitStatus.Done: {\n // The task has completely finished. There's no missing data. Exit.\n previousNavigationDidMismatch = false\n return\n }\n case NavigationTaskExitStatus.SoftRetry: {\n // Some data failed to finish loading. Trigger a soft retry.\n // TODO: As an extra precaution against soft retry loops, consider\n // tracking whether a navigation was itself triggered by a retry. If two\n // happen in a row, fall back to a hard retry.\n const isHardRetry = false\n const primaryRequestResult = await primaryRequestPromise\n dispatchRetryDueToTreeMismatch(\n isHardRetry,\n primaryRequestResult.url,\n nextUrl,\n primaryRequestResult.seed,\n task.route\n )\n return\n }\n case NavigationTaskExitStatus.HardRetry: {\n // Some data failed to finish loading in a non-recoverable way, such as a\n // network error. Trigger an MPA navigation.\n //\n // Hard navigating/refreshing is how we prevent an infinite retry loop\n // caused by a network error — when the network fails, we fall back to the\n // browser behavior for offline navigations. In the future, Next.js may\n // introduce its own custom handling of offline navigations, but that\n // doesn't exist yet.\n const isHardRetry = true\n const primaryRequestResult = await primaryRequestPromise\n dispatchRetryDueToTreeMismatch(\n isHardRetry,\n primaryRequestResult.url,\n nextUrl,\n primaryRequestResult.seed,\n task.route\n )\n return\n }\n default: {\n return exitStatus satisfies never\n }\n }\n}\n\nfunction waitForRequestsToFinish(\n primaryRequestPromise: ReturnType<typeof fetchMissingDynamicData>,\n refreshRequestPromises: Array<\n ReturnType<typeof fetchMissingDynamicData>\n > | null\n) {\n // Custom async combinator logic. This could be replaced by Promise.any but\n // we don't assume that's available.\n //\n // Each promise resolves once the server responsds and the data is written\n // into the CacheNode tree. Resolve the combined promise once all the\n // requests finish.\n //\n // Or, resolve as soon as one of the requests fails, without waiting for the\n // others to finish.\n return new Promise<NavigationTaskExitStatus>((resolve) => {\n const onFulfill = (result: { exitStatus: NavigationTaskExitStatus }) => {\n if (result.exitStatus === NavigationTaskExitStatus.Done) {\n remainingCount--\n if (remainingCount === 0) {\n // All the requests finished successfully.\n resolve(NavigationTaskExitStatus.Done)\n }\n } else {\n // One of the requests failed. Exit with a failing status.\n // NOTE: It's possible for one of the requests to fail with SoftRetry\n // and a later one to fail with HardRetry. In this case, we choose to\n // retry immediately, rather than delay the retry until all the requests\n // finish. If it fails again, we will hard retry on the next\n // attempt, anyway.\n resolve(result.exitStatus)\n }\n }\n // onReject shouldn't ever be called because fetchMissingDynamicData's\n // entire body is wrapped in a try/catch. This is just defensive.\n const onReject = () => resolve(NavigationTaskExitStatus.HardRetry)\n\n // Attach the listeners to the promises.\n let remainingCount = 1\n primaryRequestPromise.then(onFulfill, onReject)\n if (refreshRequestPromises !== null) {\n remainingCount += refreshRequestPromises.length\n refreshRequestPromises.forEach((refreshRequestPromise) =>\n refreshRequestPromise.then(onFulfill, onReject)\n )\n }\n })\n}\n\nfunction dispatchRetryDueToTreeMismatch(\n isHardRetry: boolean,\n retryUrl: URL,\n retryNextUrl: string | null,\n seed: NavigationSeed | null,\n baseTree: FlightRouterState\n) {\n // If this is the second time in a row that a navigation resulted in a\n // mismatch, fall back to a hard (MPA) refresh.\n isHardRetry = isHardRetry || previousNavigationDidMismatch\n previousNavigationDidMismatch = true\n const retryAction: ServerPatchAction = {\n type: ACTION_SERVER_PATCH,\n previousTree: baseTree,\n url: retryUrl,\n nextUrl: retryNextUrl,\n seed,\n mpa: isHardRetry,\n }\n dispatchAppRouterAction(retryAction)\n}\n\nasync function fetchMissingDynamicData(\n task: NavigationTask,\n dynamicRequestTree: FlightRouterState,\n url: URL,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy\n): Promise<{\n exitStatus: NavigationTaskExitStatus\n url: URL\n seed: NavigationSeed | null\n}> {\n try {\n const result = await fetchServerResponse(url, {\n flightRouterState: dynamicRequestTree,\n nextUrl,\n isHmrRefresh: freshnessPolicy === FreshnessPolicy.HMRRefresh,\n })\n if (typeof result === 'string') {\n // fetchServerResponse will return an href to indicate that the SPA\n // navigation failed. For example, if the server triggered a hard\n // redirect, or the fetch request errored. Initiate an MPA navigation\n // to the given href.\n return {\n exitStatus: NavigationTaskExitStatus.HardRetry,\n url: new URL(result, location.origin),\n seed: null,\n }\n }\n const seed = convertServerPatchToFullTree(\n task.route,\n result.flightData,\n result.renderedSearch\n )\n const didReceiveUnknownParallelRoute = writeDynamicDataIntoNavigationTask(\n task,\n seed.tree,\n seed.data,\n seed.head,\n result.debugInfo\n )\n return {\n exitStatus: didReceiveUnknownParallelRoute\n ? NavigationTaskExitStatus.SoftRetry\n : NavigationTaskExitStatus.Done,\n url: new URL(result.canonicalUrl, location.origin),\n seed,\n }\n } catch {\n // This shouldn't happen because fetchServerResponse's entire body is\n // wrapped in a try/catch. If it does, though, it implies the server failed\n // to respond with any tree at all. So we must fall back to a hard retry.\n return {\n exitStatus: NavigationTaskExitStatus.HardRetry,\n url: url,\n seed: null,\n }\n }\n}\n\nfunction writeDynamicDataIntoNavigationTask(\n task: NavigationTask,\n serverRouterState: FlightRouterState,\n dynamicData: CacheNodeSeedData | null,\n dynamicHead: HeadData,\n debugInfo: Array<any> | null\n): boolean {\n if (task.status === NavigationTaskStatus.Pending && dynamicData !== null) {\n task.status = NavigationTaskStatus.Fulfilled\n finishPendingCacheNode(task.node, dynamicData, dynamicHead, debugInfo)\n }\n\n const taskChildren = task.children\n const serverChildren = serverRouterState[1]\n const dynamicDataChildren = dynamicData !== null ? dynamicData[1] : null\n\n // Detect whether the server sends a parallel route slot that the client\n // doesn't know about.\n let didReceiveUnknownParallelRoute = false\n\n if (taskChildren !== null) {\n for (const parallelRouteKey in serverChildren) {\n const serverRouterStateChild: FlightRouterState =\n serverChildren[parallelRouteKey]\n const dynamicDataChild: CacheNodeSeedData | null | void =\n dynamicDataChildren !== null\n ? dynamicDataChildren[parallelRouteKey]\n : null\n\n const taskChild = taskChildren.get(parallelRouteKey)\n if (taskChild === undefined) {\n // The server sent a child segment that the client doesn't know about.\n //\n // When we receive an unknown parallel route, we must consider it a\n // mismatch. This is unlike the case where the segment itself\n // mismatches, because multiple routes can be active simultaneously.\n // But a given layout should never have a mismatching set of\n // child slots.\n //\n // Theoretically, this should only happen in development during an HMR\n // refresh, because the set of parallel routes for a layout does not\n // change over the lifetime of a build/deployment. In production, we\n // should have already mismatched on either the build id or the segment\n // path. But as an extra precaution, we validate in prod, too.\n didReceiveUnknownParallelRoute = true\n } else {\n const taskSegment = taskChild.route[0]\n if (\n matchSegment(serverRouterStateChild[0], taskSegment) &&\n dynamicDataChild !== null &&\n dynamicDataChild !== undefined\n ) {\n // Found a match for this task. Keep traversing down the task tree.\n const childDidReceiveUnknownParallelRoute =\n writeDynamicDataIntoNavigationTask(\n taskChild,\n serverRouterStateChild,\n dynamicDataChild,\n dynamicHead,\n debugInfo\n )\n if (childDidReceiveUnknownParallelRoute) {\n didReceiveUnknownParallelRoute = true\n }\n }\n }\n }\n }\n\n return didReceiveUnknownParallelRoute\n}\n\nfunction finishPendingCacheNode(\n cacheNode: CacheNode,\n dynamicData: CacheNodeSeedData,\n dynamicHead: HeadData,\n debugInfo: Array<any> | null\n): void {\n // Writes a dynamic response into an existing Cache Node tree. This does _not_\n // create a new tree, it updates the existing tree in-place. So it must follow\n // the Suspense rules of cache safety — it can resolve pending promises, but\n // it cannot overwrite existing data. It can add segments to the tree (because\n // a missing segment will cause the layout router to suspend).\n // but it cannot delete them.\n //\n // We must resolve every promise in the tree, or else it will suspend\n // indefinitely. If we did not receive data for a segment, we will resolve its\n // data promise to `null` to trigger a lazy fetch during render.\n\n // Use the dynamic data from the server to fulfill the deferred RSC promise\n // on the Cache Node.\n const rsc = cacheNode.rsc\n const dynamicSegmentData = dynamicData[0]\n\n if (dynamicSegmentData === null) {\n // This is an empty CacheNode; this particular server request did not\n // render this segment. There may be a separate pending request that will,\n // though, so we won't abort the task until all pending requests finish.\n return\n }\n\n if (rsc === null) {\n // This is a lazy cache node. We can overwrite it. This is only safe\n // because we know that the LayoutRouter suspends if `rsc` is `null`.\n cacheNode.rsc = dynamicSegmentData\n } else if (isDeferredRsc(rsc)) {\n // This is a deferred RSC promise. We can fulfill it with the data we just\n // received from the server. If it was already resolved by a different\n // navigation, then this does nothing because we can't overwrite data.\n rsc.resolve(dynamicSegmentData, debugInfo)\n } else {\n // This is not a deferred RSC promise, nor is it empty, so it must have\n // been populated by a different navigation. We must not overwrite it.\n }\n\n // If we navigated without a prefetch, then `loading` will be a deferred promise too.\n // Fulfill it using the dynamic response so that we can display the loading boundary.\n const loading = cacheNode.loading\n if (isDeferredRsc(loading)) {\n const dynamicLoading = dynamicData[2]\n loading.resolve(dynamicLoading, debugInfo)\n }\n\n // Check if this is a leaf segment. If so, it will have a `head` property with\n // a pending promise that needs to be resolved with the dynamic head from\n // the server.\n const head = cacheNode.head\n if (isDeferredRsc(head)) {\n head.resolve(dynamicHead, debugInfo)\n }\n}\n\nfunction abortRemainingPendingTasks(\n task: NavigationTask,\n error: any,\n debugInfo: Array<any> | null\n): NavigationTaskExitStatus {\n let exitStatus\n if (task.status === NavigationTaskStatus.Pending) {\n // The data for this segment is still missing.\n task.status = NavigationTaskStatus.Rejected\n abortPendingCacheNode(task.node, error, debugInfo)\n\n // If the server failed to fulfill the data for this segment, it implies\n // that the route tree received from the server mismatched the tree that\n // was previously prefetched.\n //\n // In an app with fully static routes and no proxy-driven redirects or\n // rewrites, this should never happen, because the route for a URL would\n // always be the same across multiple requests. So, this implies that some\n // runtime routing condition changed, likely in a proxy, without being\n // pushed to the client.\n //\n // When this happens, we treat this the same as a refresh(). The entire\n // tree will be re-rendered from the root.\n if (task.refreshUrl === null) {\n // Trigger a \"soft\" refresh. Essentially the same as calling `refresh()`\n // in a Server Action.\n exitStatus = NavigationTaskExitStatus.SoftRetry\n } else {\n // The mismatch was discovered inside an inactive parallel route. This\n // implies the inactive parallel route is no longer reachable at the URL\n // that originally rendered it. Fall back to an MPA refresh.\n // TODO: An alternative could be to trigger a soft refresh but to _not_\n // re-use the inactive parallel routes this time. Similar to what would\n // happen if were to do a hard refrehs, but without the HTML page.\n exitStatus = NavigationTaskExitStatus.HardRetry\n }\n } else {\n // This segment finished. (An error here is treated as Done because they are\n // surfaced to the application during render.)\n exitStatus = NavigationTaskExitStatus.Done\n }\n\n const taskChildren = task.children\n if (taskChildren !== null) {\n for (const [, taskChild] of taskChildren) {\n const childExitStatus = abortRemainingPendingTasks(\n taskChild,\n error,\n debugInfo\n )\n // Propagate the exit status up the tree. The statuses are ordered by\n // their precedence.\n if (childExitStatus > exitStatus) {\n exitStatus = childExitStatus\n }\n }\n }\n\n return exitStatus\n}\n\nfunction abortPendingCacheNode(\n cacheNode: CacheNode,\n error: any,\n debugInfo: Array<any> | null\n): void {\n const rsc = cacheNode.rsc\n if (isDeferredRsc(rsc)) {\n if (error === null) {\n // This will trigger a lazy fetch during render.\n rsc.resolve(null, debugInfo)\n } else {\n // This will trigger an error during rendering.\n rsc.reject(error, debugInfo)\n }\n }\n\n const loading = cacheNode.loading\n if (isDeferredRsc(loading)) {\n loading.resolve(null, debugInfo)\n }\n\n // Check if this is a leaf segment. If so, it will have a `head` property with\n // a pending promise that needs to be resolved. If an error was provided, we\n // will not resolve it with an error, since this is rendered at the root of\n // the app. We want the segment to error, not the entire app.\n const head = cacheNode.head\n if (isDeferredRsc(head)) {\n head.resolve(null, debugInfo)\n }\n}\n\nconst DEFERRED = Symbol()\n\ntype PendingDeferredRsc<T> = Promise<T> & {\n status: 'pending'\n resolve: (value: T, debugInfo: Array<any> | null) => void\n reject: (error: any, debugInfo: Array<any> | null) => void\n tag: Symbol\n _debugInfo: Array<any>\n}\n\ntype FulfilledDeferredRsc<T> = Promise<T> & {\n status: 'fulfilled'\n value: T\n resolve: (value: T, debugInfo: Array<any> | null) => void\n reject: (error: any, debugInfo: Array<any> | null) => void\n tag: Symbol\n _debugInfo: Array<any>\n}\n\ntype RejectedDeferredRsc<T> = Promise<T> & {\n status: 'rejected'\n reason: any\n resolve: (value: T, debugInfo: Array<any> | null) => void\n reject: (error: any, debugInfo: Array<any> | null) => void\n tag: Symbol\n _debugInfo: Array<any>\n}\n\ntype DeferredRsc<T extends React.ReactNode = React.ReactNode> =\n | PendingDeferredRsc<T>\n | FulfilledDeferredRsc<T>\n | RejectedDeferredRsc<T>\n\n// This type exists to distinguish a DeferredRsc from a Flight promise. It's a\n// compromise to avoid adding an extra field on every Cache Node, which would be\n// awkward because the pre-PPR parts of codebase would need to account for it,\n// too. We can remove it once type Cache Node type is more settled.\nexport function isDeferredRsc(value: any): value is DeferredRsc {\n return value && typeof value === 'object' && value.tag === DEFERRED\n}\n\nfunction createDeferredRsc<\n T extends React.ReactNode = React.ReactNode,\n>(): PendingDeferredRsc<T> {\n // Create an unresolved promise that represents data derived from a Flight\n // response. The promise will be resolved later as soon as we start receiving\n // data from the server, i.e. as soon as the Flight client decodes and returns\n // the top-level response object.\n\n // The `_debugInfo` field contains profiling information. Promises that are\n // created by Flight already have this info added by React; for any derived\n // promise created by the router, we need to transfer the Flight debug info\n // onto the derived promise.\n //\n // The debug info represents the latency between the start of the navigation\n // and the start of rendering. (It does not represent the time it takes for\n // whole stream to finish.)\n const debugInfo: Array<any> = []\n\n let resolve: any\n let reject: any\n const pendingRsc = new Promise<T>((res, rej) => {\n resolve = res\n reject = rej\n }) as PendingDeferredRsc<T>\n pendingRsc.status = 'pending'\n pendingRsc.resolve = (value: T, responseDebugInfo: Array<any> | null) => {\n if (pendingRsc.status === 'pending') {\n const fulfilledRsc: FulfilledDeferredRsc<T> = pendingRsc as any\n fulfilledRsc.status = 'fulfilled'\n fulfilledRsc.value = value\n if (responseDebugInfo !== null) {\n // Transfer the debug info to the derived promise.\n debugInfo.push.apply(debugInfo, responseDebugInfo)\n }\n resolve(value)\n }\n }\n pendingRsc.reject = (error: any, responseDebugInfo: Array<any> | null) => {\n if (pendingRsc.status === 'pending') {\n const rejectedRsc: RejectedDeferredRsc<T> = pendingRsc as any\n rejectedRsc.status = 'rejected'\n rejectedRsc.reason = error\n if (responseDebugInfo !== null) {\n // Transfer the debug info to the derived promise.\n debugInfo.push.apply(debugInfo, responseDebugInfo)\n }\n reject(error)\n }\n }\n pendingRsc.tag = DEFERRED\n pendingRsc._debugInfo = debugInfo\n\n return pendingRsc\n}\n","import type {\n CacheNodeSeedData,\n FlightRouterState,\n FlightSegmentPath,\n} from '../../../shared/lib/app-router-types'\nimport type { CacheNode } from '../../../shared/lib/app-router-types'\nimport type {\n HeadData,\n LoadingModuleData,\n} from '../../../shared/lib/app-router-types'\nimport type { NormalizedFlightData } from '../../flight-data-helpers'\nimport { fetchServerResponse } from '../router-reducer/fetch-server-response'\nimport {\n startPPRNavigation,\n spawnDynamicRequests,\n FreshnessPolicy,\n type NavigationTask,\n type NavigationRequestAccumulation,\n} from '../router-reducer/ppr-navigations'\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url'\nimport {\n EntryStatus,\n readRouteCacheEntry,\n readSegmentCacheEntry,\n waitForSegmentCacheEntry,\n requestOptimisticRouteCacheEntry,\n type RouteTree,\n type FulfilledRouteCacheEntry,\n} from './cache'\nimport { createCacheKey } from './cache-key'\nimport { addSearchParamsIfPageSegment } from '../../../shared/lib/segment'\nimport { NavigationResultTag } from './types'\n\ntype MPANavigationResult = {\n tag: NavigationResultTag.MPA\n data: string\n}\n\ntype SuccessfulNavigationResult = {\n tag: NavigationResultTag.Success\n data: {\n flightRouterState: FlightRouterState\n cacheNode: CacheNode\n canonicalUrl: string\n renderedSearch: string\n scrollableSegments: Array<FlightSegmentPath> | null\n shouldScroll: boolean\n hash: string\n }\n}\n\ntype AsyncNavigationResult = {\n tag: NavigationResultTag.Async\n data: Promise<MPANavigationResult | SuccessfulNavigationResult>\n}\n\nexport type NavigationResult =\n | MPANavigationResult\n | SuccessfulNavigationResult\n | AsyncNavigationResult\n\n/**\n * Navigate to a new URL, using the Segment Cache to construct a response.\n *\n * To allow for synchronous navigations whenever possible, this is not an async\n * function. It returns a promise only if there's no matching prefetch in\n * the cache. Otherwise it returns an immediate result and uses Suspense/RSC to\n * stream in any missing data.\n */\nexport function navigate(\n url: URL,\n currentUrl: URL,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n shouldScroll: boolean,\n accumulation: { collectedDebugInfo?: Array<unknown> }\n): NavigationResult {\n const now = Date.now()\n const href = url.href\n\n // We special case navigations to the exact same URL as the current location.\n // It's a common UI pattern for apps to refresh when you click a link to the\n // current page. So when this happens, we refresh the dynamic data in the page\n // segments.\n //\n // Note that this does not apply if the any part of the hash or search query\n // has changed. This might feel a bit weird but it makes more sense when you\n // consider that the way to trigger this behavior is to click the same link\n // multiple times.\n //\n // TODO: We should probably refresh the *entire* route when this case occurs,\n // not just the page segments. Essentially treating it the same as a refresh()\n // triggered by an action, which is the more explicit way of modeling the UI\n // pattern described above.\n //\n // Also note that this only refreshes the dynamic data, not static/ cached\n // data. If the page segment is fully static and prefetched, the request is\n // skipped. (This is also how refresh() works.)\n const isSamePageNavigation = href === currentUrl.href\n\n const cacheKey = createCacheKey(href, nextUrl)\n const route = readRouteCacheEntry(now, cacheKey)\n if (route !== null && route.status === EntryStatus.Fulfilled) {\n // We have a matching prefetch.\n const snapshot = readRenderSnapshotFromCache(now, route, route.tree)\n const prefetchFlightRouterState = snapshot.flightRouterState\n const prefetchSeedData = snapshot.seedData\n const headSnapshot = readHeadSnapshotFromCache(now, route)\n const prefetchHead = headSnapshot.rsc\n const isPrefetchHeadPartial = headSnapshot.isPartial\n // TODO: The \"canonicalUrl\" stored in the cache doesn't include the hash,\n // because hash entries do not vary by hash fragment. However, the one\n // we set in the router state *does* include the hash, and it's used to\n // sync with the actual browser location. To make this less of a refactor\n // hazard, we should always track the hash separately from the rest of\n // the URL.\n const newCanonicalUrl = route.canonicalUrl + url.hash\n const renderedSearch = route.renderedSearch\n return navigateUsingPrefetchedRouteTree(\n now,\n url,\n currentUrl,\n nextUrl,\n isSamePageNavigation,\n currentCacheNode,\n currentFlightRouterState,\n prefetchFlightRouterState,\n prefetchSeedData,\n prefetchHead,\n isPrefetchHeadPartial,\n newCanonicalUrl,\n renderedSearch,\n freshnessPolicy,\n shouldScroll\n )\n }\n\n // There was no matching route tree in the cache. Let's see if we can\n // construct an \"optimistic\" route tree.\n //\n // Do not construct an optimistic route tree if there was a cache hit, but\n // the entry has a rejected status, since it may have been rejected due to a\n // rewrite or redirect based on the search params.\n //\n // TODO: There are multiple reasons a prefetch might be rejected; we should\n // track them explicitly and choose what to do here based on that.\n if (route === null || route.status !== EntryStatus.Rejected) {\n const optimisticRoute = requestOptimisticRouteCacheEntry(now, url, nextUrl)\n if (optimisticRoute !== null) {\n // We have an optimistic route tree. Proceed with the normal flow.\n const snapshot = readRenderSnapshotFromCache(\n now,\n optimisticRoute,\n optimisticRoute.tree\n )\n const prefetchFlightRouterState = snapshot.flightRouterState\n const prefetchSeedData = snapshot.seedData\n const headSnapshot = readHeadSnapshotFromCache(now, optimisticRoute)\n const prefetchHead = headSnapshot.rsc\n const isPrefetchHeadPartial = headSnapshot.isPartial\n const newCanonicalUrl = optimisticRoute.canonicalUrl + url.hash\n const newRenderedSearch = optimisticRoute.renderedSearch\n return navigateUsingPrefetchedRouteTree(\n now,\n url,\n currentUrl,\n nextUrl,\n isSamePageNavigation,\n currentCacheNode,\n currentFlightRouterState,\n prefetchFlightRouterState,\n prefetchSeedData,\n prefetchHead,\n isPrefetchHeadPartial,\n newCanonicalUrl,\n newRenderedSearch,\n freshnessPolicy,\n shouldScroll\n )\n }\n }\n\n // There's no matching prefetch for this route in the cache.\n let collectedDebugInfo = accumulation.collectedDebugInfo ?? []\n if (accumulation.collectedDebugInfo === undefined) {\n collectedDebugInfo = accumulation.collectedDebugInfo = []\n }\n return {\n tag: NavigationResultTag.Async,\n data: navigateDynamicallyWithNoPrefetch(\n now,\n url,\n currentUrl,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n shouldScroll,\n collectedDebugInfo\n ),\n }\n}\n\nexport function navigateToSeededRoute(\n now: number,\n url: URL,\n canonicalUrl: string,\n navigationSeed: NavigationSeed,\n currentUrl: URL,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n nextUrl: string | null,\n shouldScroll: boolean\n): SuccessfulNavigationResult | MPANavigationResult {\n // A version of navigate() that accepts the target route tree as an argument\n // rather than reading it from the prefetch cache.\n const accumulation: NavigationRequestAccumulation = {\n scrollableSegments: null,\n separateRefreshUrls: null,\n }\n const isSamePageNavigation = url.href === currentUrl.href\n const task = startPPRNavigation(\n now,\n currentUrl,\n currentCacheNode,\n currentFlightRouterState,\n navigationSeed.tree,\n freshnessPolicy,\n navigationSeed.data,\n navigationSeed.head,\n null,\n null,\n false,\n isSamePageNavigation,\n accumulation\n )\n if (task !== null) {\n spawnDynamicRequests(task, url, nextUrl, freshnessPolicy, accumulation)\n return navigationTaskToResult(\n task,\n canonicalUrl,\n navigationSeed.renderedSearch,\n accumulation.scrollableSegments,\n shouldScroll,\n url.hash\n )\n }\n // Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.\n return {\n tag: NavigationResultTag.MPA,\n data: canonicalUrl,\n }\n}\n\nfunction navigateUsingPrefetchedRouteTree(\n now: number,\n url: URL,\n currentUrl: URL,\n nextUrl: string | null,\n isSamePageNavigation: boolean,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n prefetchFlightRouterState: FlightRouterState,\n prefetchSeedData: CacheNodeSeedData | null,\n prefetchHead: HeadData | null,\n isPrefetchHeadPartial: boolean,\n canonicalUrl: string,\n renderedSearch: string,\n freshnessPolicy: FreshnessPolicy,\n shouldScroll: boolean\n): SuccessfulNavigationResult | MPANavigationResult {\n // Recursively construct a prefetch tree by reading from the Segment Cache. To\n // maintain compatibility, we output the same data structures as the old\n // prefetching implementation: FlightRouterState and CacheNodeSeedData.\n // TODO: Eventually updateCacheNodeOnNavigation (or the equivalent) should\n // read from the Segment Cache directly. It's only structured this way for now\n // so we can share code with the old prefetching implementation.\n const accumulation: NavigationRequestAccumulation = {\n scrollableSegments: null,\n separateRefreshUrls: null,\n }\n const seedData = null\n const seedHead = null\n const task = startPPRNavigation(\n now,\n currentUrl,\n currentCacheNode,\n currentFlightRouterState,\n prefetchFlightRouterState,\n freshnessPolicy,\n seedData,\n seedHead,\n prefetchSeedData,\n prefetchHead,\n isPrefetchHeadPartial,\n isSamePageNavigation,\n accumulation\n )\n if (task !== null) {\n spawnDynamicRequests(task, url, nextUrl, freshnessPolicy, accumulation)\n return navigationTaskToResult(\n task,\n canonicalUrl,\n renderedSearch,\n accumulation.scrollableSegments,\n shouldScroll,\n url.hash\n )\n }\n // Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.\n return {\n tag: NavigationResultTag.MPA,\n data: canonicalUrl,\n }\n}\n\nfunction navigationTaskToResult(\n task: NavigationTask,\n canonicalUrl: string,\n renderedSearch: string,\n scrollableSegments: Array<FlightSegmentPath> | null,\n shouldScroll: boolean,\n hash: string\n): SuccessfulNavigationResult | MPANavigationResult {\n return {\n tag: NavigationResultTag.Success,\n data: {\n flightRouterState: task.route,\n cacheNode: task.node,\n canonicalUrl,\n renderedSearch,\n scrollableSegments,\n shouldScroll,\n hash,\n },\n }\n}\n\nfunction readRenderSnapshotFromCache(\n now: number,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree\n): { flightRouterState: FlightRouterState; seedData: CacheNodeSeedData } {\n let childRouterStates: { [parallelRouteKey: string]: FlightRouterState } = {}\n let childSeedDatas: {\n [parallelRouteKey: string]: CacheNodeSeedData | null\n } = {}\n const slots = tree.slots\n if (slots !== null) {\n for (const parallelRouteKey in slots) {\n const childTree = slots[parallelRouteKey]\n const childResult = readRenderSnapshotFromCache(now, route, childTree)\n childRouterStates[parallelRouteKey] = childResult.flightRouterState\n childSeedDatas[parallelRouteKey] = childResult.seedData\n }\n }\n\n let rsc: React.ReactNode | null = null\n let loading: LoadingModuleData | Promise<LoadingModuleData> = null\n let isPartial: boolean = true\n\n const segmentEntry = readSegmentCacheEntry(now, tree.varyPath)\n if (segmentEntry !== null) {\n switch (segmentEntry.status) {\n case EntryStatus.Fulfilled: {\n // Happy path: a cache hit\n rsc = segmentEntry.rsc\n loading = segmentEntry.loading\n isPartial = segmentEntry.isPartial\n break\n }\n case EntryStatus.Pending: {\n // We haven't received data for this segment yet, but there's already\n // an in-progress request. Since it's extremely likely to arrive\n // before the dynamic data response, we might as well use it.\n const promiseForFulfilledEntry = waitForSegmentCacheEntry(segmentEntry)\n rsc = promiseForFulfilledEntry.then((entry) =>\n entry !== null ? entry.rsc : null\n )\n loading = promiseForFulfilledEntry.then((entry) =>\n entry !== null ? entry.loading : null\n )\n // Because the request is still pending, we typically don't know yet\n // whether the response will be partial. We shouldn't skip this segment\n // during the dynamic navigation request. Otherwise, we might need to\n // do yet another request to fill in the remaining data, creating\n // a waterfall.\n //\n // The one exception is if this segment is being fetched with via\n // prefetch={true} (i.e. the \"force stale\" or \"full\" strategy). If so,\n // we can assume the response will be full. This field is set to `false`\n // for such segments.\n isPartial = segmentEntry.isPartial\n break\n }\n case EntryStatus.Empty:\n case EntryStatus.Rejected:\n break\n default:\n segmentEntry satisfies never\n }\n }\n\n // The navigation implementation expects the search params to be\n // included in the segment. However, the Segment Cache tracks search\n // params separately from the rest of the segment key. So we need to\n // add them back here.\n //\n // See corresponding comment in convertFlightRouterStateToTree.\n //\n // TODO: What we should do instead is update the navigation diffing\n // logic to compare search params explicitly. This is a temporary\n // solution until more of the Segment Cache implementation has settled.\n const segment = addSearchParamsIfPageSegment(\n tree.segment,\n Object.fromEntries(new URLSearchParams(route.renderedSearch))\n )\n\n // We don't need this information in a render snapshot, so this can just be a placeholder.\n const hasRuntimePrefetch = false\n\n return {\n flightRouterState: [\n segment,\n childRouterStates,\n null,\n null,\n tree.isRootLayout,\n ],\n seedData: [rsc, childSeedDatas, loading, isPartial, hasRuntimePrefetch],\n }\n}\n\nfunction readHeadSnapshotFromCache(\n now: number,\n route: FulfilledRouteCacheEntry\n): { rsc: HeadData; isPartial: boolean } {\n // Same as readRenderSnapshotFromCache, but for the head\n let rsc: React.ReactNode | null = null\n let isPartial: boolean = true\n const segmentEntry = readSegmentCacheEntry(now, route.metadata.varyPath)\n if (segmentEntry !== null) {\n switch (segmentEntry.status) {\n case EntryStatus.Fulfilled: {\n rsc = segmentEntry.rsc\n isPartial = segmentEntry.isPartial\n break\n }\n case EntryStatus.Pending: {\n const promiseForFulfilledEntry = waitForSegmentCacheEntry(segmentEntry)\n rsc = promiseForFulfilledEntry.then((entry) =>\n entry !== null ? entry.rsc : null\n )\n isPartial = segmentEntry.isPartial\n break\n }\n case EntryStatus.Empty:\n case EntryStatus.Rejected:\n break\n default:\n segmentEntry satisfies never\n }\n }\n return { rsc, isPartial }\n}\n\n// Used to request all the dynamic data for a route, rather than just a subset,\n// e.g. during a refresh or a revalidation. Typically this gets constructed\n// during the normal flow when diffing the route tree, but for an unprefetched\n// navigation, where we don't know the structure of the target route, we use\n// this instead.\nconst DynamicRequestTreeForEntireRoute: FlightRouterState = [\n '',\n {},\n null,\n 'refetch',\n]\n\nasync function navigateDynamicallyWithNoPrefetch(\n now: number,\n url: URL,\n currentUrl: URL,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n shouldScroll: boolean,\n collectedDebugInfo: Array<unknown>\n): Promise<MPANavigationResult | SuccessfulNavigationResult> {\n // Runs when a navigation happens but there's no cached prefetch we can use.\n // Don't bother to wait for a prefetch response; go straight to a full\n // navigation that contains both static and dynamic data in a single stream.\n // (This is unlike the old navigation implementation, which instead blocks\n // the dynamic request until a prefetch request is received.)\n //\n // To avoid duplication of logic, we're going to pretend that the tree\n // returned by the dynamic request is, in fact, a prefetch tree. Then we can\n // use the same server response to write the actual data into the CacheNode\n // tree. So it's the same flow as the \"happy path\" (prefetch, then\n // navigation), except we use a single server response for both stages.\n\n let dynamicRequestTree: FlightRouterState\n switch (freshnessPolicy) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.HistoryTraversal:\n dynamicRequestTree = currentFlightRouterState\n break\n case FreshnessPolicy.Hydration: // <- shouldn't happen during client nav\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n dynamicRequestTree = DynamicRequestTreeForEntireRoute\n break\n default:\n freshnessPolicy satisfies never\n dynamicRequestTree = currentFlightRouterState\n break\n }\n\n const promiseForDynamicServerResponse = fetchServerResponse(url, {\n flightRouterState: dynamicRequestTree,\n nextUrl,\n })\n const result = await promiseForDynamicServerResponse\n if (typeof result === 'string') {\n // This is an MPA navigation.\n const newUrl = result\n return {\n tag: NavigationResultTag.MPA,\n data: newUrl,\n }\n }\n\n const {\n flightData,\n canonicalUrl,\n renderedSearch,\n debugInfo: debugInfoFromResponse,\n } = result\n if (debugInfoFromResponse !== null) {\n collectedDebugInfo.push(...debugInfoFromResponse)\n }\n\n // Since the response format of dynamic requests and prefetches is slightly\n // different, we'll need to massage the data a bit. Create FlightRouterState\n // tree that simulates what we'd receive as the result of a prefetch.\n const navigationSeed = convertServerPatchToFullTree(\n currentFlightRouterState,\n flightData,\n renderedSearch\n )\n\n return navigateToSeededRoute(\n now,\n url,\n createHrefFromUrl(canonicalUrl),\n navigationSeed,\n currentUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n shouldScroll\n )\n}\n\nexport type NavigationSeed = {\n tree: FlightRouterState\n renderedSearch: string\n data: CacheNodeSeedData | null\n head: HeadData | null\n}\n\nexport function convertServerPatchToFullTree(\n currentTree: FlightRouterState,\n flightData: Array<NormalizedFlightData>,\n renderedSearch: string\n): NavigationSeed {\n // During a client navigation or prefetch, the server sends back only a patch\n // for the parts of the tree that have changed.\n //\n // This applies the patch to the base tree to create a full representation of\n // the resulting tree.\n //\n // The return type includes a full FlightRouterState tree and a full\n // CacheNodeSeedData tree. (Conceptually these are the same tree, and should\n // eventually be unified, but there's still lots of existing code that\n // operates on FlightRouterState trees alone without the CacheNodeSeedData.)\n //\n // TODO: This similar to what apply-router-state-patch-to-tree does. It\n // will eventually fully replace it. We should get rid of all the remaining\n // places where we iterate over the server patch format. This should also\n // eventually replace normalizeFlightData.\n\n let baseTree: FlightRouterState = currentTree\n let baseData: CacheNodeSeedData | null = null\n let head: HeadData | null = null\n for (const {\n segmentPath,\n tree: treePatch,\n seedData: dataPatch,\n head: headPatch,\n } of flightData) {\n const result = convertServerPatchToFullTreeImpl(\n baseTree,\n baseData,\n treePatch,\n dataPatch,\n segmentPath,\n 0\n )\n baseTree = result.tree\n baseData = result.data\n // This is the same for all patches per response, so just pick an\n // arbitrary one\n head = headPatch\n }\n\n return {\n tree: baseTree,\n data: baseData,\n renderedSearch,\n head,\n }\n}\n\nfunction convertServerPatchToFullTreeImpl(\n baseRouterState: FlightRouterState,\n baseData: CacheNodeSeedData | null,\n treePatch: FlightRouterState,\n dataPatch: CacheNodeSeedData | null,\n segmentPath: FlightSegmentPath,\n index: number\n): { tree: FlightRouterState; data: CacheNodeSeedData | null } {\n if (index === segmentPath.length) {\n // We reached the part of the tree that we need to patch.\n return {\n tree: treePatch,\n data: dataPatch,\n }\n }\n\n // segmentPath represents the parent path of subtree. It's a repeating\n // pattern of parallel route key and segment:\n //\n // [string, Segment, string, Segment, string, Segment, ...]\n //\n // This path tells us which part of the base tree to apply the tree patch.\n //\n // NOTE: We receive the FlightRouterState patch in the same request as the\n // seed data patch. Therefore we don't need to worry about diffing the segment\n // values; we can assume the server sent us a correct result.\n const updatedParallelRouteKey: string = segmentPath[index]\n // const segment: Segment = segmentPath[index + 1] <-- Not used, see note above\n\n const baseTreeChildren = baseRouterState[1]\n const baseSeedDataChildren = baseData !== null ? baseData[1] : null\n const newTreeChildren: Record<string, FlightRouterState> = {}\n const newSeedDataChildren: Record<string, CacheNodeSeedData | null> = {}\n for (const parallelRouteKey in baseTreeChildren) {\n const childBaseRouterState = baseTreeChildren[parallelRouteKey]\n const childBaseSeedData =\n baseSeedDataChildren !== null\n ? (baseSeedDataChildren[parallelRouteKey] ?? null)\n : null\n if (parallelRouteKey === updatedParallelRouteKey) {\n const result = convertServerPatchToFullTreeImpl(\n childBaseRouterState,\n childBaseSeedData,\n treePatch,\n dataPatch,\n segmentPath,\n // Advance the index by two and keep cloning until we reach\n // the end of the segment path.\n index + 2\n )\n\n newTreeChildren[parallelRouteKey] = result.tree\n newSeedDataChildren[parallelRouteKey] = result.data\n } else {\n // This child is not being patched. Copy it over as-is.\n newTreeChildren[parallelRouteKey] = childBaseRouterState\n newSeedDataChildren[parallelRouteKey] = childBaseSeedData\n }\n }\n\n let clonedTree: FlightRouterState\n let clonedSeedData: CacheNodeSeedData\n // Clone all the fields except the children.\n\n // Clone the FlightRouterState tree. Based on equivalent logic in\n // apply-router-state-patch-to-tree, but should confirm whether we need to\n // copy all of these fields. Not sure the server ever sends, e.g. the\n // refetch marker.\n clonedTree = [baseRouterState[0], newTreeChildren]\n if (2 in baseRouterState) {\n clonedTree[2] = baseRouterState[2]\n }\n if (3 in baseRouterState) {\n clonedTree[3] = baseRouterState[3]\n }\n if (4 in baseRouterState) {\n clonedTree[4] = baseRouterState[4]\n }\n\n // Clone the CacheNodeSeedData tree.\n const isEmptySeedDataPartial = true\n clonedSeedData = [\n null,\n newSeedDataChildren,\n null,\n isEmptySeedDataPartial,\n false,\n ]\n\n return {\n tree: clonedTree,\n data: clonedSeedData,\n }\n}\n","import type {\n FlightRouterState,\n FlightSegmentPath,\n} from '../../../../shared/lib/app-router-types'\nimport { createHrefFromUrl } from '../create-href-from-url'\nimport type {\n Mutable,\n NavigateAction,\n ReadonlyReducerState,\n ReducerState,\n} from '../router-reducer-types'\nimport { handleMutable } from '../handle-mutable'\n\nimport {\n navigate as navigateUsingSegmentCache,\n type NavigationResult,\n} from '../../segment-cache/navigation'\nimport { NavigationResultTag } from '../../segment-cache/types'\nimport { getStaleTimeMs } from '../../segment-cache/cache'\nimport { FreshnessPolicy } from '../ppr-navigations'\n\n// These values are set by `define-env-plugin` (based on `nextConfig.experimental.staleTimes`)\n// and default to 5 minutes (static) / 0 seconds (dynamic)\nexport const DYNAMIC_STALETIME_MS =\n Number(process.env.__NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME) * 1000\n\nexport const STATIC_STALETIME_MS = getStaleTimeMs(\n Number(process.env.__NEXT_CLIENT_ROUTER_STATIC_STALETIME)\n)\n\nexport function handleExternalUrl(\n state: ReadonlyReducerState,\n mutable: Mutable,\n url: string,\n pendingPush: boolean\n) {\n mutable.mpaNavigation = true\n mutable.canonicalUrl = url\n mutable.pendingPush = pendingPush\n mutable.scrollableSegments = undefined\n\n return handleMutable(state, mutable)\n}\n\nexport function generateSegmentsFromPatch(\n flightRouterPatch: FlightRouterState\n): FlightSegmentPath[] {\n const segments: FlightSegmentPath[] = []\n const [segment, parallelRoutes] = flightRouterPatch\n\n if (Object.keys(parallelRoutes).length === 0) {\n return [[segment]]\n }\n\n for (const [parallelRouteKey, parallelRoute] of Object.entries(\n parallelRoutes\n )) {\n for (const childSegment of generateSegmentsFromPatch(parallelRoute)) {\n // If the segment is empty, it means we are at the root of the tree\n if (segment === '') {\n segments.push([parallelRouteKey, ...childSegment])\n } else {\n segments.push([segment, parallelRouteKey, ...childSegment])\n }\n }\n }\n\n return segments\n}\n\nexport function handleNavigationResult(\n url: URL,\n state: ReadonlyReducerState,\n mutable: Mutable,\n pendingPush: boolean,\n result: NavigationResult\n): ReducerState {\n switch (result.tag) {\n case NavigationResultTag.MPA: {\n // Perform an MPA navigation.\n const newUrl = result.data\n return handleExternalUrl(state, mutable, newUrl, pendingPush)\n }\n case NavigationResultTag.Success: {\n // Received a new result.\n mutable.cache = result.data.cacheNode\n mutable.patchedTree = result.data.flightRouterState\n mutable.renderedSearch = result.data.renderedSearch\n mutable.canonicalUrl = result.data.canonicalUrl\n // TODO: During a refresh, we don't set the `scrollableSegments`. There's\n // some confusing and subtle logic in `handleMutable` that decides what\n // to do when `shouldScroll` is set but `scrollableSegments` is not. I'm\n // not convinced it's totally coherent but the tests assert on this\n // particular behavior so I've ported the logic as-is from the previous\n // router implementation, for now.\n mutable.scrollableSegments = result.data.scrollableSegments ?? undefined\n mutable.shouldScroll = result.data.shouldScroll\n mutable.hashFragment = result.data.hash\n\n // Check if the only thing that changed was the hash fragment.\n const oldUrl = new URL(state.canonicalUrl, url)\n const onlyHashChange =\n // We don't need to compare the origins, because client-driven\n // navigations are always same-origin.\n url.pathname === oldUrl.pathname &&\n url.search === oldUrl.search &&\n url.hash !== oldUrl.hash\n if (onlyHashChange) {\n // The only updated part of the URL is the hash.\n mutable.onlyHashChange = true\n mutable.shouldScroll = result.data.shouldScroll\n mutable.hashFragment = url.hash\n // Setting this to an empty array triggers a scroll for all new and\n // updated segments. See `ScrollAndFocusHandler` for more details.\n mutable.scrollableSegments = []\n }\n\n return handleMutable(state, mutable)\n }\n case NavigationResultTag.Async: {\n return result.data.then(\n (asyncResult) =>\n handleNavigationResult(url, state, mutable, pendingPush, asyncResult),\n // If the navigation failed, return the current state.\n // TODO: This matches the current behavior but we need to do something\n // better here if the network fails.\n () => {\n return state\n }\n )\n }\n default: {\n result satisfies never\n return state\n }\n }\n}\n\nexport function navigateReducer(\n state: ReadonlyReducerState,\n action: NavigateAction\n): ReducerState {\n const { url, isExternalUrl, navigateType, shouldScroll } = action\n const mutable: Mutable = {}\n const href = createHrefFromUrl(url)\n const pendingPush = navigateType === 'push'\n\n mutable.preserveCustomHistoryState = false\n mutable.pendingPush = pendingPush\n\n if (isExternalUrl) {\n return handleExternalUrl(state, mutable, url.toString(), pendingPush)\n }\n\n // Handles case where `<meta http-equiv=\"refresh\">` tag is present,\n // which will trigger an MPA navigation.\n if (document.getElementById('__next-page-redirect')) {\n return handleExternalUrl(state, mutable, href, pendingPush)\n }\n\n // Temporary glue code between the router reducer and the new navigation\n // implementation. Eventually we'll rewrite the router reducer to a\n // state machine.\n const currentUrl = new URL(state.canonicalUrl, location.origin)\n const result = navigateUsingSegmentCache(\n url,\n currentUrl,\n state.cache,\n state.tree,\n state.nextUrl,\n FreshnessPolicy.Default,\n shouldScroll,\n mutable\n )\n return handleNavigationResult(url, state, mutable, pendingPush, result)\n}\n","export function createPromiseWithResolvers<T>(): PromiseWithResolvers<T> {\n // Shim of Stage 4 Promise.withResolvers proposal\n let resolve: (value: T | PromiseLike<T>) => void\n let reject: (reason: any) => void\n const promise = new Promise<T>((res, rej) => {\n resolve = res\n reject = rej\n })\n return { resolve: resolve!, reject: reject!, promise }\n}\n","import type {\n TreePrefetch,\n RootTreePrefetch,\n SegmentPrefetch,\n} from '../../../server/app-render/collect-segment-data'\nimport type { LoadingModuleData } from '../../../shared/lib/app-router-types'\nimport type {\n CacheNodeSeedData,\n Segment as FlightRouterStateSegment,\n} from '../../../shared/lib/app-router-types'\nimport { HasLoadingBoundary } from '../../../shared/lib/app-router-types'\nimport {\n NEXT_DID_POSTPONE_HEADER,\n NEXT_ROUTER_PREFETCH_HEADER,\n NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n NEXT_ROUTER_STALE_TIME_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_URL,\n RSC_CONTENT_TYPE_HEADER,\n RSC_HEADER,\n} from '../app-router-headers'\nimport {\n createFetch,\n createFromNextReadableStream,\n type RSCResponse,\n type RequestHeaders,\n} from '../router-reducer/fetch-server-response'\nimport {\n pingPrefetchTask,\n isPrefetchTaskDirty,\n type PrefetchTask,\n type PrefetchSubtaskResult,\n startRevalidationCooldown,\n} from './scheduler'\nimport {\n type RouteVaryPath,\n type SegmentVaryPath,\n type PartialSegmentVaryPath,\n getRouteVaryPath,\n getFulfilledRouteVaryPath,\n getSegmentVaryPathForRequest,\n appendLayoutVaryPath,\n finalizeLayoutVaryPath,\n finalizePageVaryPath,\n clonePageVaryPathWithNewSearchParams,\n type PageVaryPath,\n finalizeMetadataVaryPath,\n} from './vary-path'\nimport { getAppBuildId } from '../../app-build-id'\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url'\nimport type { NormalizedSearch, RouteCacheKey } from './cache-key'\n// TODO: Rename this module to avoid confusion with other types of cache keys\nimport { createCacheKey as createPrefetchRequestKey } from './cache-key'\nimport {\n doesStaticSegmentAppearInURL,\n getCacheKeyForDynamicParam,\n getRenderedPathname,\n getRenderedSearch,\n parseDynamicParamFromURLPart,\n} from '../../route-params'\nimport {\n createCacheMap,\n getFromCacheMap,\n setInCacheMap,\n setSizeInCacheMap,\n deleteFromCacheMap,\n isValueExpired,\n type CacheMap,\n type UnknownMapEntry,\n} from './cache-map'\nimport {\n appendSegmentRequestKeyPart,\n convertSegmentPathToStaticExportFilename,\n createSegmentRequestKeyPart,\n HEAD_REQUEST_KEY,\n ROOT_SEGMENT_REQUEST_KEY,\n type SegmentRequestKey,\n} from '../../../shared/lib/segment-cache/segment-value-encoding'\nimport type {\n FlightRouterState,\n NavigationFlightResponse,\n} from '../../../shared/lib/app-router-types'\nimport {\n normalizeFlightData,\n prepareFlightRouterStateForRequest,\n} from '../../flight-data-helpers'\nimport { STATIC_STALETIME_MS } from '../router-reducer/reducers/navigate-reducer'\nimport { pingVisibleLinks } from '../links'\nimport { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'\nimport { FetchStrategy } from './types'\nimport { createPromiseWithResolvers } from '../../../shared/lib/promise-with-resolvers'\n\n/**\n * Ensures a minimum stale time of 30s to avoid issues where the server sends a too\n * short-lived stale time, which would prevent anything from being prefetched.\n */\nexport function getStaleTimeMs(staleTimeSeconds: number): number {\n return Math.max(staleTimeSeconds, 30) * 1000\n}\n\n// A note on async/await when working in the prefetch cache:\n//\n// Most async operations in the prefetch cache should *not* use async/await,\n// Instead, spawn a subtask that writes the results to a cache entry, and attach\n// a \"ping\" listener to notify the prefetch queue to try again.\n//\n// The reason is we need to be able to access the segment cache and traverse its\n// data structures synchronously. For example, if there's a synchronous update\n// we can take an immediate snapshot of the cache to produce something we can\n// render. Limiting the use of async/await also makes it easier to avoid race\n// conditions, which is especially important because is cache is mutable.\n//\n// Another reason is that while we're performing async work, it's possible for\n// existing entries to become stale, or for Link prefetches to be removed from\n// the queue. For optimal scheduling, we need to be able to \"cancel\" subtasks\n// that are no longer needed. So, when a segment is received from the server, we\n// restart from the root of the tree that's being prefetched, to confirm all the\n// parent segments are still cached. If the segment is no longer reachable from\n// the root, then it's effectively canceled. This is similar to the design of\n// Rust Futures, or React Suspense.\n\ntype RouteTreeShared = {\n requestKey: SegmentRequestKey\n // TODO: Remove the `segment` field, now that it can be reconstructed\n // from `param`.\n segment: FlightRouterStateSegment\n slots: null | {\n [parallelRouteKey: string]: RouteTree\n }\n isRootLayout: boolean\n\n // If this is a dynamic route, indicates whether there is a loading boundary\n // somewhere in the tree. If not, we can skip the prefetch for the data,\n // because we know it would be an empty response. (For a static/PPR route,\n // this value is disregarded, because in that model `loading.tsx` is treated\n // like any other Suspense boundary.)\n hasLoadingBoundary: HasLoadingBoundary\n\n // Indicates whether this route has a runtime prefetch that we can request.\n // This is determined by the server; it's not purely a user configuration\n // because the server may determine that a route is fully static and doesn't\n // need runtime prefetching regardless of the configuration.\n hasRuntimePrefetch: boolean\n}\n\ntype LayoutRouteTree = RouteTreeShared & {\n isPage: false\n varyPath: SegmentVaryPath\n}\n\ntype PageRouteTree = RouteTreeShared & {\n isPage: true\n varyPath: PageVaryPath\n}\n\nexport type RouteTree = LayoutRouteTree | PageRouteTree\n\ntype RouteCacheEntryShared = {\n // This is false only if we're certain the route cannot be intercepted. It's\n // true in all other cases, including on initialization when we haven't yet\n // received a response from the server.\n couldBeIntercepted: boolean\n\n // Map-related fields.\n ref: UnknownMapEntry | null\n size: number\n staleAt: number\n version: number\n}\n\n/**\n * Tracks the status of a cache entry as it progresses from no data (Empty),\n * waiting for server data (Pending), and finished (either Fulfilled or\n * Rejected depending on the response from the server.\n */\nexport const enum EntryStatus {\n Empty = 0,\n Pending = 1,\n Fulfilled = 2,\n Rejected = 3,\n}\n\ntype PendingRouteCacheEntry = RouteCacheEntryShared & {\n status: EntryStatus.Empty | EntryStatus.Pending\n blockedTasks: Set<PrefetchTask> | null\n canonicalUrl: null\n renderedSearch: null\n tree: null\n metadata: null\n isPPREnabled: false\n}\n\ntype RejectedRouteCacheEntry = RouteCacheEntryShared & {\n status: EntryStatus.Rejected\n blockedTasks: Set<PrefetchTask> | null\n canonicalUrl: null\n renderedSearch: null\n tree: null\n metadata: null\n isPPREnabled: boolean\n}\n\nexport type FulfilledRouteCacheEntry = RouteCacheEntryShared & {\n status: EntryStatus.Fulfilled\n blockedTasks: null\n canonicalUrl: string\n renderedSearch: NormalizedSearch\n tree: RouteTree\n metadata: RouteTree\n isPPREnabled: boolean\n}\n\nexport type RouteCacheEntry =\n | PendingRouteCacheEntry\n | FulfilledRouteCacheEntry\n | RejectedRouteCacheEntry\n\ntype SegmentCacheEntryShared = {\n fetchStrategy: FetchStrategy\n\n // Map-related fields.\n ref: UnknownMapEntry | null\n size: number\n staleAt: number\n version: number\n}\n\nexport type EmptySegmentCacheEntry = SegmentCacheEntryShared & {\n status: EntryStatus.Empty\n rsc: null\n loading: null\n isPartial: true\n promise: null\n}\n\nexport type PendingSegmentCacheEntry = SegmentCacheEntryShared & {\n status: EntryStatus.Pending\n rsc: null\n loading: null\n isPartial: boolean\n promise: null | PromiseWithResolvers<FulfilledSegmentCacheEntry | null>\n}\n\ntype RejectedSegmentCacheEntry = SegmentCacheEntryShared & {\n status: EntryStatus.Rejected\n rsc: null\n loading: null\n isPartial: true\n promise: null\n}\n\nexport type FulfilledSegmentCacheEntry = SegmentCacheEntryShared & {\n status: EntryStatus.Fulfilled\n rsc: React.ReactNode | null\n loading: LoadingModuleData | Promise<LoadingModuleData>\n isPartial: boolean\n promise: null\n}\n\nexport type SegmentCacheEntry =\n | EmptySegmentCacheEntry\n | PendingSegmentCacheEntry\n | RejectedSegmentCacheEntry\n | FulfilledSegmentCacheEntry\n\nexport type NonEmptySegmentCacheEntry = Exclude<\n SegmentCacheEntry,\n EmptySegmentCacheEntry\n>\n\nconst isOutputExportMode =\n process.env.NODE_ENV === 'production' &&\n process.env.__NEXT_CONFIG_OUTPUT === 'export'\n\nconst MetadataOnlyRequestTree: FlightRouterState = [\n '',\n {},\n null,\n 'metadata-only',\n]\n\nlet routeCacheMap: CacheMap<RouteCacheEntry> = createCacheMap()\nlet segmentCacheMap: CacheMap<SegmentCacheEntry> = createCacheMap()\n\n// All invalidation listeners for the whole cache are tracked in single set.\n// Since we don't yet support tag or path-based invalidation, there's no point\n// tracking them any more granularly than this. Once we add granular\n// invalidation, that may change, though generally the model is to just notify\n// the listeners and allow the caller to poll the prefetch cache with a new\n// prefetch task if desired.\nlet invalidationListeners: Set<PrefetchTask> | null = null\n\n// Incrementing counter used to track cache invalidations.\nlet currentCacheVersion = 0\n\nexport function getCurrentCacheVersion(): number {\n return currentCacheVersion\n}\n\n/**\n * Used to clear the client prefetch cache when a server action calls\n * revalidatePath or revalidateTag. Eventually we will support only clearing the\n * segments that were actually affected, but there's more work to be done on the\n * server before the client is able to do this correctly.\n */\nexport function revalidateEntireCache(\n nextUrl: string | null,\n tree: FlightRouterState\n) {\n // Increment the current cache version. This does not eagerly evict anything\n // from the cache, but because all the entries are versioned, and we check\n // the version when reading from the cache, this effectively causes all\n // entries to be evicted lazily. We do it lazily because in the future,\n // actions like revalidateTag or refresh will not evict the entire cache,\n // but rather some subset of the entries.\n currentCacheVersion++\n\n // Start a cooldown before re-prefetching to allow CDN cache propagation.\n startRevalidationCooldown()\n\n // Prefetch all the currently visible links again, to re-fill the cache.\n pingVisibleLinks(nextUrl, tree)\n\n // Similarly, notify all invalidation listeners (i.e. those passed to\n // `router.prefetch(onInvalidate)`), so they can trigger a new prefetch\n // if needed.\n pingInvalidationListeners(nextUrl, tree)\n}\n\nfunction attachInvalidationListener(task: PrefetchTask): void {\n // This function is called whenever a prefetch task reads a cache entry. If\n // the task has an onInvalidate function associated with it — i.e. the one\n // optionally passed to router.prefetch(onInvalidate) — then we attach that\n // listener to the every cache entry that the task reads. Then, if an entry\n // is invalidated, we call the function.\n if (task.onInvalidate !== null) {\n if (invalidationListeners === null) {\n invalidationListeners = new Set([task])\n } else {\n invalidationListeners.add(task)\n }\n }\n}\n\nfunction notifyInvalidationListener(task: PrefetchTask): void {\n const onInvalidate = task.onInvalidate\n if (onInvalidate !== null) {\n // Clear the callback from the task object to guarantee it's not called more\n // than once.\n task.onInvalidate = null\n\n // This is a user-space function, so we must wrap in try/catch.\n try {\n onInvalidate()\n } catch (error) {\n if (typeof reportError === 'function') {\n reportError(error)\n } else {\n console.error(error)\n }\n }\n }\n}\n\nexport function pingInvalidationListeners(\n nextUrl: string | null,\n tree: FlightRouterState\n): void {\n // The rough equivalent of pingVisibleLinks, but for onInvalidate callbacks.\n // This is called when the Next-Url or the base tree changes, since those\n // may affect the result of a prefetch task. It's also called after a\n // cache invalidation.\n if (invalidationListeners !== null) {\n const tasks = invalidationListeners\n invalidationListeners = null\n for (const task of tasks) {\n if (isPrefetchTaskDirty(task, nextUrl, tree)) {\n notifyInvalidationListener(task)\n }\n }\n }\n}\n\nexport function readRouteCacheEntry(\n now: number,\n key: RouteCacheKey\n): RouteCacheEntry | null {\n const varyPath: RouteVaryPath = getRouteVaryPath(\n key.pathname,\n key.search,\n key.nextUrl\n )\n const isRevalidation = false\n return getFromCacheMap(\n now,\n getCurrentCacheVersion(),\n routeCacheMap,\n varyPath,\n isRevalidation\n )\n}\n\nexport function readSegmentCacheEntry(\n now: number,\n varyPath: SegmentVaryPath\n): SegmentCacheEntry | null {\n const isRevalidation = false\n return getFromCacheMap(\n now,\n getCurrentCacheVersion(),\n segmentCacheMap,\n varyPath,\n isRevalidation\n )\n}\n\nfunction readRevalidatingSegmentCacheEntry(\n now: number,\n varyPath: SegmentVaryPath\n): SegmentCacheEntry | null {\n const isRevalidation = true\n return getFromCacheMap(\n now,\n getCurrentCacheVersion(),\n segmentCacheMap,\n varyPath,\n isRevalidation\n )\n}\n\nexport function waitForSegmentCacheEntry(\n pendingEntry: PendingSegmentCacheEntry\n): Promise<FulfilledSegmentCacheEntry | null> {\n // Because the entry is pending, there's already a in-progress request.\n // Attach a promise to the entry that will resolve when the server responds.\n let promiseWithResolvers = pendingEntry.promise\n if (promiseWithResolvers === null) {\n promiseWithResolvers = pendingEntry.promise =\n createPromiseWithResolvers<FulfilledSegmentCacheEntry | null>()\n } else {\n // There's already a promise we can use\n }\n return promiseWithResolvers.promise\n}\n\n/**\n * Checks if an entry for a route exists in the cache. If so, it returns the\n * entry, If not, it adds an empty entry to the cache and returns it.\n */\nexport function readOrCreateRouteCacheEntry(\n now: number,\n task: PrefetchTask,\n key: RouteCacheKey\n): RouteCacheEntry {\n attachInvalidationListener(task)\n\n const existingEntry = readRouteCacheEntry(now, key)\n if (existingEntry !== null) {\n return existingEntry\n }\n // Create a pending entry and add it to the cache.\n const pendingEntry: PendingRouteCacheEntry = {\n canonicalUrl: null,\n status: EntryStatus.Empty,\n blockedTasks: null,\n tree: null,\n metadata: null,\n // This is initialized to true because we don't know yet whether the route\n // could be intercepted. It's only set to false once we receive a response\n // from the server.\n couldBeIntercepted: true,\n // Similarly, we don't yet know if the route supports PPR.\n isPPREnabled: false,\n renderedSearch: null,\n\n // Map-related fields\n ref: null,\n size: 0,\n // Since this is an empty entry, there's no reason to ever evict it. It will\n // be updated when the data is populated.\n staleAt: Infinity,\n version: getCurrentCacheVersion(),\n }\n const varyPath: RouteVaryPath = getRouteVaryPath(\n key.pathname,\n key.search,\n key.nextUrl\n )\n const isRevalidation = false\n setInCacheMap(routeCacheMap, varyPath, pendingEntry, isRevalidation)\n return pendingEntry\n}\n\nexport function requestOptimisticRouteCacheEntry(\n now: number,\n requestedUrl: URL,\n nextUrl: string | null\n): FulfilledRouteCacheEntry | null {\n // This function is called during a navigation when there was no matching\n // route tree in the prefetch cache. Before de-opting to a blocking,\n // unprefetched navigation, we will first attempt to construct an \"optimistic\"\n // route tree by checking the cache for similar routes.\n //\n // Check if there's a route with the same pathname, but with different\n // search params. We can then base our optimistic route tree on this entry.\n //\n // Conceptually, we are simulating what would happen if we did perform a\n // prefetch the requested URL, under the assumption that the server will\n // not redirect or rewrite the request in a different manner than the\n // base route tree. This assumption might not hold, in which case we'll have\n // to recover when we perform the dynamic navigation request. However, this\n // is what would happen if a route were dynamically rewritten/redirected\n // in between the prefetch and the navigation. So the logic needs to exist\n // to handle this case regardless.\n\n // Look for a route with the same pathname, but with an empty search string.\n // TODO: There's nothing inherently special about the empty search string;\n // it's chosen somewhat arbitrarily, with the rationale that it's the most\n // likely one to exist. But we should update this to match _any_ search\n // string. The plan is to generalize this logic alongside other improvements\n // related to \"fallback\" cache entries.\n const requestedSearch = requestedUrl.search as NormalizedSearch\n if (requestedSearch === '') {\n // The caller would have already checked if a route with an empty search\n // string is in the cache. So we can bail out here.\n return null\n }\n const urlWithoutSearchParams = new URL(requestedUrl)\n urlWithoutSearchParams.search = ''\n const routeWithNoSearchParams = readRouteCacheEntry(\n now,\n createPrefetchRequestKey(urlWithoutSearchParams.href, nextUrl)\n )\n\n if (\n routeWithNoSearchParams === null ||\n routeWithNoSearchParams.status !== EntryStatus.Fulfilled\n ) {\n // Bail out of constructing an optimistic route tree. This will result in\n // a blocking, unprefetched navigation.\n return null\n }\n\n // Now we have a base route tree we can \"patch\" with our optimistic values.\n\n // Optimistically assume that redirects for the requested pathname do\n // not vary on the search string. Therefore, if the base route was\n // redirected to a different search string, then the optimistic route\n // should be redirected to the same search string. Otherwise, we use\n // the requested search string.\n const canonicalUrlForRouteWithNoSearchParams = new URL(\n routeWithNoSearchParams.canonicalUrl,\n requestedUrl.origin\n )\n const optimisticCanonicalSearch =\n canonicalUrlForRouteWithNoSearchParams.search !== ''\n ? // Base route was redirected. Reuse the same redirected search string.\n canonicalUrlForRouteWithNoSearchParams.search\n : requestedSearch\n\n // Similarly, optimistically assume that rewrites for the requested\n // pathname do not vary on the search string. Therefore, if the base\n // route was rewritten to a different search string, then the optimistic\n // route should be rewritten to the same search string. Otherwise, we use\n // the requested search string.\n const optimisticRenderedSearch =\n routeWithNoSearchParams.renderedSearch !== ''\n ? // Base route was rewritten. Reuse the same rewritten search string.\n routeWithNoSearchParams.renderedSearch\n : requestedSearch\n\n const optimisticUrl = new URL(\n routeWithNoSearchParams.canonicalUrl,\n location.origin\n )\n optimisticUrl.search = optimisticCanonicalSearch\n const optimisticCanonicalUrl = createHrefFromUrl(optimisticUrl)\n\n const optimisticRouteTree = createOptimisticRouteTree(\n routeWithNoSearchParams.tree,\n optimisticRenderedSearch\n )\n const optimisticMetadataTree = createOptimisticRouteTree(\n routeWithNoSearchParams.metadata,\n optimisticRenderedSearch\n )\n\n // Clone the base route tree, and override the relevant fields with our\n // optimistic values.\n const optimisticEntry: FulfilledRouteCacheEntry = {\n canonicalUrl: optimisticCanonicalUrl,\n\n status: EntryStatus.Fulfilled,\n // This isn't cloned because it's instance-specific\n blockedTasks: null,\n tree: optimisticRouteTree,\n metadata: optimisticMetadataTree,\n couldBeIntercepted: routeWithNoSearchParams.couldBeIntercepted,\n isPPREnabled: routeWithNoSearchParams.isPPREnabled,\n\n // Override the rendered search with the optimistic value.\n renderedSearch: optimisticRenderedSearch,\n\n // Map-related fields\n ref: null,\n size: 0,\n staleAt: routeWithNoSearchParams.staleAt,\n version: routeWithNoSearchParams.version,\n }\n\n // Do not insert this entry into the cache. It only exists so we can\n // perform the current navigation. Just return it to the caller.\n return optimisticEntry\n}\n\nfunction createOptimisticRouteTree(\n tree: RouteTree,\n newRenderedSearch: NormalizedSearch\n): RouteTree {\n // Create a new route tree that identical to the original one except for\n // the rendered search string, which is contained in the vary path.\n\n let clonedSlots: Record<string, RouteTree> | null = null\n const originalSlots = tree.slots\n if (originalSlots !== null) {\n clonedSlots = {}\n for (const parallelRouteKey in originalSlots) {\n const childTree = originalSlots[parallelRouteKey]\n clonedSlots[parallelRouteKey] = createOptimisticRouteTree(\n childTree,\n newRenderedSearch\n )\n }\n }\n\n // We only need to clone the vary path if the route is a page.\n if (tree.isPage) {\n return {\n requestKey: tree.requestKey,\n segment: tree.segment,\n varyPath: clonePageVaryPathWithNewSearchParams(\n tree.varyPath,\n newRenderedSearch\n ),\n isPage: true,\n slots: clonedSlots,\n isRootLayout: tree.isRootLayout,\n hasLoadingBoundary: tree.hasLoadingBoundary,\n hasRuntimePrefetch: tree.hasRuntimePrefetch,\n }\n }\n\n return {\n requestKey: tree.requestKey,\n segment: tree.segment,\n varyPath: tree.varyPath,\n isPage: false,\n slots: clonedSlots,\n isRootLayout: tree.isRootLayout,\n hasLoadingBoundary: tree.hasLoadingBoundary,\n hasRuntimePrefetch: tree.hasRuntimePrefetch,\n }\n}\n\n/**\n * Checks if an entry for a segment exists in the cache. If so, it returns the\n * entry, If not, it adds an empty entry to the cache and returns it.\n */\nexport function readOrCreateSegmentCacheEntry(\n now: number,\n fetchStrategy: FetchStrategy,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree\n): SegmentCacheEntry {\n const existingEntry = readSegmentCacheEntry(now, tree.varyPath)\n if (existingEntry !== null) {\n return existingEntry\n }\n // Create a pending entry and add it to the cache.\n const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)\n const pendingEntry = createDetachedSegmentCacheEntry(route.staleAt)\n const isRevalidation = false\n setInCacheMap(\n segmentCacheMap,\n varyPathForRequest,\n pendingEntry,\n isRevalidation\n )\n return pendingEntry\n}\n\nexport function readOrCreateRevalidatingSegmentEntry(\n now: number,\n fetchStrategy: FetchStrategy,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree\n): SegmentCacheEntry {\n // This function is called when we've already confirmed that a particular\n // segment is cached, but we want to perform another request anyway in case it\n // returns more complete and/or fresher data than we already have. The logic\n // for deciding whether to replace the existing entry is handled elsewhere;\n // this function just handles retrieving a cache entry that we can use to\n // track the revalidation.\n //\n // The reason revalidations are stored in the cache is because we need to be\n // able to dedupe multiple revalidation requests. The reason they have to be\n // handled specially is because we shouldn't overwrite a \"normal\" entry if\n // one exists at the same keypath. So, for each internal cache location, there\n // is a special \"revalidation\" slot that is used solely for this purpose.\n //\n // You can think of it as if all the revalidation entries were stored in a\n // separate cache map from the canonical entries, and then transfered to the\n // canonical cache map once the request is complete — this isn't how it's\n // actually implemented, since it's more efficient to store them in the same\n // data structure as the normal entries, but that's how it's modeled\n // conceptually.\n\n // TODO: Once we implement Fallback behavior for params, where an entry is\n // re-keyed based on response information, we'll need to account for the\n // possibility that the keypath of the previous entry is more generic than\n // the keypath of the revalidating entry. In other words, the server could\n // return a less generic entry upon revalidation. For now, though, this isn't\n // a concern because the keypath is based solely on the prefetch strategy,\n // not on data contained in the response.\n const existingEntry = readRevalidatingSegmentCacheEntry(now, tree.varyPath)\n if (existingEntry !== null) {\n return existingEntry\n }\n // Create a pending entry and add it to the cache.\n const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)\n const pendingEntry = createDetachedSegmentCacheEntry(route.staleAt)\n const isRevalidation = true\n setInCacheMap(\n segmentCacheMap,\n varyPathForRequest,\n pendingEntry,\n isRevalidation\n )\n return pendingEntry\n}\n\nexport function overwriteRevalidatingSegmentCacheEntry(\n fetchStrategy: FetchStrategy,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree\n) {\n // This function is called when we've already decided to replace an existing\n // revalidation entry. Create a new entry and write it into the cache,\n // overwriting the previous value.\n const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)\n const pendingEntry = createDetachedSegmentCacheEntry(route.staleAt)\n const isRevalidation = true\n setInCacheMap(\n segmentCacheMap,\n varyPathForRequest,\n pendingEntry,\n isRevalidation\n )\n return pendingEntry\n}\n\nexport function upsertSegmentEntry(\n now: number,\n varyPath: SegmentVaryPath,\n candidateEntry: SegmentCacheEntry\n): SegmentCacheEntry | null {\n // We have a new entry that has not yet been inserted into the cache. Before\n // we do so, we need to confirm whether it takes precedence over the existing\n // entry (if one exists).\n // TODO: We should not upsert an entry if its key was invalidated in the time\n // since the request was made. We can do that by passing the \"owner\" entry to\n // this function and confirming it's the same as `existingEntry`.\n\n if (isValueExpired(now, getCurrentCacheVersion(), candidateEntry)) {\n // The entry is expired. We cannot upsert it.\n return null\n }\n\n const existingEntry = readSegmentCacheEntry(now, varyPath)\n if (existingEntry !== null) {\n // Don't replace a more specific segment with a less-specific one. A case where this\n // might happen is if the existing segment was fetched via\n // `<Link prefetch={true}>`.\n if (\n // We fetched the new segment using a different, less specific fetch strategy\n // than the segment we already have in the cache, so it can't have more content.\n (candidateEntry.fetchStrategy !== existingEntry.fetchStrategy &&\n !canNewFetchStrategyProvideMoreContent(\n existingEntry.fetchStrategy,\n candidateEntry.fetchStrategy\n )) ||\n // The existing entry isn't partial, but the new one is.\n // (TODO: can this be true if `candidateEntry.fetchStrategy >= existingEntry.fetchStrategy`?)\n (!existingEntry.isPartial && candidateEntry.isPartial)\n ) {\n // We're going to leave revalidating entry in the cache so that it doesn't\n // get revalidated again unnecessarily. Downgrade the Fulfilled entry to\n // Rejected and null out the data so it can be garbage collected. We leave\n // `staleAt` intact to prevent subsequent revalidation attempts only until\n // the entry expires.\n const rejectedEntry: RejectedSegmentCacheEntry = candidateEntry as any\n rejectedEntry.status = EntryStatus.Rejected\n rejectedEntry.loading = null\n rejectedEntry.rsc = null\n return null\n }\n\n // Evict the existing entry from the cache.\n deleteFromCacheMap(existingEntry)\n }\n\n const isRevalidation = false\n setInCacheMap(segmentCacheMap, varyPath, candidateEntry, isRevalidation)\n return candidateEntry\n}\n\nexport function createDetachedSegmentCacheEntry(\n staleAt: number\n): EmptySegmentCacheEntry {\n const emptyEntry: EmptySegmentCacheEntry = {\n status: EntryStatus.Empty,\n // Default to assuming the fetch strategy will be PPR. This will be updated\n // when a fetch is actually initiated.\n fetchStrategy: FetchStrategy.PPR,\n rsc: null,\n loading: null,\n isPartial: true,\n promise: null,\n\n // Map-related fields\n ref: null,\n size: 0,\n staleAt,\n version: 0,\n }\n return emptyEntry\n}\n\nexport function upgradeToPendingSegment(\n emptyEntry: EmptySegmentCacheEntry,\n fetchStrategy: FetchStrategy\n): PendingSegmentCacheEntry {\n const pendingEntry: PendingSegmentCacheEntry = emptyEntry as any\n pendingEntry.status = EntryStatus.Pending\n pendingEntry.fetchStrategy = fetchStrategy\n\n if (fetchStrategy === FetchStrategy.Full) {\n // We can assume the response will contain the full segment data. Set this\n // to false so we know it's OK to omit this segment from any navigation\n // requests that may happen while the data is still pending.\n pendingEntry.isPartial = false\n }\n\n // Set the version here, since this is right before the request is initiated.\n // The next time the global cache version is incremented, the entry will\n // effectively be evicted. This happens before initiating the request, rather\n // than when receiving the response, because it's guaranteed to happen\n // before the data is read on the server.\n pendingEntry.version = getCurrentCacheVersion()\n return pendingEntry\n}\n\nfunction pingBlockedTasks(entry: {\n blockedTasks: Set<PrefetchTask> | null\n}): void {\n const blockedTasks = entry.blockedTasks\n if (blockedTasks !== null) {\n for (const task of blockedTasks) {\n pingPrefetchTask(task)\n }\n entry.blockedTasks = null\n }\n}\n\nfunction fulfillRouteCacheEntry(\n entry: RouteCacheEntry,\n tree: RouteTree,\n metadataVaryPath: PageVaryPath,\n staleAt: number,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n renderedSearch: NormalizedSearch,\n isPPREnabled: boolean\n): FulfilledRouteCacheEntry {\n // The Head is not actually part of the route tree, but other than that, it's\n // fetched and cached like a segment. Some functions expect a RouteTree\n // object, so rather than fork the logic in all those places, we use this\n // \"fake\" one.\n const metadata: RouteTree = {\n requestKey: HEAD_REQUEST_KEY,\n segment: HEAD_REQUEST_KEY,\n varyPath: metadataVaryPath,\n // The metadata isn't really a \"page\" (though it isn't really a \"segment\"\n // either) but for the purposes of how this field is used, it behaves like\n // one. If this logic ever gets more complex we can change this to an enum.\n isPage: true,\n slots: null,\n isRootLayout: false,\n hasLoadingBoundary: HasLoadingBoundary.SubtreeHasNoLoadingBoundary,\n hasRuntimePrefetch: false,\n }\n const fulfilledEntry: FulfilledRouteCacheEntry = entry as any\n fulfilledEntry.status = EntryStatus.Fulfilled\n fulfilledEntry.tree = tree\n fulfilledEntry.metadata = metadata\n fulfilledEntry.staleAt = staleAt\n fulfilledEntry.couldBeIntercepted = couldBeIntercepted\n fulfilledEntry.canonicalUrl = canonicalUrl\n fulfilledEntry.renderedSearch = renderedSearch\n fulfilledEntry.isPPREnabled = isPPREnabled\n pingBlockedTasks(entry)\n return fulfilledEntry\n}\n\nfunction fulfillSegmentCacheEntry(\n segmentCacheEntry: PendingSegmentCacheEntry,\n rsc: React.ReactNode,\n loading: LoadingModuleData | Promise<LoadingModuleData>,\n staleAt: number,\n isPartial: boolean\n): FulfilledSegmentCacheEntry {\n const fulfilledEntry: FulfilledSegmentCacheEntry = segmentCacheEntry as any\n fulfilledEntry.status = EntryStatus.Fulfilled\n fulfilledEntry.rsc = rsc\n fulfilledEntry.loading = loading\n fulfilledEntry.staleAt = staleAt\n fulfilledEntry.isPartial = isPartial\n // Resolve any listeners that were waiting for this data.\n if (segmentCacheEntry.promise !== null) {\n segmentCacheEntry.promise.resolve(fulfilledEntry)\n // Free the promise for garbage collection.\n fulfilledEntry.promise = null\n }\n return fulfilledEntry\n}\n\nfunction rejectRouteCacheEntry(\n entry: PendingRouteCacheEntry,\n staleAt: number\n): void {\n const rejectedEntry: RejectedRouteCacheEntry = entry as any\n rejectedEntry.status = EntryStatus.Rejected\n rejectedEntry.staleAt = staleAt\n pingBlockedTasks(entry)\n}\n\nfunction rejectSegmentCacheEntry(\n entry: PendingSegmentCacheEntry,\n staleAt: number\n): void {\n const rejectedEntry: RejectedSegmentCacheEntry = entry as any\n rejectedEntry.status = EntryStatus.Rejected\n rejectedEntry.staleAt = staleAt\n if (entry.promise !== null) {\n // NOTE: We don't currently propagate the reason the prefetch was canceled\n // but we could by accepting a `reason` argument.\n entry.promise.resolve(null)\n entry.promise = null\n }\n}\n\ntype RouteTreeAccumulator = {\n metadataVaryPath: PageVaryPath | null\n}\n\nfunction convertRootTreePrefetchToRouteTree(\n rootTree: RootTreePrefetch,\n renderedPathname: string,\n renderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n) {\n // Remove trailing and leading slashes\n const pathnameParts = renderedPathname.split('/').filter((p) => p !== '')\n const index = 0\n const rootSegment = ROOT_SEGMENT_REQUEST_KEY\n return convertTreePrefetchToRouteTree(\n rootTree.tree,\n rootSegment,\n null,\n ROOT_SEGMENT_REQUEST_KEY,\n pathnameParts,\n index,\n renderedSearch,\n acc\n )\n}\n\nfunction convertTreePrefetchToRouteTree(\n prefetch: TreePrefetch,\n segment: FlightRouterStateSegment,\n partialVaryPath: PartialSegmentVaryPath | null,\n requestKey: SegmentRequestKey,\n pathnameParts: Array<string>,\n pathnamePartsIndex: number,\n renderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree {\n // Converts the route tree sent by the server into the format used by the\n // cache. The cached version of the tree includes additional fields, such as a\n // cache key for each segment. Since this is frequently accessed, we compute\n // it once instead of on every access. This same cache key is also used to\n // request the segment from the server.\n\n let slots: { [parallelRouteKey: string]: RouteTree } | null = null\n let isPage: boolean\n let varyPath: SegmentVaryPath\n const prefetchSlots = prefetch.slots\n if (prefetchSlots !== null) {\n isPage = false\n varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n\n slots = {}\n for (let parallelRouteKey in prefetchSlots) {\n const childPrefetch = prefetchSlots[parallelRouteKey]\n const childParamName = childPrefetch.name\n const childParamType = childPrefetch.paramType\n const childServerSentParamKey = childPrefetch.paramKey\n\n let childDoesAppearInURL: boolean\n let childSegment: FlightRouterStateSegment\n let childPartialVaryPath: PartialSegmentVaryPath | null\n if (childParamType !== null) {\n // This segment is parameterized. Get the param from the pathname.\n const childParamValue = parseDynamicParamFromURLPart(\n childParamType,\n pathnameParts,\n pathnamePartsIndex\n )\n\n // Assign a cache key to the segment, based on the param value. In the\n // pre-Segment Cache implementation, the server computes this and sends\n // it in the body of the response. In the Segment Cache implementation,\n // the server sends an empty string and we fill it in here.\n\n // TODO: We're intentionally not adding the search param to page\n // segments here; it's tracked separately and added back during a read.\n // This would clearer if we waited to construct the segment until it's\n // read from the cache, since that's effectively what we're\n // doing anyway.\n const childParamKey =\n // The server omits this field from the prefetch response when\n // cacheComponents is enabled.\n childServerSentParamKey !== null\n ? childServerSentParamKey\n : // If no param key was sent, use the value parsed on the client.\n getCacheKeyForDynamicParam(\n childParamValue,\n '' as NormalizedSearch\n )\n\n childPartialVaryPath = appendLayoutVaryPath(\n partialVaryPath,\n childParamKey\n )\n childSegment = [childParamName, childParamKey, childParamType]\n childDoesAppearInURL = true\n } else {\n // This segment does not have a param. Inherit the partial vary path of\n // the parent.\n childPartialVaryPath = partialVaryPath\n childSegment = childParamName\n childDoesAppearInURL = doesStaticSegmentAppearInURL(childParamName)\n }\n\n // Only increment the index if the segment appears in the URL. If it's a\n // \"virtual\" segment, like a route group, it remains the same.\n const childPathnamePartsIndex = childDoesAppearInURL\n ? pathnamePartsIndex + 1\n : pathnamePartsIndex\n\n const childRequestKeyPart = createSegmentRequestKeyPart(childSegment)\n const childRequestKey = appendSegmentRequestKeyPart(\n requestKey,\n parallelRouteKey,\n childRequestKeyPart\n )\n slots[parallelRouteKey] = convertTreePrefetchToRouteTree(\n childPrefetch,\n childSegment,\n childPartialVaryPath,\n childRequestKey,\n pathnameParts,\n childPathnamePartsIndex,\n renderedSearch,\n acc\n )\n }\n } else {\n if (requestKey.endsWith(PAGE_SEGMENT_KEY)) {\n // This is a page segment.\n isPage = true\n varyPath = finalizePageVaryPath(\n requestKey,\n renderedSearch,\n partialVaryPath\n )\n // The metadata \"segment\" is not part the route tree, but it has the same\n // conceptual params as a page segment. Write the vary path into the\n // accumulator object. If there are multiple parallel pages, we use the\n // first one. Which page we choose is arbitrary as long as it's\n // consistently the same one every time every time. See\n // finalizeMetadataVaryPath for more details.\n if (acc.metadataVaryPath === null) {\n acc.metadataVaryPath = finalizeMetadataVaryPath(\n requestKey,\n renderedSearch,\n partialVaryPath\n )\n }\n } else {\n // This is a layout segment.\n isPage = false\n varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n }\n }\n\n return {\n requestKey,\n segment,\n varyPath,\n // TODO: Cheating the type system here a bit because TypeScript can't tell\n // that the type of isPage and varyPath are consistent. The fix would be to\n // create separate constructors and call the appropriate one from each of\n // the branches above. Just seems a bit overkill only for one field so I'll\n // leave it as-is for now. If isPage were wrong it would break the behavior\n // and we'd catch it quickly, anyway.\n isPage: isPage as boolean as any,\n slots,\n isRootLayout: prefetch.isRootLayout,\n // This field is only relevant to dynamic routes. For a PPR/static route,\n // there's always some partial loading state we can fetch.\n hasLoadingBoundary: HasLoadingBoundary.SegmentHasLoadingBoundary,\n hasRuntimePrefetch: prefetch.hasRuntimePrefetch,\n }\n}\n\nfunction convertRootFlightRouterStateToRouteTree(\n flightRouterState: FlightRouterState,\n renderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree {\n return convertFlightRouterStateToRouteTree(\n flightRouterState,\n ROOT_SEGMENT_REQUEST_KEY,\n null,\n renderedSearch,\n acc\n )\n}\n\nfunction convertFlightRouterStateToRouteTree(\n flightRouterState: FlightRouterState,\n requestKey: SegmentRequestKey,\n parentPartialVaryPath: PartialSegmentVaryPath | null,\n renderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree {\n const originalSegment = flightRouterState[0]\n\n let segment: FlightRouterStateSegment\n let partialVaryPath: PartialSegmentVaryPath | null\n let isPage: boolean\n let varyPath: SegmentVaryPath\n if (Array.isArray(originalSegment)) {\n isPage = false\n const paramCacheKey = originalSegment[1]\n partialVaryPath = appendLayoutVaryPath(parentPartialVaryPath, paramCacheKey)\n varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n segment = originalSegment\n } else {\n // This segment does not have a param. Inherit the partial vary path of\n // the parent.\n partialVaryPath = parentPartialVaryPath\n if (requestKey.endsWith(PAGE_SEGMENT_KEY)) {\n // This is a page segment.\n isPage = true\n\n // The navigation implementation expects the search params to be included\n // in the segment. However, in the case of a static response, the search\n // params are omitted. So the client needs to add them back in when reading\n // from the Segment Cache.\n //\n // For consistency, we'll do this for dynamic responses, too.\n //\n // TODO: We should move search params out of FlightRouterState and handle\n // them entirely on the client, similar to our plan for dynamic params.\n segment = PAGE_SEGMENT_KEY\n varyPath = finalizePageVaryPath(\n requestKey,\n renderedSearch,\n partialVaryPath\n )\n // The metadata \"segment\" is not part the route tree, but it has the same\n // conceptual params as a page segment. Write the vary path into the\n // accumulator object. If there are multiple parallel pages, we use the\n // first one. Which page we choose is arbitrary as long as it's\n // consistently the same one every time every time. See\n // finalizeMetadataVaryPath for more details.\n if (acc.metadataVaryPath === null) {\n acc.metadataVaryPath = finalizeMetadataVaryPath(\n requestKey,\n renderedSearch,\n partialVaryPath\n )\n }\n } else {\n // This is a layout segment.\n isPage = false\n segment = originalSegment\n varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n }\n }\n\n let slots: { [parallelRouteKey: string]: RouteTree } | null = null\n\n const parallelRoutes = flightRouterState[1]\n for (let parallelRouteKey in parallelRoutes) {\n const childRouterState = parallelRoutes[parallelRouteKey]\n const childSegment = childRouterState[0]\n // TODO: Eventually, the param values will not be included in the response\n // from the server. We'll instead fill them in on the client by parsing\n // the URL. This is where we'll do that.\n const childRequestKeyPart = createSegmentRequestKeyPart(childSegment)\n const childRequestKey = appendSegmentRequestKeyPart(\n requestKey,\n parallelRouteKey,\n childRequestKeyPart\n )\n const childTree = convertFlightRouterStateToRouteTree(\n childRouterState,\n childRequestKey,\n partialVaryPath,\n renderedSearch,\n acc\n )\n if (slots === null) {\n slots = {\n [parallelRouteKey]: childTree,\n }\n } else {\n slots[parallelRouteKey] = childTree\n }\n }\n\n return {\n requestKey,\n segment,\n varyPath,\n // TODO: Cheating the type system here a bit because TypeScript can't tell\n // that the type of isPage and varyPath are consistent. The fix would be to\n // create separate constructors and call the appropriate one from each of\n // the branches above. Just seems a bit overkill only for one field so I'll\n // leave it as-is for now. If isPage were wrong it would break the behavior\n // and we'd catch it quickly, anyway.\n isPage: isPage as boolean as any,\n slots,\n isRootLayout: flightRouterState[4] === true,\n hasLoadingBoundary:\n flightRouterState[5] !== undefined\n ? flightRouterState[5]\n : HasLoadingBoundary.SubtreeHasNoLoadingBoundary,\n\n // Non-static tree responses are only used by apps that haven't adopted\n // Cache Components. So this is always false.\n hasRuntimePrefetch: false,\n }\n}\n\nexport function convertRouteTreeToFlightRouterState(\n routeTree: RouteTree\n): FlightRouterState {\n const parallelRoutes: Record<string, FlightRouterState> = {}\n if (routeTree.slots !== null) {\n for (const parallelRouteKey in routeTree.slots) {\n parallelRoutes[parallelRouteKey] = convertRouteTreeToFlightRouterState(\n routeTree.slots[parallelRouteKey]\n )\n }\n }\n const flightRouterState: FlightRouterState = [\n routeTree.segment,\n parallelRoutes,\n null,\n null,\n routeTree.isRootLayout,\n ]\n return flightRouterState\n}\n\nexport async function fetchRouteOnCacheMiss(\n entry: PendingRouteCacheEntry,\n task: PrefetchTask,\n key: RouteCacheKey\n): Promise<PrefetchSubtaskResult<null> | null> {\n // This function is allowed to use async/await because it contains the actual\n // fetch that gets issued on a cache miss. Notice it writes the result to the\n // cache entry directly, rather than return data that is then written by\n // the caller.\n const pathname = key.pathname\n const search = key.search\n const nextUrl = key.nextUrl\n const segmentPath = '/_tree' as SegmentRequestKey\n\n const headers: RequestHeaders = {\n [RSC_HEADER]: '1',\n [NEXT_ROUTER_PREFETCH_HEADER]: '1',\n [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: segmentPath,\n }\n if (nextUrl !== null) {\n headers[NEXT_URL] = nextUrl\n }\n\n try {\n const url = new URL(pathname + search, location.origin)\n let response\n let urlAfterRedirects\n if (isOutputExportMode) {\n // In output: \"export\" mode, we can't use headers to request a particular\n // segment. Instead, we encode the extra request information into the URL.\n // This is not part of the \"public\" interface of the app; it's an internal\n // Next.js implementation detail that the app developer should not need to\n // concern themselves with.\n //\n // For example, to request a segment:\n //\n // Path passed to <Link>: /path/to/page\n // Path passed to fetch: /path/to/page/__next-segments/_tree\n //\n // (This is not the exact protocol, just an illustration.)\n //\n // Before we do that, though, we need to account for redirects. Even in\n // output: \"export\" mode, a proxy might redirect the page to a different\n // location, but we shouldn't assume or expect that they also redirect all\n // the segment files, too.\n //\n // To check whether the page is redirected, previously we perform a range\n // request of 64 bytes of the HTML document to check if the target page\n // is part of this app (by checking if build id matches). Only if the target\n // page is part of this app do we determine the final canonical URL.\n //\n // However, as mentioned in https://github.com/vercel/next.js/pull/85903,\n // some popular static hosting providers (like Cloudflare Pages or Render.com)\n // do not support range requests, in the worst case, the entire HTML instead\n // of 64 bytes could be returned, which is wasteful.\n //\n // So instead, we drops the check for build id here, and simply perform\n // a HEAD request to rejects 1xx/4xx/5xx responses, and then determine the\n // final URL after redirects.\n //\n // NOTE: We could embed the route tree into the HTML document, to avoid\n // a second request. We're not doing that currently because it would make\n // the HTML document larger and affect normal page loads.\n const headResponse = await fetch(url, {\n method: 'HEAD',\n })\n if (headResponse.status < 200 || headResponse.status >= 400) {\n // The target page responded w/o a successful status code\n // Could be a WAF serving a 403, or a 5xx from a backend\n //\n // Note that we can't use headResponse.ok here, because\n // Response#ok returns `false` with 3xx responses.\n rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n return null\n }\n\n urlAfterRedirects = headResponse.redirected\n ? new URL(headResponse.url)\n : url\n\n response = await fetchPrefetchResponse(\n addSegmentPathToUrlInOutputExportMode(urlAfterRedirects, segmentPath),\n headers\n )\n } else {\n // \"Server\" mode. We can use request headers instead of the pathname.\n // TODO: The eventual plan is to get rid of our custom request headers and\n // encode everything into the URL, using a similar strategy to the\n // \"output: export\" block above.\n response = await fetchPrefetchResponse(url, headers)\n urlAfterRedirects =\n response !== null && response.redirected ? new URL(response.url) : url\n }\n\n if (\n !response ||\n !response.ok ||\n // 204 is a Cache miss. Though theoretically this shouldn't happen when\n // PPR is enabled, because we always respond to route tree requests, even\n // if it needs to be blockingly generated on demand.\n response.status === 204 ||\n !response.body\n ) {\n // Server responded with an error, or with a miss. We should still cache\n // the response, but we can try again after 10 seconds.\n rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n return null\n }\n\n // TODO: The canonical URL is the href without the origin. I think\n // historically the reason for this is because the initial canonical URL\n // gets passed as a prop to the top-level React component, which means it\n // needs to be computed during SSR. If it were to include the origin, it\n // would need to always be same as location.origin on the client, to prevent\n // a hydration mismatch. To sidestep this complexity, we omit the origin.\n //\n // However, since this is neither a native URL object nor a fully qualified\n // URL string, we need to be careful about how we use it. To prevent subtle\n // mistakes, we should create a special type for it, instead of just string.\n // Or, we should just use a (readonly) URL object instead. The type of the\n // prop that we pass to seed the initial state does not need to be the same\n // type as the state itself.\n const canonicalUrl = createHrefFromUrl(urlAfterRedirects)\n\n // Check whether the response varies based on the Next-Url header.\n const varyHeader = response.headers.get('vary')\n const couldBeIntercepted =\n varyHeader !== null && varyHeader.includes(NEXT_URL)\n\n // Track when the network connection closes.\n const closed = createPromiseWithResolvers<void>()\n\n // This checks whether the response was served from the per-segment cache,\n // rather than the old prefetching flow. If it fails, it implies that PPR\n // is disabled on this route.\n const routeIsPPREnabled =\n response.headers.get(NEXT_DID_POSTPONE_HEADER) === '2' ||\n // In output: \"export\" mode, we can't rely on response headers. But if we\n // receive a well-formed response, we can assume it's a static response,\n // because all data is static in this mode.\n isOutputExportMode\n\n if (routeIsPPREnabled) {\n const prefetchStream = createPrefetchResponseStream(\n response.body,\n closed.resolve,\n function onResponseSizeUpdate(size) {\n setSizeInCacheMap(entry, size)\n }\n )\n const serverData = await createFromNextReadableStream<RootTreePrefetch>(\n prefetchStream,\n headers\n )\n if (serverData.buildId !== getAppBuildId()) {\n // The server build does not match the client. Treat as a 404. During\n // an actual navigation, the router will trigger an MPA navigation.\n // TODO: Consider moving the build ID to a response header so we can check\n // it before decoding the response, and so there's one way of checking\n // across all response types.\n // TODO: We should cache the fact that this is an MPA navigation.\n rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n return null\n }\n\n // Get the params that were used to render the target page. These may\n // be different from the params in the request URL, if the page\n // was rewritten.\n const renderedPathname = getRenderedPathname(response)\n const renderedSearch = getRenderedSearch(response)\n\n // Convert the server-sent data into the RouteTree format used by the\n // client cache.\n //\n // During this traversal, we accumulate additional data into this\n // \"accumulator\" object.\n const acc: RouteTreeAccumulator = { metadataVaryPath: null }\n const routeTree = convertRootTreePrefetchToRouteTree(\n serverData,\n renderedPathname,\n renderedSearch,\n acc\n )\n const metadataVaryPath = acc.metadataVaryPath\n if (metadataVaryPath === null) {\n rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n return null\n }\n\n const staleTimeMs = getStaleTimeMs(serverData.staleTime)\n fulfillRouteCacheEntry(\n entry,\n routeTree,\n metadataVaryPath,\n Date.now() + staleTimeMs,\n couldBeIntercepted,\n canonicalUrl,\n renderedSearch,\n routeIsPPREnabled\n )\n } else {\n // PPR is not enabled for this route. The server responds with a\n // different format (FlightRouterState) that we need to convert.\n // TODO: We will unify the responses eventually. I'm keeping the types\n // separate for now because FlightRouterState has so many\n // overloaded concerns.\n const prefetchStream = createPrefetchResponseStream(\n response.body,\n closed.resolve,\n function onResponseSizeUpdate(size) {\n setSizeInCacheMap(entry, size)\n }\n )\n const serverData =\n await createFromNextReadableStream<NavigationFlightResponse>(\n prefetchStream,\n headers\n )\n if (serverData.b !== getAppBuildId()) {\n // The server build does not match the client. Treat as a 404. During\n // an actual navigation, the router will trigger an MPA navigation.\n // TODO: Consider moving the build ID to a response header so we can check\n // it before decoding the response, and so there's one way of checking\n // across all response types.\n // TODO: We should cache the fact that this is an MPA navigation.\n rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n return null\n }\n\n writeDynamicTreeResponseIntoCache(\n Date.now(),\n task,\n // The non-PPR response format is what we'd get if we prefetched these segments\n // using the LoadingBoundary fetch strategy, so mark their cache entries accordingly.\n FetchStrategy.LoadingBoundary,\n response as RSCResponse<NavigationFlightResponse>,\n serverData,\n entry,\n couldBeIntercepted,\n canonicalUrl,\n routeIsPPREnabled\n )\n }\n\n if (!couldBeIntercepted) {\n // This route will never be intercepted. So we can use this entry for all\n // requests to this route, regardless of the Next-Url header. This works\n // because when reading the cache we always check for a valid\n // non-intercepted entry first.\n\n // Re-key the entry. The `set` implementation handles removing it from\n // its previous position in the cache. We don't need to do anything to\n // update the LRU, because the entry is already in it.\n // TODO: Treat this as an upsert — should check if an entry already\n // exists at the new keypath, and if so, whether we should keep that\n // one instead.\n const fulfilledVaryPath: RouteVaryPath = getFulfilledRouteVaryPath(\n pathname,\n search,\n nextUrl,\n couldBeIntercepted\n )\n const isRevalidation = false\n setInCacheMap(routeCacheMap, fulfilledVaryPath, entry, isRevalidation)\n }\n // Return a promise that resolves when the network connection closes, so\n // the scheduler can track the number of concurrent network connections.\n return { value: null, closed: closed.promise }\n } catch (error) {\n // Either the connection itself failed, or something bad happened while\n // decoding the response.\n rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n return null\n }\n}\n\nexport async function fetchSegmentOnCacheMiss(\n route: FulfilledRouteCacheEntry,\n segmentCacheEntry: PendingSegmentCacheEntry,\n routeKey: RouteCacheKey,\n tree: RouteTree\n): Promise<PrefetchSubtaskResult<FulfilledSegmentCacheEntry> | null> {\n // This function is allowed to use async/await because it contains the actual\n // fetch that gets issued on a cache miss. Notice it writes the result to the\n // cache entry directly, rather than return data that is then written by\n // the caller.\n //\n // Segment fetches are non-blocking so we don't need to ping the scheduler\n // on completion.\n\n // Use the canonical URL to request the segment, not the original URL. These\n // are usually the same, but the canonical URL will be different if the route\n // tree response was redirected. To avoid an extra waterfall on every segment\n // request, we pass the redirected URL instead of the original one.\n const url = new URL(route.canonicalUrl, location.origin)\n const nextUrl = routeKey.nextUrl\n\n const requestKey = tree.requestKey\n const normalizedRequestKey =\n requestKey === ROOT_SEGMENT_REQUEST_KEY\n ? // The root segment is a special case. To simplify the server-side\n // handling of these requests, we encode the root segment path as\n // `_index` instead of as an empty string. This should be treated as\n // an implementation detail and not as a stable part of the protocol.\n // It just needs to match the equivalent logic that happens when\n // prerendering the responses. It should not leak outside of Next.js.\n ('/_index' as SegmentRequestKey)\n : requestKey\n\n const headers: RequestHeaders = {\n [RSC_HEADER]: '1',\n [NEXT_ROUTER_PREFETCH_HEADER]: '1',\n [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: normalizedRequestKey,\n }\n if (nextUrl !== null) {\n headers[NEXT_URL] = nextUrl\n }\n\n const requestUrl = isOutputExportMode\n ? // In output: \"export\" mode, we need to add the segment path to the URL.\n addSegmentPathToUrlInOutputExportMode(url, normalizedRequestKey)\n : url\n try {\n const response = await fetchPrefetchResponse(requestUrl, headers)\n if (\n !response ||\n !response.ok ||\n response.status === 204 || // Cache miss\n // This checks whether the response was served from the per-segment cache,\n // rather than the old prefetching flow. If it fails, it implies that PPR\n // is disabled on this route. Theoretically this should never happen\n // because we only issue requests for segments once we've verified that\n // the route supports PPR.\n (response.headers.get(NEXT_DID_POSTPONE_HEADER) !== '2' &&\n // In output: \"export\" mode, we can't rely on response headers. But if\n // we receive a well-formed response, we can assume it's a static\n // response, because all data is static in this mode.\n !isOutputExportMode) ||\n !response.body\n ) {\n // Server responded with an error, or with a miss. We should still cache\n // the response, but we can try again after 10 seconds.\n rejectSegmentCacheEntry(segmentCacheEntry, Date.now() + 10 * 1000)\n return null\n }\n\n // Track when the network connection closes.\n const closed = createPromiseWithResolvers<void>()\n\n // Wrap the original stream in a new stream that never closes. That way the\n // Flight client doesn't error if there's a hanging promise.\n const prefetchStream = createPrefetchResponseStream(\n response.body,\n closed.resolve,\n function onResponseSizeUpdate(size) {\n setSizeInCacheMap(segmentCacheEntry, size)\n }\n )\n const serverData = await (createFromNextReadableStream(\n prefetchStream,\n headers\n ) as Promise<SegmentPrefetch>)\n if (serverData.buildId !== getAppBuildId()) {\n // The server build does not match the client. Treat as a 404. During\n // an actual navigation, the router will trigger an MPA navigation.\n // TODO: Consider moving the build ID to a response header so we can check\n // it before decoding the response, and so there's one way of checking\n // across all response types.\n rejectSegmentCacheEntry(segmentCacheEntry, Date.now() + 10 * 1000)\n return null\n }\n return {\n value: fulfillSegmentCacheEntry(\n segmentCacheEntry,\n serverData.rsc,\n serverData.loading,\n // TODO: The server does not currently provide per-segment stale time.\n // So we use the stale time of the route.\n route.staleAt,\n serverData.isPartial\n ),\n // Return a promise that resolves when the network connection closes, so\n // the scheduler can track the number of concurrent network connections.\n closed: closed.promise,\n }\n } catch (error) {\n // Either the connection itself failed, or something bad happened while\n // decoding the response.\n rejectSegmentCacheEntry(segmentCacheEntry, Date.now() + 10 * 1000)\n return null\n }\n}\n\nexport async function fetchSegmentPrefetchesUsingDynamicRequest(\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n fetchStrategy:\n | FetchStrategy.LoadingBoundary\n | FetchStrategy.PPRRuntime\n | FetchStrategy.Full,\n dynamicRequestTree: FlightRouterState,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>\n): Promise<PrefetchSubtaskResult<null> | null> {\n const key = task.key\n const url = new URL(route.canonicalUrl, location.origin)\n const nextUrl = key.nextUrl\n\n if (\n spawnedEntries.size === 1 &&\n spawnedEntries.has(route.metadata.requestKey)\n ) {\n // The only thing pending is the head. Instruct the server to\n // skip over everything else.\n dynamicRequestTree = MetadataOnlyRequestTree\n }\n\n const headers: RequestHeaders = {\n [RSC_HEADER]: '1',\n [NEXT_ROUTER_STATE_TREE_HEADER]:\n prepareFlightRouterStateForRequest(dynamicRequestTree),\n }\n if (nextUrl !== null) {\n headers[NEXT_URL] = nextUrl\n }\n switch (fetchStrategy) {\n case FetchStrategy.Full: {\n // We omit the prefetch header from a full prefetch because it's essentially\n // just a navigation request that happens ahead of time — it should include\n // all the same data in the response.\n break\n }\n case FetchStrategy.PPRRuntime: {\n headers[NEXT_ROUTER_PREFETCH_HEADER] = '2'\n break\n }\n case FetchStrategy.LoadingBoundary: {\n headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'\n break\n }\n default: {\n fetchStrategy satisfies never\n }\n }\n\n try {\n const response = await fetchPrefetchResponse(url, headers)\n if (!response || !response.ok || !response.body) {\n // Server responded with an error, or with a miss. We should still cache\n // the response, but we can try again after 10 seconds.\n rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n return null\n }\n\n const renderedSearch = getRenderedSearch(response)\n if (renderedSearch !== route.renderedSearch) {\n // The search params that were used to render the target page are\n // different from the search params in the request URL. This only happens\n // when there's a dynamic rewrite in between the tree prefetch and the\n // data prefetch.\n // TODO: For now, since this is an edge case, we reject the prefetch, but\n // the proper way to handle this is to evict the stale route tree entry\n // then fill the cache with the new response.\n rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n return null\n }\n\n // Track when the network connection closes.\n const closed = createPromiseWithResolvers<void>()\n\n let fulfilledEntries: Array<FulfilledSegmentCacheEntry> | null = null\n const prefetchStream = createPrefetchResponseStream(\n response.body,\n closed.resolve,\n function onResponseSizeUpdate(totalBytesReceivedSoFar) {\n // When processing a dynamic response, we don't know how large each\n // individual segment is, so approximate by assiging each segment\n // the average of the total response size.\n if (fulfilledEntries === null) {\n // Haven't received enough data yet to know which segments\n // were included.\n return\n }\n const averageSize = totalBytesReceivedSoFar / fulfilledEntries.length\n for (const entry of fulfilledEntries) {\n setSizeInCacheMap(entry, averageSize)\n }\n }\n )\n const serverData = await (createFromNextReadableStream(\n prefetchStream,\n headers\n ) as Promise<NavigationFlightResponse>)\n\n const isResponsePartial =\n fetchStrategy === FetchStrategy.PPRRuntime\n ? // A runtime prefetch may have holes.\n serverData.rp?.[0] === true\n : // Full and LoadingBoundary prefetches cannot have holes.\n // (even if we did set the prefetch header, we only use this codepath for non-PPR-enabled routes)\n false\n\n // Aside from writing the data into the cache, this function also returns\n // the entries that were fulfilled, so we can streamingly update their sizes\n // in the LRU as more data comes in.\n fulfilledEntries = writeDynamicRenderResponseIntoCache(\n Date.now(),\n task,\n fetchStrategy,\n response as RSCResponse<NavigationFlightResponse>,\n serverData,\n isResponsePartial,\n route,\n spawnedEntries\n )\n\n // Return a promise that resolves when the network connection closes, so\n // the scheduler can track the number of concurrent network connections.\n return { value: null, closed: closed.promise }\n } catch (error) {\n rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n return null\n }\n}\n\nfunction writeDynamicTreeResponseIntoCache(\n now: number,\n task: PrefetchTask,\n fetchStrategy:\n | FetchStrategy.LoadingBoundary\n | FetchStrategy.PPRRuntime\n | FetchStrategy.Full,\n response: RSCResponse<NavigationFlightResponse>,\n serverData: NavigationFlightResponse,\n entry: PendingRouteCacheEntry,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n routeIsPPREnabled: boolean\n) {\n // Get the URL that was used to render the target page. This may be different\n // from the URL in the request URL, if the page was rewritten.\n const renderedSearch = getRenderedSearch(response)\n\n const normalizedFlightDataResult = normalizeFlightData(serverData.f)\n if (\n // A string result means navigating to this route will result in an\n // MPA navigation.\n typeof normalizedFlightDataResult === 'string' ||\n normalizedFlightDataResult.length !== 1\n ) {\n rejectRouteCacheEntry(entry, now + 10 * 1000)\n return\n }\n const flightData = normalizedFlightDataResult[0]\n if (!flightData.isRootRender) {\n // Unexpected response format.\n rejectRouteCacheEntry(entry, now + 10 * 1000)\n return\n }\n\n const flightRouterState = flightData.tree\n // For runtime prefetches, stale time is in the payload at rp[1].\n // For other responses, fall back to the header.\n const staleTimeSeconds =\n typeof serverData.rp?.[1] === 'number'\n ? serverData.rp[1]\n : parseInt(response.headers.get(NEXT_ROUTER_STALE_TIME_HEADER) ?? '', 10)\n const staleTimeMs = !isNaN(staleTimeSeconds)\n ? getStaleTimeMs(staleTimeSeconds)\n : STATIC_STALETIME_MS\n\n // If the response contains dynamic holes, then we must conservatively assume\n // that any individual segment might contain dynamic holes, and also the\n // head. If it did not contain dynamic holes, then we can assume every segment\n // and the head is completely static.\n const isResponsePartial =\n response.headers.get(NEXT_DID_POSTPONE_HEADER) === '1'\n\n // Convert the server-sent data into the RouteTree format used by the\n // client cache.\n //\n // During this traversal, we accumulate additional data into this\n // \"accumulator\" object.\n const acc: RouteTreeAccumulator = { metadataVaryPath: null }\n const routeTree = convertRootFlightRouterStateToRouteTree(\n flightRouterState,\n renderedSearch,\n acc\n )\n const metadataVaryPath = acc.metadataVaryPath\n if (metadataVaryPath === null) {\n rejectRouteCacheEntry(entry, now + 10 * 1000)\n return\n }\n\n const fulfilledEntry = fulfillRouteCacheEntry(\n entry,\n routeTree,\n metadataVaryPath,\n now + staleTimeMs,\n couldBeIntercepted,\n canonicalUrl,\n renderedSearch,\n routeIsPPREnabled\n )\n\n // If the server sent segment data as part of the response, we should write\n // it into the cache to prevent a second, redundant prefetch request.\n //\n // TODO: When `clientSegmentCache` is enabled, the server does not include\n // segment data when responding to a route tree prefetch request. However,\n // when `clientSegmentCache` is set to \"client-only\", and PPR is enabled (or\n // the page is fully static), the normal check is bypassed and the server\n // responds with the full page. This is a temporary situation until we can\n // remove the \"client-only\" option. Then, we can delete this function call.\n writeDynamicRenderResponseIntoCache(\n now,\n task,\n fetchStrategy,\n response,\n serverData,\n isResponsePartial,\n fulfilledEntry,\n null\n )\n}\n\nfunction rejectSegmentEntriesIfStillPending(\n entries: Map<SegmentRequestKey, SegmentCacheEntry>,\n staleAt: number\n): Array<FulfilledSegmentCacheEntry> {\n const fulfilledEntries = []\n for (const entry of entries.values()) {\n if (entry.status === EntryStatus.Pending) {\n rejectSegmentCacheEntry(entry, staleAt)\n } else if (entry.status === EntryStatus.Fulfilled) {\n fulfilledEntries.push(entry)\n }\n }\n return fulfilledEntries\n}\n\nfunction writeDynamicRenderResponseIntoCache(\n now: number,\n task: PrefetchTask,\n fetchStrategy:\n | FetchStrategy.LoadingBoundary\n | FetchStrategy.PPRRuntime\n | FetchStrategy.Full,\n response: RSCResponse<NavigationFlightResponse>,\n serverData: NavigationFlightResponse,\n isResponsePartial: boolean,\n route: FulfilledRouteCacheEntry,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null\n): Array<FulfilledSegmentCacheEntry> | null {\n if (serverData.b !== getAppBuildId()) {\n // The server build does not match the client. Treat as a 404. During\n // an actual navigation, the router will trigger an MPA navigation.\n // TODO: Consider moving the build ID to a response header so we can check\n // it before decoding the response, and so there's one way of checking\n // across all response types.\n if (spawnedEntries !== null) {\n rejectSegmentEntriesIfStillPending(spawnedEntries, now + 10 * 1000)\n }\n return null\n }\n\n const flightDatas = normalizeFlightData(serverData.f)\n if (typeof flightDatas === 'string') {\n // This means navigating to this route will result in an MPA navigation.\n // TODO: We should cache this, too, so that the MPA navigation is immediate.\n return null\n }\n\n // For runtime prefetches, stale time is in the payload at rp[1].\n // For other responses, fall back to the header.\n const staleTimeSeconds =\n typeof serverData.rp?.[1] === 'number'\n ? serverData.rp[1]\n : parseInt(response.headers.get(NEXT_ROUTER_STALE_TIME_HEADER) ?? '', 10)\n const staleTimeMs = !isNaN(staleTimeSeconds)\n ? getStaleTimeMs(staleTimeSeconds)\n : STATIC_STALETIME_MS\n const staleAt = now + staleTimeMs\n\n for (const flightData of flightDatas) {\n const seedData = flightData.seedData\n if (seedData !== null) {\n // The data sent by the server represents only a subtree of the app. We\n // need to find the part of the task tree that matches the response.\n //\n // segmentPath represents the parent path of subtree. It's a repeating\n // pattern of parallel route key and segment:\n //\n // [string, Segment, string, Segment, string, Segment, ...]\n const segmentPath = flightData.segmentPath\n let tree = route.tree\n for (let i = 0; i < segmentPath.length; i += 2) {\n const parallelRouteKey: string = segmentPath[i]\n if (tree?.slots?.[parallelRouteKey] !== undefined) {\n tree = tree.slots[parallelRouteKey]\n } else {\n if (spawnedEntries !== null) {\n rejectSegmentEntriesIfStillPending(spawnedEntries, now + 10 * 1000)\n }\n return null\n }\n }\n\n writeSeedDataIntoCache(\n now,\n task,\n fetchStrategy,\n route,\n tree,\n staleAt,\n seedData,\n isResponsePartial,\n spawnedEntries\n )\n }\n\n const head = flightData.head\n if (head !== null) {\n fulfillEntrySpawnedByRuntimePrefetch(\n now,\n fetchStrategy,\n route,\n head,\n null,\n flightData.isHeadPartial,\n staleAt,\n route.metadata,\n spawnedEntries\n )\n }\n }\n // Any entry that's still pending was intentionally not rendered by the\n // server, because it was inside the loading boundary. Mark them as rejected\n // so we know not to fetch them again.\n // TODO: If PPR is enabled on some routes but not others, then it's possible\n // that a different page is able to do a per-segment prefetch of one of the\n // segments we're marking as rejected here. We should mark on the segment\n // somehow that the reason for the rejection is because of a non-PPR prefetch.\n // That way a per-segment prefetch knows to disregard the rejection.\n if (spawnedEntries !== null) {\n const fulfilledEntries = rejectSegmentEntriesIfStillPending(\n spawnedEntries,\n now + 10 * 1000\n )\n return fulfilledEntries\n }\n return null\n}\n\nfunction writeSeedDataIntoCache(\n now: number,\n task: PrefetchTask,\n fetchStrategy:\n | FetchStrategy.LoadingBoundary\n | FetchStrategy.PPRRuntime\n | FetchStrategy.Full,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree,\n staleAt: number,\n seedData: CacheNodeSeedData,\n isResponsePartial: boolean,\n entriesOwnedByCurrentTask: Map<\n SegmentRequestKey,\n PendingSegmentCacheEntry\n > | null\n) {\n // This function is used to write the result of a runtime server request\n // (CacheNodeSeedData) into the prefetch cache.\n const rsc = seedData[0]\n const loading = seedData[2]\n const isPartial = rsc === null || isResponsePartial\n fulfillEntrySpawnedByRuntimePrefetch(\n now,\n fetchStrategy,\n route,\n rsc,\n loading,\n isPartial,\n staleAt,\n tree,\n entriesOwnedByCurrentTask\n )\n\n // Recursively write the child data into the cache.\n const slots = tree.slots\n if (slots !== null) {\n const seedDataChildren = seedData[1]\n for (const parallelRouteKey in slots) {\n const childTree = slots[parallelRouteKey]\n const childSeedData: CacheNodeSeedData | null | void =\n seedDataChildren[parallelRouteKey]\n if (childSeedData !== null && childSeedData !== undefined) {\n writeSeedDataIntoCache(\n now,\n task,\n fetchStrategy,\n route,\n childTree,\n staleAt,\n childSeedData,\n isResponsePartial,\n entriesOwnedByCurrentTask\n )\n }\n }\n }\n}\n\nfunction fulfillEntrySpawnedByRuntimePrefetch(\n now: number,\n fetchStrategy:\n | FetchStrategy.LoadingBoundary\n | FetchStrategy.PPRRuntime\n | FetchStrategy.Full,\n route: FulfilledRouteCacheEntry,\n rsc: React.ReactNode,\n loading: LoadingModuleData | Promise<LoadingModuleData>,\n isPartial: boolean,\n staleAt: number,\n tree: RouteTree,\n entriesOwnedByCurrentTask: Map<\n SegmentRequestKey,\n PendingSegmentCacheEntry\n > | null\n) {\n // We should only write into cache entries that are owned by us. Or create\n // a new one and write into that. We must never write over an entry that was\n // created by a different task, because that causes data races.\n const ownedEntry =\n entriesOwnedByCurrentTask !== null\n ? entriesOwnedByCurrentTask.get(tree.requestKey)\n : undefined\n if (ownedEntry !== undefined) {\n fulfillSegmentCacheEntry(ownedEntry, rsc, loading, staleAt, isPartial)\n } else {\n // There's no matching entry. Attempt to create a new one.\n const possiblyNewEntry = readOrCreateSegmentCacheEntry(\n now,\n fetchStrategy,\n route,\n tree\n )\n if (possiblyNewEntry.status === EntryStatus.Empty) {\n // Confirmed this is a new entry. We can fulfill it.\n const newEntry = possiblyNewEntry\n fulfillSegmentCacheEntry(\n upgradeToPendingSegment(newEntry, fetchStrategy),\n rsc,\n loading,\n staleAt,\n isPartial\n )\n } else {\n // There was already an entry in the cache. But we may be able to\n // replace it with the new one from the server.\n const newEntry = fulfillSegmentCacheEntry(\n upgradeToPendingSegment(\n createDetachedSegmentCacheEntry(staleAt),\n fetchStrategy\n ),\n rsc,\n loading,\n staleAt,\n isPartial\n )\n upsertSegmentEntry(\n now,\n getSegmentVaryPathForRequest(fetchStrategy, tree),\n newEntry\n )\n }\n }\n}\n\nasync function fetchPrefetchResponse<T>(\n url: URL,\n headers: RequestHeaders\n): Promise<RSCResponse<T> | null> {\n const fetchPriority = 'low'\n // When issuing a prefetch request, don't immediately decode the response; we\n // use the lower level `createFromResponse` API instead because we need to do\n // some extra processing of the response stream. See\n // `createPrefetchResponseStream` for more details.\n const shouldImmediatelyDecode = false\n const response = await createFetch<T>(\n url,\n headers,\n fetchPriority,\n shouldImmediatelyDecode\n )\n if (!response.ok) {\n return null\n }\n\n // Check the content type\n if (isOutputExportMode) {\n // In output: \"export\" mode, we relaxed about the content type, since it's\n // not Next.js that's serving the response. If the status is OK, assume the\n // response is valid. If it's not a valid response, the Flight client won't\n // be able to decode it, and we'll treat it as a miss.\n } else {\n const contentType = response.headers.get('content-type')\n const isFlightResponse =\n contentType && contentType.startsWith(RSC_CONTENT_TYPE_HEADER)\n if (!isFlightResponse) {\n return null\n }\n }\n return response\n}\n\nfunction createPrefetchResponseStream(\n originalFlightStream: ReadableStream<Uint8Array>,\n onStreamClose: () => void,\n onResponseSizeUpdate: (size: number) => void\n): ReadableStream<Uint8Array> {\n // When PPR is enabled, prefetch streams may contain references that never\n // resolve, because that's how we encode dynamic data access. In the decoded\n // object returned by the Flight client, these are reified into hanging\n // promises that suspend during render, which is effectively what we want.\n // The UI resolves when it switches to the dynamic data stream\n // (via useDeferredValue(dynamic, static)).\n //\n // However, the Flight implementation currently errors if the server closes\n // the response before all the references are resolved. As a cheat to work\n // around this, we wrap the original stream in a new stream that never closes,\n // and therefore doesn't error.\n //\n // While processing the original stream, we also incrementally update the size\n // of the cache entry in the LRU.\n let totalByteLength = 0\n const reader = originalFlightStream.getReader()\n return new ReadableStream({\n async pull(controller) {\n while (true) {\n const { done, value } = await reader.read()\n if (!done) {\n // Pass to the target stream and keep consuming the Flight response\n // from the server.\n controller.enqueue(value)\n\n // Incrementally update the size of the cache entry in the LRU.\n // NOTE: Since prefetch responses are delivered in a single chunk,\n // it's not really necessary to do this streamingly, but I'm doing it\n // anyway in case this changes in the future.\n totalByteLength += value.byteLength\n onResponseSizeUpdate(totalByteLength)\n continue\n }\n // The server stream has closed. Exit, but intentionally do not close\n // the target stream. We do notify the caller, though.\n onStreamClose()\n return\n }\n },\n })\n}\n\nfunction addSegmentPathToUrlInOutputExportMode(\n url: URL,\n segmentPath: SegmentRequestKey\n): URL {\n if (isOutputExportMode) {\n // In output: \"export\" mode, we cannot use a header to encode the segment\n // path. Instead, we append it to the end of the pathname.\n const staticUrl = new URL(url)\n const routeDir = staticUrl.pathname.endsWith('/')\n ? staticUrl.pathname.slice(0, -1)\n : staticUrl.pathname\n const staticExportFilename =\n convertSegmentPathToStaticExportFilename(segmentPath)\n staticUrl.pathname = `${routeDir}/${staticExportFilename}`\n return staticUrl\n }\n return url\n}\n\n/**\n * Checks whether the new fetch strategy is likely to provide more content than the old one.\n *\n * Generally, when an app uses dynamic data, a \"more specific\" fetch strategy is expected to provide more content:\n * - `LoadingBoundary` only provides static layouts\n * - `PPR` can provide shells for each segment (even for segments that use dynamic data)\n * - `PPRRuntime` can additionally include content that uses searchParams, params, or cookies\n * - `Full` includes all the content, even if it uses dynamic data\n *\n * However, it's possible that a more specific fetch strategy *won't* give us more content if:\n * - a segment is fully static\n * (then, `PPR`/`PPRRuntime`/`Full` will all yield equivalent results)\n * - providing searchParams/params/cookies doesn't reveal any more content, e.g. because of an `await connection()`\n * (then, `PPR` and `PPRRuntime` will yield equivalent results, only `Full` will give us more)\n * Because of this, when comparing two segments, we should also check if the existing segment is partial.\n * If it's not partial, then there's no need to prefetch it again, even using a \"more specific\" strategy.\n * There's currently no way to know if `PPRRuntime` will yield more data that `PPR`, so we have to assume it will.\n *\n * Also note that, in practice, we don't expect to be comparing `LoadingBoundary` to `PPR`/`PPRRuntime`,\n * because a non-PPR-enabled route wouldn't ever use the latter strategies. It might however use `Full`.\n */\nexport function canNewFetchStrategyProvideMoreContent(\n currentStrategy: FetchStrategy,\n newStrategy: FetchStrategy\n): boolean {\n return currentStrategy < newStrategy\n}\n","import type {\n FlightRouterState,\n Segment as FlightRouterStateSegment,\n Segment,\n} from '../../../shared/lib/app-router-types'\nimport { HasLoadingBoundary } from '../../../shared/lib/app-router-types'\nimport { matchSegment } from '../match-segments'\nimport {\n readOrCreateRouteCacheEntry,\n readOrCreateSegmentCacheEntry,\n fetchRouteOnCacheMiss,\n fetchSegmentOnCacheMiss,\n EntryStatus,\n type FulfilledRouteCacheEntry,\n type RouteCacheEntry,\n type SegmentCacheEntry,\n type RouteTree,\n fetchSegmentPrefetchesUsingDynamicRequest,\n type PendingSegmentCacheEntry,\n convertRouteTreeToFlightRouterState,\n readOrCreateRevalidatingSegmentEntry,\n upsertSegmentEntry,\n type FulfilledSegmentCacheEntry,\n upgradeToPendingSegment,\n waitForSegmentCacheEntry,\n overwriteRevalidatingSegmentCacheEntry,\n canNewFetchStrategyProvideMoreContent,\n} from './cache'\nimport { getSegmentVaryPathForRequest, type SegmentVaryPath } from './vary-path'\nimport type { RouteCacheKey } from './cache-key'\nimport { createCacheKey } from './cache-key'\nimport {\n FetchStrategy,\n type PrefetchTaskFetchStrategy,\n PrefetchPriority,\n} from './types'\nimport { getCurrentCacheVersion } from './cache'\nimport {\n addSearchParamsIfPageSegment,\n PAGE_SEGMENT_KEY,\n} from '../../../shared/lib/segment'\nimport type { SegmentRequestKey } from '../../../shared/lib/segment-cache/segment-value-encoding'\n\nconst scheduleMicrotask =\n typeof queueMicrotask === 'function'\n ? queueMicrotask\n : (fn: () => unknown) =>\n Promise.resolve()\n .then(fn)\n .catch((error) =>\n setTimeout(() => {\n throw error\n })\n )\n\nexport type PrefetchTask = {\n key: RouteCacheKey\n\n /**\n * The FlightRouterState at the time the task was initiated. This is needed\n * when falling back to the non-PPR behavior, which only prefetches up to\n * the first loading boundary.\n */\n treeAtTimeOfPrefetch: FlightRouterState\n\n /**\n * The cache version at the time the task was initiated. This is used to\n * determine if the cache was invalidated since the task was initiated.\n */\n cacheVersion: number\n\n /**\n * Whether to prefetch dynamic data, in addition to static data. This is\n * used by `<Link prefetch={true}>`.\n *\n * Note that a task with `FetchStrategy.PPR` might need to use\n * `FetchStrategy.LoadingBoundary` instead if we find out that a route\n * does not support PPR after doing the initial route prefetch.\n */\n fetchStrategy: PrefetchTaskFetchStrategy\n\n /**\n * sortId is an incrementing counter\n *\n * Newer prefetches are prioritized over older ones, so that as new links\n * enter the viewport, they are not starved by older links that are no\n * longer relevant. In the future, we can add additional prioritization\n * heuristics, like removing prefetches once a link leaves the viewport.\n *\n * The sortId is assigned when the prefetch is initiated, and reassigned if\n * the same task is prefetched again (effectively bumping it to the top of\n * the queue).\n *\n * TODO: We can add additional fields here to indicate what kind of prefetch\n * it is. For example, was it initiated by a link? Or was it an imperative\n * call? If it was initiated by a link, we can remove it from the queue when\n * the link leaves the viewport, but if it was an imperative call, then we\n * should keep it in the queue until it's fulfilled.\n *\n * We can also add priority levels. For example, hovering over a link could\n * increase the priority of its prefetch.\n */\n sortId: number\n\n /**\n * The priority of the task. Like sortId, this affects the task's position in\n * the queue, so it must never be updated without resifting the heap.\n */\n priority: PrefetchPriority\n\n /**\n * The phase of the task. Tasks are split into multiple phases so that their\n * priority can be adjusted based on what kind of work they're doing.\n * Concretely, prefetching the route tree is higher priority than prefetching\n * segment data.\n */\n phase: PrefetchPhase\n\n /**\n * These fields are temporary state for tracking the currently running task.\n * They are reset after each iteration of the task queue.\n */\n hasBackgroundWork: boolean\n spawnedRuntimePrefetches: Set<SegmentRequestKey> | null\n\n /**\n * True if the prefetch was cancelled.\n */\n isCanceled: boolean\n\n /**\n * The callback passed to `router.prefetch`, if given.\n */\n onInvalidate: null | (() => void)\n\n /**\n * The index of the task in the heap's backing array. Used to efficiently\n * change the priority of a task by re-sifting it, which requires knowing\n * where it is in the array. This is only used internally by the heap\n * algorithm. The naive alternative is indexOf every time a task is queued,\n * which has O(n) complexity.\n *\n * We also use this field to check whether a task is currently in the queue.\n */\n _heapIndex: number\n}\n\nconst enum PrefetchTaskExitStatus {\n /**\n * The task yielded because there are too many requests in progress.\n */\n InProgress,\n\n /**\n * The task is blocked. It needs more data before it can proceed.\n *\n * Currently the only reason this happens is we're still waiting to receive a\n * route tree from the server, because we can't start prefetching the segments\n * until we know what to prefetch.\n */\n Blocked,\n\n /**\n * There's nothing left to prefetch.\n */\n Done,\n}\n\n/**\n * Prefetch tasks are processed in two phases: first the route tree is fetched,\n * then the segments. We use this to priortize tasks that have not yet fetched\n * the route tree.\n */\nconst enum PrefetchPhase {\n RouteTree = 1,\n Segments = 0,\n}\n\nexport type PrefetchSubtaskResult<T> = {\n /**\n * A promise that resolves when the network connection is closed.\n */\n closed: Promise<void>\n value: T\n}\n\nconst taskHeap: Array<PrefetchTask> = []\n\nlet inProgressRequests = 0\n\nlet sortIdCounter = 0\nlet didScheduleMicrotask = false\n\n// The most recently hovered (or touched, etc) link, i.e. the most recent task\n// scheduled at Intent priority. There's only ever a single task at Intent\n// priority at a time. We reserve special network bandwidth for this task only.\nlet mostRecentlyHoveredLink: PrefetchTask | null = null\n\n// CDN cache propagation delay after revalidation (in milliseconds)\nconst REVALIDATION_COOLDOWN_MS = 300\n\n// Timeout handle for the revalidation cooldown. When non-null, prefetch\n// requests are blocked to allow CDN cache propagation.\nlet revalidationCooldownTimeoutHandle: ReturnType<typeof setTimeout> | null =\n null\n\n/**\n * Called by the cache when revalidation occurs. Starts a cooldown period\n * during which prefetch requests are blocked to allow CDN cache propagation.\n */\nexport function startRevalidationCooldown(): void {\n // Clear any existing timeout in case multiple revalidations happen\n // in quick succession.\n if (revalidationCooldownTimeoutHandle !== null) {\n clearTimeout(revalidationCooldownTimeoutHandle)\n }\n\n // Schedule the cooldown to expire after the delay.\n revalidationCooldownTimeoutHandle = setTimeout(() => {\n revalidationCooldownTimeoutHandle = null\n // Retry the prefetch queue now that the cooldown has expired.\n ensureWorkIsScheduled()\n }, REVALIDATION_COOLDOWN_MS)\n}\n\nexport type IncludeDynamicData = null | 'full' | 'dynamic'\n\n/**\n * Initiates a prefetch task for the given URL. If a prefetch for the same URL\n * is already in progress, this will bump it to the top of the queue.\n *\n * This is not a user-facing function. By the time this is called, the href is\n * expected to be validated and normalized.\n *\n * @param key The RouteCacheKey to prefetch.\n * @param treeAtTimeOfPrefetch The app's current FlightRouterState\n * @param fetchStrategy Whether to prefetch dynamic data, in addition to\n * static data. This is used by `<Link prefetch={true}>`.\n */\nexport function schedulePrefetchTask(\n key: RouteCacheKey,\n treeAtTimeOfPrefetch: FlightRouterState,\n fetchStrategy: PrefetchTaskFetchStrategy,\n priority: PrefetchPriority,\n onInvalidate: null | (() => void)\n): PrefetchTask {\n // Spawn a new prefetch task\n const task: PrefetchTask = {\n key,\n treeAtTimeOfPrefetch,\n cacheVersion: getCurrentCacheVersion(),\n priority,\n phase: PrefetchPhase.RouteTree,\n hasBackgroundWork: false,\n spawnedRuntimePrefetches: null,\n fetchStrategy,\n sortId: sortIdCounter++,\n isCanceled: false,\n onInvalidate,\n _heapIndex: -1,\n }\n\n trackMostRecentlyHoveredLink(task)\n\n heapPush(taskHeap, task)\n\n // Schedule an async task to process the queue.\n //\n // The main reason we process the queue in an async task is for batching.\n // It's common for a single JS task/event to trigger multiple prefetches.\n // By deferring to a microtask, we only process the queue once per JS task.\n // If they have different priorities, it also ensures they are processed in\n // the optimal order.\n ensureWorkIsScheduled()\n\n return task\n}\n\nexport function cancelPrefetchTask(task: PrefetchTask): void {\n // Remove the prefetch task from the queue. If the task already completed,\n // then this is a no-op.\n //\n // We must also explicitly mark the task as canceled so that a blocked task\n // does not get added back to the queue when it's pinged by the network.\n task.isCanceled = true\n heapDelete(taskHeap, task)\n}\n\nexport function reschedulePrefetchTask(\n task: PrefetchTask,\n treeAtTimeOfPrefetch: FlightRouterState,\n fetchStrategy: PrefetchTaskFetchStrategy,\n priority: PrefetchPriority\n): void {\n // Bump the prefetch task to the top of the queue, as if it were a fresh\n // task. This is essentially the same as canceling the task and scheduling\n // a new one, except it reuses the original object.\n //\n // The primary use case is to increase the priority of a Link-initated\n // prefetch on hover.\n\n // Un-cancel the task, in case it was previously canceled.\n task.isCanceled = false\n task.phase = PrefetchPhase.RouteTree\n\n // Assign a new sort ID to move it ahead of all other tasks at the same\n // priority level. (Higher sort IDs are processed first.)\n task.sortId = sortIdCounter++\n task.priority =\n // If this task is the most recently hovered link, maintain its\n // Intent priority, even if the rescheduled priority is lower.\n task === mostRecentlyHoveredLink ? PrefetchPriority.Intent : priority\n\n task.treeAtTimeOfPrefetch = treeAtTimeOfPrefetch\n task.fetchStrategy = fetchStrategy\n\n trackMostRecentlyHoveredLink(task)\n\n if (task._heapIndex !== -1) {\n // The task is already in the queue.\n heapResift(taskHeap, task)\n } else {\n heapPush(taskHeap, task)\n }\n ensureWorkIsScheduled()\n}\n\nexport function isPrefetchTaskDirty(\n task: PrefetchTask,\n nextUrl: string | null,\n tree: FlightRouterState\n): boolean {\n // This is used to quickly bail out of a prefetch task if the result is\n // guaranteed to not have changed since the task was initiated. This is\n // strictly an optimization — theoretically, if it always returned true, no\n // behavior should change because a full prefetch task will effectively\n // perform the same checks.\n const currentCacheVersion = getCurrentCacheVersion()\n return (\n task.cacheVersion !== currentCacheVersion ||\n task.treeAtTimeOfPrefetch !== tree ||\n task.key.nextUrl !== nextUrl\n )\n}\n\nfunction trackMostRecentlyHoveredLink(task: PrefetchTask) {\n // Track the mostly recently hovered link, i.e. the most recently scheduled\n // task at Intent priority. There must only be one such task at a time.\n if (\n task.priority === PrefetchPriority.Intent &&\n task !== mostRecentlyHoveredLink\n ) {\n if (mostRecentlyHoveredLink !== null) {\n // Bump the previously hovered link's priority down to Default.\n if (mostRecentlyHoveredLink.priority !== PrefetchPriority.Background) {\n mostRecentlyHoveredLink.priority = PrefetchPriority.Default\n heapResift(taskHeap, mostRecentlyHoveredLink)\n }\n }\n mostRecentlyHoveredLink = task\n }\n}\n\nfunction ensureWorkIsScheduled() {\n if (didScheduleMicrotask) {\n // Already scheduled a task to process the queue\n return\n }\n didScheduleMicrotask = true\n scheduleMicrotask(processQueueInMicrotask)\n}\n\n/**\n * Checks if we've exceeded the maximum number of concurrent prefetch requests,\n * to avoid saturating the browser's internal network queue. This is a\n * cooperative limit — prefetch tasks should check this before issuing\n * new requests.\n *\n * Also checks if we're within the revalidation cooldown window, during which\n * prefetch requests are delayed to allow CDN cache propagation.\n */\nfunction hasNetworkBandwidth(task: PrefetchTask): boolean {\n // Check if we're within the revalidation cooldown window\n if (revalidationCooldownTimeoutHandle !== null) {\n // We're within the cooldown window. Return false to prevent prefetching.\n // When the cooldown expires, the timeout will call ensureWorkIsScheduled()\n // to retry the queue.\n return false\n }\n\n // TODO: Also check if there's an in-progress navigation. We should never\n // add prefetch requests to the network queue if an actual navigation is\n // taking place, to ensure there's sufficient bandwidth for render-blocking\n // data and resources.\n\n // TODO: Consider reserving some amount of bandwidth for static prefetches.\n\n if (task.priority === PrefetchPriority.Intent) {\n // The most recently hovered link is allowed to exceed the default limit.\n //\n // The goal is to always have enough bandwidth to start a new prefetch\n // request when hovering over a link.\n //\n // However, because we don't abort in-progress requests, it's still possible\n // we'll run out of bandwidth. When links are hovered in quick succession,\n // there could be multiple hover requests running simultaneously.\n return inProgressRequests < 12\n }\n\n // The default limit is lower than the limit for a hovered link.\n return inProgressRequests < 4\n}\n\nfunction spawnPrefetchSubtask<T>(\n prefetchSubtask: Promise<PrefetchSubtaskResult<T> | null>\n): Promise<T | null> {\n // When the scheduler spawns an async task, we don't await its result.\n // Instead, the async task writes its result directly into the cache, then\n // pings the scheduler to continue.\n //\n // We process server responses streamingly, so the prefetch subtask will\n // likely resolve before we're finished receiving all the data. The subtask\n // result includes a promise that resolves once the network connection is\n // closed. The scheduler uses this to control network bandwidth by tracking\n // and limiting the number of concurrent requests.\n inProgressRequests++\n return prefetchSubtask.then((result) => {\n if (result === null) {\n // The prefetch task errored before it could start processing the\n // network stream. Assume the connection is closed.\n onPrefetchConnectionClosed()\n return null\n }\n // Wait for the connection to close before freeing up more bandwidth.\n result.closed.then(onPrefetchConnectionClosed)\n return result.value\n })\n}\n\nfunction onPrefetchConnectionClosed(): void {\n inProgressRequests--\n\n // Notify the scheduler that we have more bandwidth, and can continue\n // processing tasks.\n ensureWorkIsScheduled()\n}\n\n/**\n * Notify the scheduler that we've received new data for an in-progress\n * prefetch. The corresponding task will be added back to the queue (unless the\n * task has been canceled in the meantime).\n */\nexport function pingPrefetchTask(task: PrefetchTask) {\n // \"Ping\" a prefetch that's already in progress to notify it of new data.\n if (\n // Check if prefetch was canceled.\n task.isCanceled ||\n // Check if prefetch is already queued.\n task._heapIndex !== -1\n ) {\n return\n }\n // Add the task back to the queue.\n heapPush(taskHeap, task)\n ensureWorkIsScheduled()\n}\n\nfunction processQueueInMicrotask() {\n didScheduleMicrotask = false\n\n // We aim to minimize how often we read the current time. Since nearly all\n // functions in the prefetch scheduler are synchronous, we can read the time\n // once and pass it as an argument wherever it's needed.\n const now = Date.now()\n\n // Process the task queue until we run out of network bandwidth.\n let task = heapPeek(taskHeap)\n while (task !== null && hasNetworkBandwidth(task)) {\n task.cacheVersion = getCurrentCacheVersion()\n\n const exitStatus = pingRoute(now, task)\n\n // These fields are only valid for a single attempt. Reset them after each\n // iteration of the task queue.\n const hasBackgroundWork = task.hasBackgroundWork\n task.hasBackgroundWork = false\n task.spawnedRuntimePrefetches = null\n\n switch (exitStatus) {\n case PrefetchTaskExitStatus.InProgress:\n // The task yielded because there are too many requests in progress.\n // Stop processing tasks until we have more bandwidth.\n return\n case PrefetchTaskExitStatus.Blocked:\n // The task is blocked. It needs more data before it can proceed.\n // Keep the task out of the queue until the server responds.\n heapPop(taskHeap)\n // Continue to the next task\n task = heapPeek(taskHeap)\n continue\n case PrefetchTaskExitStatus.Done:\n if (task.phase === PrefetchPhase.RouteTree) {\n // Finished prefetching the route tree. Proceed to prefetching\n // the segments.\n task.phase = PrefetchPhase.Segments\n heapResift(taskHeap, task)\n } else if (hasBackgroundWork) {\n // The task spawned additional background work. Reschedule the task\n // at background priority.\n task.priority = PrefetchPriority.Background\n heapResift(taskHeap, task)\n } else {\n // The prefetch is complete. Continue to the next task.\n heapPop(taskHeap)\n }\n task = heapPeek(taskHeap)\n continue\n default:\n exitStatus satisfies never\n }\n }\n}\n\n/**\n * Check this during a prefetch task to determine if background work can be\n * performed. If so, it evaluates to `true`. Otherwise, it returns `false`,\n * while also scheduling a background task to run later. Usage:\n *\n * @example\n * if (background(task)) {\n * // Perform background-pri work\n * }\n */\nfunction background(task: PrefetchTask): boolean {\n if (task.priority === PrefetchPriority.Background) {\n return true\n }\n task.hasBackgroundWork = true\n return false\n}\n\nfunction pingRoute(now: number, task: PrefetchTask): PrefetchTaskExitStatus {\n const key = task.key\n const route = readOrCreateRouteCacheEntry(now, task, key)\n const exitStatus = pingRootRouteTree(now, task, route)\n\n if (exitStatus !== PrefetchTaskExitStatus.InProgress && key.search !== '') {\n // If the URL has a non-empty search string, also prefetch the pathname\n // without the search string. We use the searchless route tree as a base for\n // optimistic routing; see requestOptimisticRouteCacheEntry for details.\n //\n // Note that we don't need to prefetch any of the segment data. Just the\n // route tree.\n //\n // TODO: This is a temporary solution; the plan is to replace this by adding\n // a wildcard lookup method to the TupleMap implementation. This is\n // non-trivial to implement because it needs to account for things like\n // fallback route entries, hence this temporary workaround.\n const url = new URL(key.pathname, location.origin)\n const keyWithoutSearch = createCacheKey(url.href, key.nextUrl)\n const routeWithoutSearch = readOrCreateRouteCacheEntry(\n now,\n task,\n keyWithoutSearch\n )\n switch (routeWithoutSearch.status) {\n case EntryStatus.Empty: {\n if (background(task)) {\n routeWithoutSearch.status = EntryStatus.Pending\n spawnPrefetchSubtask(\n fetchRouteOnCacheMiss(routeWithoutSearch, task, keyWithoutSearch)\n )\n }\n break\n }\n case EntryStatus.Pending:\n case EntryStatus.Fulfilled:\n case EntryStatus.Rejected: {\n // Either the route tree is already cached, or there's already a\n // request in progress. Since we don't need to fetch any segment data\n // for this route, there's nothing left to do.\n break\n }\n default:\n routeWithoutSearch satisfies never\n }\n }\n\n return exitStatus\n}\n\nfunction pingRootRouteTree(\n now: number,\n task: PrefetchTask,\n route: RouteCacheEntry\n): PrefetchTaskExitStatus {\n switch (route.status) {\n case EntryStatus.Empty: {\n // Route is not yet cached, and there's no request already in progress.\n // Spawn a task to request the route, load it into the cache, and ping\n // the task to continue.\n\n // TODO: There are multiple strategies in the <Link> API for prefetching\n // a route. Currently we've only implemented the main one: per-segment,\n // static-data only.\n //\n // There's also `<Link prefetch={true}>`\n // which prefetch both static *and* dynamic data.\n // Similarly, we need to fallback to the old, per-page\n // behavior if PPR is disabled for a route (via the incremental opt-in).\n //\n // Those cases will be handled here.\n spawnPrefetchSubtask(fetchRouteOnCacheMiss(route, task, task.key))\n\n // If the request takes longer than a minute, a subsequent request should\n // retry instead of waiting for this one. When the response is received,\n // this value will be replaced by a new value based on the stale time sent\n // from the server.\n // TODO: We should probably also manually abort the fetch task, to reclaim\n // server bandwidth.\n route.staleAt = now + 60 * 1000\n\n // Upgrade to Pending so we know there's already a request in progress\n route.status = EntryStatus.Pending\n\n // Intentional fallthrough to the Pending branch\n }\n case EntryStatus.Pending: {\n // Still pending. We can't start prefetching the segments until the route\n // tree has loaded. Add the task to the set of blocked tasks so that it\n // is notified when the route tree is ready.\n const blockedTasks = route.blockedTasks\n if (blockedTasks === null) {\n route.blockedTasks = new Set([task])\n } else {\n blockedTasks.add(task)\n }\n return PrefetchTaskExitStatus.Blocked\n }\n case EntryStatus.Rejected: {\n // Route tree failed to load. Treat as a 404.\n return PrefetchTaskExitStatus.Done\n }\n case EntryStatus.Fulfilled: {\n if (task.phase !== PrefetchPhase.Segments) {\n // Do not prefetch segment data until we've entered the segment phase.\n return PrefetchTaskExitStatus.Done\n }\n // Recursively fill in the segment tree.\n if (!hasNetworkBandwidth(task)) {\n // Stop prefetching segments until there's more bandwidth.\n return PrefetchTaskExitStatus.InProgress\n }\n const tree = route.tree\n\n // A task's fetch strategy gets set to `PPR` for any \"auto\" prefetch.\n // If it turned out that the route isn't PPR-enabled, we need to use `LoadingBoundary` instead.\n // We don't need to do this for runtime prefetches, because those are only available in\n // `cacheComponents`, where every route is PPR.\n const fetchStrategy =\n task.fetchStrategy === FetchStrategy.PPR\n ? route.isPPREnabled\n ? FetchStrategy.PPR\n : FetchStrategy.LoadingBoundary\n : task.fetchStrategy\n\n switch (fetchStrategy) {\n case FetchStrategy.PPR: {\n // For Cache Components pages, each segment may be prefetched\n // statically or using a runtime request, based on various\n // configurations and heuristics. We'll do this in two passes: first\n // traverse the tree and perform all the static prefetches.\n //\n // Then, if there are any segments that need a runtime request,\n // do another pass to perform a runtime prefetch.\n pingStaticHead(now, task, route)\n const exitStatus = pingSharedPartOfCacheComponentsTree(\n now,\n task,\n route,\n task.treeAtTimeOfPrefetch,\n tree\n )\n if (exitStatus === PrefetchTaskExitStatus.InProgress) {\n // Child yielded without finishing.\n return PrefetchTaskExitStatus.InProgress\n }\n const spawnedRuntimePrefetches = task.spawnedRuntimePrefetches\n if (spawnedRuntimePrefetches !== null) {\n // During the first pass, we discovered segments that require a\n // runtime prefetch. Do a second pass to construct a request tree.\n const spawnedEntries = new Map<\n SegmentRequestKey,\n PendingSegmentCacheEntry\n >()\n pingRuntimeHead(\n now,\n task,\n route,\n spawnedEntries,\n FetchStrategy.PPRRuntime\n )\n const requestTree = pingRuntimePrefetches(\n now,\n task,\n route,\n tree,\n spawnedRuntimePrefetches,\n spawnedEntries\n )\n let needsDynamicRequest = spawnedEntries.size > 0\n if (needsDynamicRequest) {\n // Perform a dynamic prefetch request and populate the cache with\n // the result.\n spawnPrefetchSubtask(\n fetchSegmentPrefetchesUsingDynamicRequest(\n task,\n route,\n FetchStrategy.PPRRuntime,\n requestTree,\n spawnedEntries\n )\n )\n }\n }\n return PrefetchTaskExitStatus.Done\n }\n case FetchStrategy.Full:\n case FetchStrategy.PPRRuntime:\n case FetchStrategy.LoadingBoundary: {\n // Prefetch multiple segments using a single dynamic request.\n // TODO: We can consolidate this branch with previous one by modeling\n // it as if the first segment in the new tree has runtime prefetching\n // enabled. Will do this as a follow-up refactor. Might want to remove\n // the special metatdata case below first. In the meantime, it's not\n // really that much duplication, just would be nice to remove one of\n // these codepaths.\n const spawnedEntries = new Map<\n SegmentRequestKey,\n PendingSegmentCacheEntry\n >()\n pingRuntimeHead(now, task, route, spawnedEntries, fetchStrategy)\n const dynamicRequestTree = diffRouteTreeAgainstCurrent(\n now,\n task,\n route,\n task.treeAtTimeOfPrefetch,\n tree,\n spawnedEntries,\n fetchStrategy\n )\n let needsDynamicRequest = spawnedEntries.size > 0\n if (needsDynamicRequest) {\n spawnPrefetchSubtask(\n fetchSegmentPrefetchesUsingDynamicRequest(\n task,\n route,\n fetchStrategy,\n dynamicRequestTree,\n spawnedEntries\n )\n )\n }\n return PrefetchTaskExitStatus.Done\n }\n default:\n fetchStrategy satisfies never\n }\n break\n }\n default: {\n route satisfies never\n }\n }\n return PrefetchTaskExitStatus.Done\n}\n\nfunction pingStaticHead(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry\n): void {\n // The Head data for a page (metadata, viewport) is not really a route\n // segment, in the sense that it doesn't appear in the route tree. But we\n // store it in the cache as if it were, using a special key.\n pingStaticSegmentData(\n now,\n task,\n route,\n readOrCreateSegmentCacheEntry(\n now,\n FetchStrategy.PPR,\n route,\n route.metadata\n ),\n task.key,\n route.metadata\n )\n}\n\nfunction pingRuntimeHead(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,\n fetchStrategy:\n | FetchStrategy.Full\n | FetchStrategy.PPRRuntime\n | FetchStrategy.LoadingBoundary\n): void {\n pingRouteTreeAndIncludeDynamicData(\n now,\n task,\n route,\n route.metadata,\n false,\n spawnedEntries,\n // When prefetching the head, there's no difference between Full\n // and LoadingBoundary\n fetchStrategy === FetchStrategy.LoadingBoundary\n ? FetchStrategy.Full\n : fetchStrategy\n )\n}\n\n// TODO: Rename dynamic -> runtime throughout this module\n\nfunction pingSharedPartOfCacheComponentsTree(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n oldTree: FlightRouterState,\n newTree: RouteTree\n): PrefetchTaskExitStatus {\n // When Cache Components is enabled (or PPR, or a fully static route when PPR\n // is disabled; those cases are treated equivalently to Cache Components), we\n // start by prefetching each segment individually. Once we reach the \"new\"\n // part of the tree — the part that doesn't exist on the current page — we\n // may choose to switch to a runtime prefetch instead, based on the\n // information sent by the server in the route tree.\n //\n // The traversal starts in the \"shared\" part of the tree. Once we reach the\n // \"new\" part of the tree, we switch to a different traversal,\n // pingNewPartOfCacheComponentsTree.\n\n // Prefetch this segment's static data.\n const segment = readOrCreateSegmentCacheEntry(\n now,\n task.fetchStrategy,\n route,\n newTree\n )\n pingStaticSegmentData(now, task, route, segment, task.key, newTree)\n\n // Recursively ping the children.\n const oldTreeChildren = oldTree[1]\n const newTreeChildren = newTree.slots\n if (newTreeChildren !== null) {\n for (const parallelRouteKey in newTreeChildren) {\n if (!hasNetworkBandwidth(task)) {\n // Stop prefetching segments until there's more bandwidth.\n return PrefetchTaskExitStatus.InProgress\n }\n const newTreeChild = newTreeChildren[parallelRouteKey]\n const newTreeChildSegment = newTreeChild.segment\n const oldTreeChild: FlightRouterState | void =\n oldTreeChildren[parallelRouteKey]\n const oldTreeChildSegment: FlightRouterStateSegment | void =\n oldTreeChild?.[0]\n let childExitStatus\n if (\n oldTreeChildSegment !== undefined &&\n doesCurrentSegmentMatchCachedSegment(\n route,\n newTreeChildSegment,\n oldTreeChildSegment\n )\n ) {\n // We're still in the \"shared\" part of the tree.\n childExitStatus = pingSharedPartOfCacheComponentsTree(\n now,\n task,\n route,\n oldTreeChild,\n newTreeChild\n )\n } else {\n // We've entered the \"new\" part of the tree. Switch\n // traversal functions.\n childExitStatus = pingNewPartOfCacheComponentsTree(\n now,\n task,\n route,\n newTreeChild\n )\n }\n if (childExitStatus === PrefetchTaskExitStatus.InProgress) {\n // Child yielded without finishing.\n return PrefetchTaskExitStatus.InProgress\n }\n }\n }\n\n return PrefetchTaskExitStatus.Done\n}\n\nfunction pingNewPartOfCacheComponentsTree(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree\n): PrefetchTaskExitStatus.InProgress | PrefetchTaskExitStatus.Done {\n // We're now prefetching in the \"new\" part of the tree, the part that doesn't\n // exist on the current page. (In other words, we're deeper than the\n // shared layouts.) Segments in here default to being prefetched statically.\n // However, if the server instructs us to, we may switch to a runtime\n // prefetch instead. Traverse the tree and check at each segment.\n if (tree.hasRuntimePrefetch) {\n // This route has a runtime prefetch response. Since we're below the shared\n // layout, everything from this point should be prefetched using a single,\n // combined runtime request, rather than using per-segment static requests.\n // This is true even if some of the child segments are known to be fully\n // static — once we've decided to perform a runtime prefetch, we might as\n // well respond with the static segments in the same roundtrip. (That's how\n // regular navigations work, too.) We'll still skip over segments that are\n // already cached, though.\n //\n // It's the server's responsibility to set a reasonable value of\n // `hasRuntimePrefetch`. Currently it's user-defined, but eventually, the\n // server may send a value of `false` even if the user opts in, if it\n // determines during build that the route is always fully static. There are\n // more optimizations we can do once we implement fallback param\n // tracking, too.\n //\n // Use the task object to collect the segments that need a runtime prefetch.\n // This will signal to the outer task queue that a second traversal is\n // required to construct a request tree.\n if (task.spawnedRuntimePrefetches === null) {\n task.spawnedRuntimePrefetches = new Set([tree.requestKey])\n } else {\n task.spawnedRuntimePrefetches.add(tree.requestKey)\n }\n // Then exit the traversal without prefetching anything further.\n return PrefetchTaskExitStatus.Done\n }\n\n // This segment should not be runtime prefetched. Prefetch its static data.\n const segment = readOrCreateSegmentCacheEntry(\n now,\n task.fetchStrategy,\n route,\n tree\n )\n pingStaticSegmentData(now, task, route, segment, task.key, tree)\n if (tree.slots !== null) {\n if (!hasNetworkBandwidth(task)) {\n // Stop prefetching segments until there's more bandwidth.\n return PrefetchTaskExitStatus.InProgress\n }\n // Recursively ping the children.\n for (const parallelRouteKey in tree.slots) {\n const childTree = tree.slots[parallelRouteKey]\n const childExitStatus = pingNewPartOfCacheComponentsTree(\n now,\n task,\n route,\n childTree\n )\n if (childExitStatus === PrefetchTaskExitStatus.InProgress) {\n // Child yielded without finishing.\n return PrefetchTaskExitStatus.InProgress\n }\n }\n }\n // This segment and all its children have finished prefetching.\n return PrefetchTaskExitStatus.Done\n}\n\nfunction diffRouteTreeAgainstCurrent(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n oldTree: FlightRouterState,\n newTree: RouteTree,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,\n fetchStrategy:\n | FetchStrategy.Full\n | FetchStrategy.PPRRuntime\n | FetchStrategy.LoadingBoundary\n): FlightRouterState {\n // This is a single recursive traversal that does multiple things:\n // - Finds the parts of the target route (newTree) that are not part of\n // of the current page (oldTree) by diffing them, using the same algorithm\n // as a real navigation.\n // - Constructs a request tree (FlightRouterState) that describes which\n // segments need to be prefetched and which ones are already cached.\n // - Creates a set of pending cache entries for the segments that need to\n // be prefetched, so that a subsequent prefetch task does not request the\n // same segments again.\n const oldTreeChildren = oldTree[1]\n const newTreeChildren = newTree.slots\n let requestTreeChildren: Record<string, FlightRouterState> = {}\n if (newTreeChildren !== null) {\n for (const parallelRouteKey in newTreeChildren) {\n const newTreeChild = newTreeChildren[parallelRouteKey]\n const newTreeChildSegment = newTreeChild.segment\n const oldTreeChild: FlightRouterState | void =\n oldTreeChildren[parallelRouteKey]\n const oldTreeChildSegment: FlightRouterStateSegment | void =\n oldTreeChild?.[0]\n if (\n oldTreeChildSegment !== undefined &&\n doesCurrentSegmentMatchCachedSegment(\n route,\n newTreeChildSegment,\n oldTreeChildSegment\n )\n ) {\n // This segment is already part of the current route. Keep traversing.\n const requestTreeChild = diffRouteTreeAgainstCurrent(\n now,\n task,\n route,\n oldTreeChild,\n newTreeChild,\n spawnedEntries,\n fetchStrategy\n )\n requestTreeChildren[parallelRouteKey] = requestTreeChild\n } else {\n // This segment is not part of the current route. We're entering a\n // part of the tree that we need to prefetch (unless everything is\n // already cached).\n switch (fetchStrategy) {\n case FetchStrategy.LoadingBoundary: {\n // When PPR is disabled, we can't prefetch per segment. We must\n // fallback to the old prefetch behavior and send a dynamic request.\n // Only routes that include a loading boundary can be prefetched in\n // this way.\n //\n // This is simlar to a \"full\" prefetch, but we're much more\n // conservative about which segments to include in the request.\n //\n // The server will only render up to the first loading boundary\n // inside new part of the tree. If there's no loading boundary\n // anywhere in the tree, the server will never return any data, so\n // we can skip the request.\n const subtreeHasLoadingBoundary =\n newTreeChild.hasLoadingBoundary !==\n HasLoadingBoundary.SubtreeHasNoLoadingBoundary\n const requestTreeChild = subtreeHasLoadingBoundary\n ? pingPPRDisabledRouteTreeUpToLoadingBoundary(\n now,\n task,\n route,\n newTreeChild,\n null,\n spawnedEntries\n )\n : // There's no loading boundary within this tree. Bail out.\n convertRouteTreeToFlightRouterState(newTreeChild)\n requestTreeChildren[parallelRouteKey] = requestTreeChild\n break\n }\n case FetchStrategy.PPRRuntime: {\n // This is a runtime prefetch. Fetch all cacheable data in the tree,\n // not just the static PPR shell.\n const requestTreeChild = pingRouteTreeAndIncludeDynamicData(\n now,\n task,\n route,\n newTreeChild,\n false,\n spawnedEntries,\n fetchStrategy\n )\n requestTreeChildren[parallelRouteKey] = requestTreeChild\n break\n }\n case FetchStrategy.Full: {\n // This is a \"full\" prefetch. Fetch all the data in the tree, both\n // static and dynamic. We issue roughly the same request that we\n // would during a real navigation. The goal is that once the\n // navigation occurs, the router should not have to fetch any\n // additional data.\n //\n // Although the response will include dynamic data, opting into a\n // Full prefetch — via <Link prefetch={true}> — implicitly\n // instructs the cache to treat the response as \"static\", or non-\n // dynamic, since the whole point is to cache it for\n // future navigations.\n //\n // Construct a tree (currently a FlightRouterState) that represents\n // which segments need to be prefetched and which ones are already\n // cached. If the tree is empty, then we can exit. Otherwise, we'll\n // send the request tree to the server and use the response to\n // populate the segment cache.\n const requestTreeChild = pingRouteTreeAndIncludeDynamicData(\n now,\n task,\n route,\n newTreeChild,\n false,\n spawnedEntries,\n fetchStrategy\n )\n requestTreeChildren[parallelRouteKey] = requestTreeChild\n break\n }\n default:\n fetchStrategy satisfies never\n }\n }\n }\n }\n const requestTree: FlightRouterState = [\n newTree.segment,\n requestTreeChildren,\n null,\n null,\n newTree.isRootLayout,\n ]\n return requestTree\n}\n\nfunction pingPPRDisabledRouteTreeUpToLoadingBoundary(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree,\n refetchMarkerContext: 'refetch' | 'inside-shared-layout' | null,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>\n): FlightRouterState {\n // This function is similar to pingRouteTreeAndIncludeDynamicData, except the\n // server is only going to return a minimal loading state — it will stop\n // rendering at the first loading boundary. Whereas a Full prefetch is\n // intentionally aggressive and tries to pretfetch all the data that will be\n // needed for a navigation, a LoadingBoundary prefetch is much more\n // conservative. For example, it will omit from the request tree any segment\n // that is already cached, regardles of whether it's partial or full. By\n // contrast, a Full prefetch will refetch partial segments.\n\n // \"inside-shared-layout\" tells the server where to start looking for a\n // loading boundary.\n let refetchMarker: 'refetch' | 'inside-shared-layout' | null =\n refetchMarkerContext === null ? 'inside-shared-layout' : null\n\n const segment = readOrCreateSegmentCacheEntry(\n now,\n task.fetchStrategy,\n route,\n tree\n )\n switch (segment.status) {\n case EntryStatus.Empty: {\n // This segment is not cached. Add a refetch marker so the server knows\n // to start rendering here.\n // TODO: Instead of a \"refetch\" marker, we could just omit this subtree's\n // FlightRouterState from the request tree. I think this would probably\n // already work even without any updates to the server. For consistency,\n // though, I'll send the full tree and we'll look into this later as part\n // of a larger redesign of the request protocol.\n\n // Add the pending cache entry to the result map.\n spawnedEntries.set(\n tree.requestKey,\n upgradeToPendingSegment(\n segment,\n // Set the fetch strategy to LoadingBoundary to indicate that the server\n // might not include it in the pending response. If another route is able\n // to issue a per-segment request, we'll do that in the background.\n FetchStrategy.LoadingBoundary\n )\n )\n if (refetchMarkerContext !== 'refetch') {\n refetchMarker = refetchMarkerContext = 'refetch'\n } else {\n // There's already a parent with a refetch marker, so we don't need\n // to add another one.\n }\n break\n }\n case EntryStatus.Fulfilled: {\n // The segment is already cached.\n const segmentHasLoadingBoundary =\n tree.hasLoadingBoundary === HasLoadingBoundary.SegmentHasLoadingBoundary\n if (segmentHasLoadingBoundary) {\n // This segment has a loading boundary, which means the server won't\n // render its children. So there's nothing left to prefetch along this\n // path. We can bail out.\n return convertRouteTreeToFlightRouterState(tree)\n }\n // NOTE: If the cached segment were fetched using PPR, then it might be\n // partial. We could get a more complete version of the segment by\n // including it in this non-PPR request.\n //\n // We're intentionally choosing not to, though, because it's generally\n // better to avoid doing a full prefetch whenever possible.\n break\n }\n case EntryStatus.Pending: {\n // There's another prefetch currently in progress. Don't add the refetch\n // marker yet, so the server knows it can skip rendering this segment.\n break\n }\n case EntryStatus.Rejected: {\n // The segment failed to load. We shouldn't issue another request until\n // the stale time has elapsed.\n break\n }\n default:\n segment satisfies never\n }\n const requestTreeChildren: Record<string, FlightRouterState> = {}\n if (tree.slots !== null) {\n for (const parallelRouteKey in tree.slots) {\n const childTree = tree.slots[parallelRouteKey]\n requestTreeChildren[parallelRouteKey] =\n pingPPRDisabledRouteTreeUpToLoadingBoundary(\n now,\n task,\n route,\n childTree,\n refetchMarkerContext,\n spawnedEntries\n )\n }\n }\n const requestTree: FlightRouterState = [\n tree.segment,\n requestTreeChildren,\n null,\n refetchMarker,\n tree.isRootLayout,\n ]\n return requestTree\n}\n\nfunction pingRouteTreeAndIncludeDynamicData(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree,\n isInsideRefetchingParent: boolean,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,\n fetchStrategy: FetchStrategy.Full | FetchStrategy.PPRRuntime\n): FlightRouterState {\n // The tree we're constructing is the same shape as the tree we're navigating\n // to. But even though this is a \"new\" tree, some of the individual segments\n // may be cached as a result of other route prefetches.\n //\n // So we need to find the first uncached segment along each path add an\n // explicit \"refetch\" marker so the server knows where to start rendering.\n // Once the server starts rendering along a path, it keeps rendering the\n // entire subtree.\n const segment = readOrCreateSegmentCacheEntry(\n now,\n // Note that `fetchStrategy` might be different from `task.fetchStrategy`,\n // and we have to use the former here.\n // We can have a task with `FetchStrategy.PPR` where some of its segments are configured to\n // always use runtime prefetching (via `export const prefetch`), and those should check for\n // entries that include search params.\n fetchStrategy,\n route,\n tree\n )\n\n let spawnedSegment: PendingSegmentCacheEntry | null = null\n\n switch (segment.status) {\n case EntryStatus.Empty: {\n // This segment is not cached. Include it in the request.\n spawnedSegment = upgradeToPendingSegment(segment, fetchStrategy)\n break\n }\n case EntryStatus.Fulfilled: {\n // The segment is already cached.\n if (\n segment.isPartial &&\n canNewFetchStrategyProvideMoreContent(\n segment.fetchStrategy,\n fetchStrategy\n )\n ) {\n // The cached segment contains dynamic holes, and was prefetched using a less specific strategy than the current one.\n // This means we're in one of these cases:\n // - we have a static prefetch, and we're doing a runtime prefetch\n // - we have a static or runtime prefetch, and we're doing a Full prefetch (or a navigation).\n // In either case, we need to include it in the request to get a more specific (or full) version.\n spawnedSegment = pingFullSegmentRevalidation(\n now,\n route,\n tree,\n fetchStrategy\n )\n }\n break\n }\n case EntryStatus.Pending:\n case EntryStatus.Rejected: {\n // There's either another prefetch currently in progress, or the previous\n // attempt failed. If the new strategy can provide more content, fetch it again.\n if (\n canNewFetchStrategyProvideMoreContent(\n segment.fetchStrategy,\n fetchStrategy\n )\n ) {\n spawnedSegment = pingFullSegmentRevalidation(\n now,\n route,\n tree,\n fetchStrategy\n )\n }\n break\n }\n default:\n segment satisfies never\n }\n const requestTreeChildren: Record<string, FlightRouterState> = {}\n if (tree.slots !== null) {\n for (const parallelRouteKey in tree.slots) {\n const childTree = tree.slots[parallelRouteKey]\n requestTreeChildren[parallelRouteKey] =\n pingRouteTreeAndIncludeDynamicData(\n now,\n task,\n route,\n childTree,\n isInsideRefetchingParent || spawnedSegment !== null,\n spawnedEntries,\n fetchStrategy\n )\n }\n }\n\n if (spawnedSegment !== null) {\n // Add the pending entry to the result map.\n spawnedEntries.set(tree.requestKey, spawnedSegment)\n }\n\n // Don't bother to add a refetch marker if one is already present in a parent.\n const refetchMarker =\n !isInsideRefetchingParent && spawnedSegment !== null ? 'refetch' : null\n\n const requestTree: FlightRouterState = [\n tree.segment,\n requestTreeChildren,\n null,\n refetchMarker,\n tree.isRootLayout,\n ]\n return requestTree\n}\n\nfunction pingRuntimePrefetches(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree,\n spawnedRuntimePrefetches: Set<SegmentRequestKey>,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>\n): FlightRouterState {\n // Construct a request tree (FlightRouterState) for a runtime prefetch. If\n // a segment is part of the runtime prefetch, the tree is constructed by\n // diffing against what's already in the prefetch cache. Otherwise, we send\n // a regular FlightRouterState with no special markers.\n //\n // See pingRouteTreeAndIncludeDynamicData for details.\n if (spawnedRuntimePrefetches.has(tree.requestKey)) {\n // This segment needs a runtime prefetch.\n return pingRouteTreeAndIncludeDynamicData(\n now,\n task,\n route,\n tree,\n false,\n spawnedEntries,\n FetchStrategy.PPRRuntime\n )\n }\n let requestTreeChildren: Record<string, FlightRouterState> = {}\n const slots = tree.slots\n if (slots !== null) {\n for (const parallelRouteKey in slots) {\n const childTree = slots[parallelRouteKey]\n requestTreeChildren[parallelRouteKey] = pingRuntimePrefetches(\n now,\n task,\n route,\n childTree,\n spawnedRuntimePrefetches,\n spawnedEntries\n )\n }\n }\n\n // This segment is not part of the runtime prefetch. Clone the base tree.\n const requestTree: FlightRouterState = [\n tree.segment,\n requestTreeChildren,\n null,\n null,\n ]\n return requestTree\n}\n\nfunction pingStaticSegmentData(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n segment: SegmentCacheEntry,\n routeKey: RouteCacheKey,\n tree: RouteTree\n): void {\n switch (segment.status) {\n case EntryStatus.Empty:\n // Upgrade to Pending so we know there's already a request in progress\n spawnPrefetchSubtask(\n fetchSegmentOnCacheMiss(\n route,\n upgradeToPendingSegment(segment, FetchStrategy.PPR),\n routeKey,\n tree\n )\n )\n break\n case EntryStatus.Pending: {\n // There's already a request in progress. Depending on what kind of\n // request it is, we may want to revalidate it.\n switch (segment.fetchStrategy) {\n case FetchStrategy.PPR:\n case FetchStrategy.PPRRuntime:\n case FetchStrategy.Full:\n // There's already a request in progress. Don't do anything.\n break\n case FetchStrategy.LoadingBoundary:\n // There's a pending request, but because it's using the old\n // prefetching strategy, we can't be sure if it will be fulfilled by\n // the response — it might be inside the loading boundary. Perform\n // a revalidation, but because it's speculative, wait to do it at\n // background priority.\n if (background(task)) {\n // TODO: Instead of speculatively revalidating, consider including\n // `hasLoading` in the route tree prefetch response.\n pingPPRSegmentRevalidation(now, route, routeKey, tree)\n }\n break\n default:\n segment.fetchStrategy satisfies never\n }\n break\n }\n case EntryStatus.Rejected: {\n // The existing entry in the cache was rejected. Depending on how it\n // was originally fetched, we may or may not want to revalidate it.\n switch (segment.fetchStrategy) {\n case FetchStrategy.PPR:\n case FetchStrategy.PPRRuntime:\n case FetchStrategy.Full:\n // The previous attempt to fetch this entry failed. Don't attempt to\n // fetch it again until the entry expires.\n break\n case FetchStrategy.LoadingBoundary:\n // There's a rejected entry, but it was fetched using the loading\n // boundary strategy. So the reason it wasn't returned by the server\n // might just be because it was inside a loading boundary. Or because\n // there was a dynamic rewrite. Revalidate it using the per-\n // segment strategy.\n //\n // Because a rejected segment will definitely prevent the segment (and\n // all of its children) from rendering, we perform this revalidation\n // immediately instead of deferring it to a background task.\n pingPPRSegmentRevalidation(now, route, routeKey, tree)\n break\n default:\n segment.fetchStrategy satisfies never\n }\n break\n }\n case EntryStatus.Fulfilled:\n // Segment is already cached. There's nothing left to prefetch.\n break\n default:\n segment satisfies never\n }\n\n // Segments do not have dependent tasks, so once the prefetch is initiated,\n // there's nothing else for us to do (except write the server data into the\n // entry, which is handled by `fetchSegmentOnCacheMiss`).\n}\n\nfunction pingPPRSegmentRevalidation(\n now: number,\n route: FulfilledRouteCacheEntry,\n routeKey: RouteCacheKey,\n tree: RouteTree\n): void {\n const revalidatingSegment = readOrCreateRevalidatingSegmentEntry(\n now,\n FetchStrategy.PPR,\n route,\n tree\n )\n switch (revalidatingSegment.status) {\n case EntryStatus.Empty:\n // Spawn a prefetch request and upsert the segment into the cache\n // upon completion.\n upsertSegmentOnCompletion(\n spawnPrefetchSubtask(\n fetchSegmentOnCacheMiss(\n route,\n upgradeToPendingSegment(revalidatingSegment, FetchStrategy.PPR),\n routeKey,\n tree\n )\n ),\n getSegmentVaryPathForRequest(FetchStrategy.PPR, tree)\n )\n break\n case EntryStatus.Pending:\n // There's already a revalidation in progress.\n break\n case EntryStatus.Fulfilled:\n case EntryStatus.Rejected:\n // A previous revalidation attempt finished, but we chose not to replace\n // the existing entry in the cache. Don't try again until or unless the\n // revalidation entry expires.\n break\n default:\n revalidatingSegment satisfies never\n }\n}\n\nfunction pingFullSegmentRevalidation(\n now: number,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree,\n fetchStrategy: FetchStrategy.Full | FetchStrategy.PPRRuntime\n): PendingSegmentCacheEntry | null {\n const revalidatingSegment = readOrCreateRevalidatingSegmentEntry(\n now,\n fetchStrategy,\n route,\n tree\n )\n if (revalidatingSegment.status === EntryStatus.Empty) {\n // During a Full/PPRRuntime prefetch, a single dynamic request is made for all the\n // segments that we need. So we don't initiate a request here directly. By\n // returning a pending entry from this function, it signals to the caller\n // that this segment should be included in the request that's sent to\n // the server.\n const pendingSegment = upgradeToPendingSegment(\n revalidatingSegment,\n fetchStrategy\n )\n upsertSegmentOnCompletion(\n waitForSegmentCacheEntry(pendingSegment),\n getSegmentVaryPathForRequest(fetchStrategy, tree)\n )\n return pendingSegment\n } else {\n // There's already a revalidation in progress.\n const nonEmptyRevalidatingSegment = revalidatingSegment\n if (\n canNewFetchStrategyProvideMoreContent(\n nonEmptyRevalidatingSegment.fetchStrategy,\n fetchStrategy\n )\n ) {\n // The existing revalidation was fetched using a less specific strategy.\n // Reset it and start a new revalidation.\n const emptySegment = overwriteRevalidatingSegmentCacheEntry(\n fetchStrategy,\n route,\n tree\n )\n const pendingSegment = upgradeToPendingSegment(\n emptySegment,\n fetchStrategy\n )\n upsertSegmentOnCompletion(\n waitForSegmentCacheEntry(pendingSegment),\n getSegmentVaryPathForRequest(fetchStrategy, tree)\n )\n return pendingSegment\n }\n switch (nonEmptyRevalidatingSegment.status) {\n case EntryStatus.Pending:\n // There's already an in-progress prefetch that includes this segment.\n return null\n case EntryStatus.Fulfilled:\n case EntryStatus.Rejected:\n // A previous revalidation attempt finished, but we chose not to replace\n // the existing entry in the cache. Don't try again until or unless the\n // revalidation entry expires.\n return null\n default:\n nonEmptyRevalidatingSegment satisfies never\n return null\n }\n }\n}\n\nconst noop = () => {}\n\nfunction upsertSegmentOnCompletion(\n promise: Promise<FulfilledSegmentCacheEntry | null>,\n varyPath: SegmentVaryPath\n) {\n // Wait for a segment to finish loading, then upsert it into the cache\n promise.then((fulfilled) => {\n if (fulfilled !== null) {\n // Received new data. Attempt to replace the existing entry in the cache.\n upsertSegmentEntry(Date.now(), varyPath, fulfilled)\n }\n }, noop)\n}\n\nfunction doesCurrentSegmentMatchCachedSegment(\n route: FulfilledRouteCacheEntry,\n currentSegment: Segment,\n cachedSegment: Segment\n): boolean {\n if (cachedSegment === PAGE_SEGMENT_KEY) {\n // In the FlightRouterState stored by the router, the page segment has the\n // rendered search params appended to the name of the segment. In the\n // prefetch cache, however, this is stored separately. So, when comparing\n // the router's current FlightRouterState to the cached FlightRouterState,\n // we need to make sure we compare both parts of the segment.\n // TODO: This is not modeled clearly. We use the same type,\n // FlightRouterState, for both the CacheNode tree _and_ the prefetch cache\n // _and_ the server response format, when conceptually those are three\n // different things and treated in different ways. We should encode more of\n // this information into the type design so mistakes are less likely.\n return (\n currentSegment ===\n addSearchParamsIfPageSegment(\n PAGE_SEGMENT_KEY,\n Object.fromEntries(new URLSearchParams(route.renderedSearch))\n )\n )\n }\n // Non-page segments are compared using the same function as the server\n return matchSegment(cachedSegment, currentSegment)\n}\n\n// -----------------------------------------------------------------------------\n// The remainder of the module is a MinHeap implementation. Try not to put any\n// logic below here unless it's related to the heap algorithm. We can extract\n// this to a separate module if/when we need multiple kinds of heaps.\n// -----------------------------------------------------------------------------\n\nfunction compareQueuePriority(a: PrefetchTask, b: PrefetchTask) {\n // Since the queue is a MinHeap, this should return a positive number if b is\n // higher priority than a, and a negative number if a is higher priority\n // than b.\n\n // `priority` is an integer, where higher numbers are higher priority.\n const priorityDiff = b.priority - a.priority\n if (priorityDiff !== 0) {\n return priorityDiff\n }\n\n // If the priority is the same, check which phase the prefetch is in — is it\n // prefetching the route tree, or the segments? Route trees are prioritized.\n const phaseDiff = b.phase - a.phase\n if (phaseDiff !== 0) {\n return phaseDiff\n }\n\n // Finally, check the insertion order. `sortId` is an incrementing counter\n // assigned to prefetches. We want to process the newest prefetches first.\n return b.sortId - a.sortId\n}\n\nfunction heapPush(heap: Array<PrefetchTask>, node: PrefetchTask): void {\n const index = heap.length\n heap.push(node)\n node._heapIndex = index\n heapSiftUp(heap, node, index)\n}\n\nfunction heapPeek(heap: Array<PrefetchTask>): PrefetchTask | null {\n return heap.length === 0 ? null : heap[0]\n}\n\nfunction heapPop(heap: Array<PrefetchTask>): PrefetchTask | null {\n if (heap.length === 0) {\n return null\n }\n const first = heap[0]\n first._heapIndex = -1\n const last = heap.pop() as PrefetchTask\n if (last !== first) {\n heap[0] = last\n last._heapIndex = 0\n heapSiftDown(heap, last, 0)\n }\n return first\n}\n\nfunction heapDelete(heap: Array<PrefetchTask>, node: PrefetchTask): void {\n const index = node._heapIndex\n if (index !== -1) {\n node._heapIndex = -1\n if (heap.length !== 0) {\n const last = heap.pop() as PrefetchTask\n if (last !== node) {\n heap[index] = last\n last._heapIndex = index\n heapSiftDown(heap, last, index)\n }\n }\n }\n}\n\nfunction heapResift(heap: Array<PrefetchTask>, node: PrefetchTask): void {\n const index = node._heapIndex\n if (index !== -1) {\n if (index === 0) {\n heapSiftDown(heap, node, 0)\n } else {\n const parentIndex = (index - 1) >>> 1\n const parent = heap[parentIndex]\n if (compareQueuePriority(parent, node) > 0) {\n // The parent is larger. Sift up.\n heapSiftUp(heap, node, index)\n } else {\n // The parent is smaller (or equal). Sift down.\n heapSiftDown(heap, node, index)\n }\n }\n }\n}\n\nfunction heapSiftUp(\n heap: Array<PrefetchTask>,\n node: PrefetchTask,\n i: number\n): void {\n let index = i\n while (index > 0) {\n const parentIndex = (index - 1) >>> 1\n const parent = heap[parentIndex]\n if (compareQueuePriority(parent, node) > 0) {\n // The parent is larger. Swap positions.\n heap[parentIndex] = node\n node._heapIndex = parentIndex\n heap[index] = parent\n parent._heapIndex = index\n\n index = parentIndex\n } else {\n // The parent is smaller. Exit.\n return\n }\n }\n}\n\nfunction heapSiftDown(\n heap: Array<PrefetchTask>,\n node: PrefetchTask,\n i: number\n): void {\n let index = i\n const length = heap.length\n const halfLength = length >>> 1\n while (index < halfLength) {\n const leftIndex = (index + 1) * 2 - 1\n const left = heap[leftIndex]\n const rightIndex = leftIndex + 1\n const right = heap[rightIndex]\n\n // If the left or right node is smaller, swap with the smaller of those.\n if (compareQueuePriority(left, node) < 0) {\n if (rightIndex < length && compareQueuePriority(right, left) < 0) {\n heap[index] = right\n right._heapIndex = index\n heap[rightIndex] = node\n node._heapIndex = rightIndex\n\n index = rightIndex\n } else {\n heap[index] = left\n left._heapIndex = index\n heap[leftIndex] = node\n node._heapIndex = leftIndex\n\n index = leftIndex\n }\n } else if (rightIndex < length && compareQueuePriority(right, node) < 0) {\n heap[index] = right\n right._heapIndex = index\n heap[rightIndex] = node\n node._heapIndex = rightIndex\n\n index = rightIndex\n } else {\n // Neither child is smaller. Exit.\n return\n }\n }\n}\n","import type { FlightRouterState } from '../../shared/lib/app-router-types'\nimport type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime'\nimport {\n FetchStrategy,\n type PrefetchTaskFetchStrategy,\n PrefetchPriority,\n} from './segment-cache/types'\nimport { createCacheKey } from './segment-cache/cache-key'\nimport {\n type PrefetchTask,\n schedulePrefetchTask as scheduleSegmentPrefetchTask,\n cancelPrefetchTask,\n reschedulePrefetchTask,\n isPrefetchTaskDirty,\n} from './segment-cache/scheduler'\nimport { startTransition } from 'react'\n\ntype LinkElement = HTMLAnchorElement | SVGAElement\n\ntype Element = LinkElement | HTMLFormElement\n\n// Properties that are shared between Link and Form instances. We use the same\n// shape for both to prevent a polymorphic de-opt in the VM.\ntype LinkOrFormInstanceShared = {\n router: AppRouterInstance\n fetchStrategy: PrefetchTaskFetchStrategy\n\n isVisible: boolean\n\n // The most recently initiated prefetch task. It may or may not have\n // already completed. The same prefetch task object can be reused across\n // multiple prefetches of the same link.\n prefetchTask: PrefetchTask | null\n}\n\nexport type FormInstance = LinkOrFormInstanceShared & {\n prefetchHref: string\n setOptimisticLinkStatus: null\n}\n\ntype PrefetchableLinkInstance = LinkOrFormInstanceShared & {\n prefetchHref: string\n setOptimisticLinkStatus: (status: { pending: boolean }) => void\n}\n\ntype NonPrefetchableLinkInstance = LinkOrFormInstanceShared & {\n prefetchHref: null\n setOptimisticLinkStatus: (status: { pending: boolean }) => void\n}\n\ntype PrefetchableInstance = PrefetchableLinkInstance | FormInstance\n\nexport type LinkInstance =\n | PrefetchableLinkInstance\n | NonPrefetchableLinkInstance\n\n// Tracks the most recently navigated link instance. When null, indicates\n// the current navigation was not initiated by a link click.\nlet linkForMostRecentNavigation: LinkInstance | null = null\n\n// Status object indicating link is pending\nexport const PENDING_LINK_STATUS = { pending: true }\n\n// Status object indicating link is idle\nexport const IDLE_LINK_STATUS = { pending: false }\n\n// Updates the loading state when navigating between links\n// - Resets the previous link's loading state\n// - Sets the new link's loading state\n// - Updates tracking of current navigation\nexport function setLinkForCurrentNavigation(link: LinkInstance | null) {\n startTransition(() => {\n linkForMostRecentNavigation?.setOptimisticLinkStatus(IDLE_LINK_STATUS)\n link?.setOptimisticLinkStatus(PENDING_LINK_STATUS)\n linkForMostRecentNavigation = link\n })\n}\n\n// Unmounts the current link instance from navigation tracking\nexport function unmountLinkForCurrentNavigation(link: LinkInstance) {\n if (linkForMostRecentNavigation === link) {\n linkForMostRecentNavigation = null\n }\n}\n\n// Use a WeakMap to associate a Link instance with its DOM element. This is\n// used by the IntersectionObserver to track the link's visibility.\nconst prefetchable:\n | WeakMap<Element, PrefetchableInstance>\n | Map<Element, PrefetchableInstance> =\n typeof WeakMap === 'function' ? new WeakMap() : new Map()\n\n// A Set of the currently visible links. We re-prefetch visible links after a\n// cache invalidation, or when the current URL changes. It's a separate data\n// structure from the WeakMap above because only the visible links need to\n// be enumerated.\nconst prefetchableAndVisible: Set<PrefetchableInstance> = new Set()\n\n// A single IntersectionObserver instance shared by all <Link> components.\nconst observer: IntersectionObserver | null =\n typeof IntersectionObserver === 'function'\n ? new IntersectionObserver(handleIntersect, {\n rootMargin: '200px',\n })\n : null\n\nfunction observeVisibility(element: Element, instance: PrefetchableInstance) {\n const existingInstance = prefetchable.get(element)\n if (existingInstance !== undefined) {\n // This shouldn't happen because each <Link> component should have its own\n // anchor tag instance, but it's defensive coding to avoid a memory leak in\n // case there's a logical error somewhere else.\n unmountPrefetchableInstance(element)\n }\n // Only track prefetchable links that have a valid prefetch URL\n prefetchable.set(element, instance)\n if (observer !== null) {\n observer.observe(element)\n }\n}\n\nfunction coercePrefetchableUrl(href: string): URL | null {\n if (typeof window !== 'undefined') {\n const { createPrefetchURL } =\n require('./app-router-utils') as typeof import('./app-router-utils')\n\n try {\n return createPrefetchURL(href)\n } catch {\n // createPrefetchURL sometimes throws an error if an invalid URL is\n // provided, though I'm not sure if it's actually necessary.\n // TODO: Consider removing the throw from the inner function, or change it\n // to reportError. Or maybe the error isn't even necessary for automatic\n // prefetches, just navigations.\n const reportErrorFn =\n typeof reportError === 'function' ? reportError : console.error\n reportErrorFn(\n `Cannot prefetch '${href}' because it cannot be converted to a URL.`\n )\n return null\n }\n } else {\n return null\n }\n}\n\nexport function mountLinkInstance(\n element: LinkElement,\n href: string,\n router: AppRouterInstance,\n fetchStrategy: PrefetchTaskFetchStrategy,\n prefetchEnabled: boolean,\n setOptimisticLinkStatus: (status: { pending: boolean }) => void\n): LinkInstance {\n if (prefetchEnabled) {\n const prefetchURL = coercePrefetchableUrl(href)\n if (prefetchURL !== null) {\n const instance: PrefetchableLinkInstance = {\n router,\n fetchStrategy,\n isVisible: false,\n prefetchTask: null,\n prefetchHref: prefetchURL.href,\n setOptimisticLinkStatus,\n }\n // We only observe the link's visibility if it's prefetchable. For\n // example, this excludes links to external URLs.\n observeVisibility(element, instance)\n return instance\n }\n }\n // If the link is not prefetchable, we still create an instance so we can\n // track its optimistic state (i.e. useLinkStatus).\n const instance: NonPrefetchableLinkInstance = {\n router,\n fetchStrategy,\n isVisible: false,\n prefetchTask: null,\n prefetchHref: null,\n setOptimisticLinkStatus,\n }\n return instance\n}\n\nexport function mountFormInstance(\n element: HTMLFormElement,\n href: string,\n router: AppRouterInstance,\n fetchStrategy: PrefetchTaskFetchStrategy\n): void {\n const prefetchURL = coercePrefetchableUrl(href)\n if (prefetchURL === null) {\n // This href is not prefetchable, so we don't track it.\n // TODO: We currently observe/unobserve a form every time its href changes.\n // For Links, this isn't a big deal because the href doesn't usually change,\n // but for forms it's extremely common. We should optimize this.\n return\n }\n const instance: FormInstance = {\n router,\n fetchStrategy,\n isVisible: false,\n prefetchTask: null,\n prefetchHref: prefetchURL.href,\n setOptimisticLinkStatus: null,\n }\n observeVisibility(element, instance)\n}\n\nexport function unmountPrefetchableInstance(element: Element) {\n const instance = prefetchable.get(element)\n if (instance !== undefined) {\n prefetchable.delete(element)\n prefetchableAndVisible.delete(instance)\n const prefetchTask = instance.prefetchTask\n if (prefetchTask !== null) {\n cancelPrefetchTask(prefetchTask)\n }\n }\n if (observer !== null) {\n observer.unobserve(element)\n }\n}\n\nfunction handleIntersect(entries: Array<IntersectionObserverEntry>) {\n for (const entry of entries) {\n // Some extremely old browsers or polyfills don't reliably support\n // isIntersecting so we check intersectionRatio instead. (Do we care? Not\n // really. But whatever this is fine.)\n const isVisible = entry.intersectionRatio > 0\n onLinkVisibilityChanged(entry.target as HTMLAnchorElement, isVisible)\n }\n}\n\nexport function onLinkVisibilityChanged(element: Element, isVisible: boolean) {\n if (process.env.NODE_ENV !== 'production') {\n // Prefetching on viewport is disabled in development for performance\n // reasons, because it requires compiling the target page.\n // TODO: Investigate re-enabling this.\n return\n }\n\n const instance = prefetchable.get(element)\n if (instance === undefined) {\n return\n }\n\n instance.isVisible = isVisible\n if (isVisible) {\n prefetchableAndVisible.add(instance)\n } else {\n prefetchableAndVisible.delete(instance)\n }\n rescheduleLinkPrefetch(instance, PrefetchPriority.Default)\n}\n\nexport function onNavigationIntent(\n element: HTMLAnchorElement | SVGAElement,\n unstable_upgradeToDynamicPrefetch: boolean\n) {\n const instance = prefetchable.get(element)\n if (instance === undefined) {\n return\n }\n // Prefetch the link on hover/touchstart.\n if (instance !== undefined) {\n if (\n process.env.__NEXT_DYNAMIC_ON_HOVER &&\n unstable_upgradeToDynamicPrefetch\n ) {\n // Switch to a full prefetch\n instance.fetchStrategy = FetchStrategy.Full\n }\n rescheduleLinkPrefetch(instance, PrefetchPriority.Intent)\n }\n}\n\nfunction rescheduleLinkPrefetch(\n instance: PrefetchableInstance,\n priority: PrefetchPriority.Default | PrefetchPriority.Intent\n) {\n // Ensures that app-router-instance is not compiled in the server bundle\n if (typeof window !== 'undefined') {\n const existingPrefetchTask = instance.prefetchTask\n\n if (!instance.isVisible) {\n // Cancel any in-progress prefetch task. (If it already finished then this\n // is a no-op.)\n if (existingPrefetchTask !== null) {\n cancelPrefetchTask(existingPrefetchTask)\n }\n // We don't need to reset the prefetchTask to null upon cancellation; an\n // old task object can be rescheduled with reschedulePrefetchTask. This is a\n // micro-optimization but also makes the code simpler (don't need to\n // worry about whether an old task object is stale).\n return\n }\n\n const { getCurrentAppRouterState } =\n require('./app-router-instance') as typeof import('./app-router-instance')\n\n const appRouterState = getCurrentAppRouterState()\n if (appRouterState !== null) {\n const treeAtTimeOfPrefetch = appRouterState.tree\n if (existingPrefetchTask === null) {\n // Initiate a prefetch task.\n const nextUrl = appRouterState.nextUrl\n const cacheKey = createCacheKey(instance.prefetchHref, nextUrl)\n instance.prefetchTask = scheduleSegmentPrefetchTask(\n cacheKey,\n treeAtTimeOfPrefetch,\n instance.fetchStrategy,\n priority,\n null\n )\n } else {\n // We already have an old task object that we can reschedule. This is\n // effectively the same as canceling the old task and creating a new one.\n reschedulePrefetchTask(\n existingPrefetchTask,\n treeAtTimeOfPrefetch,\n instance.fetchStrategy,\n priority\n )\n }\n }\n }\n}\n\nexport function pingVisibleLinks(\n nextUrl: string | null,\n tree: FlightRouterState\n) {\n // For each currently visible link, cancel the existing prefetch task (if it\n // exists) and schedule a new one. This is effectively the same as if all the\n // visible links left and then re-entered the viewport.\n //\n // This is called when the Next-Url or the base tree changes, since those\n // may affect the result of a prefetch task. It's also called after a\n // cache invalidation.\n for (const instance of prefetchableAndVisible) {\n const task = instance.prefetchTask\n if (task !== null && !isPrefetchTaskDirty(task, nextUrl, tree)) {\n // The cache has not been invalidated, and none of the inputs have\n // changed. Bail out.\n continue\n }\n // Something changed. Cancel the existing prefetch task and schedule a\n // new one.\n if (task !== null) {\n cancelPrefetchTask(task)\n }\n const cacheKey = createCacheKey(instance.prefetchHref, nextUrl)\n instance.prefetchTask = scheduleSegmentPrefetchTask(\n cacheKey,\n tree,\n instance.fetchStrategy,\n PrefetchPriority.Default,\n null\n )\n }\n}\n","import { parsePath } from './parse-path'\n\n/**\n * Checks if a given path starts with a given prefix. It ensures it matches\n * exactly without containing extra chars. e.g. prefix /docs should replace\n * for /docs, /docs/, /docs/a but not /docsss\n * @param path The path to check.\n * @param prefix The prefix to check against.\n */\nexport function pathHasPrefix(path: string, prefix: string) {\n if (typeof path !== 'string') {\n return false\n }\n\n const { pathname } = parsePath(path)\n return pathname === prefix || pathname.startsWith(prefix + '/')\n}\n","import { pathHasPrefix } from '../shared/lib/router/utils/path-has-prefix'\n\nconst basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''\n\nexport function hasBasePath(path: string): boolean {\n return pathHasPrefix(path, basePath)\n}\n","import { isAbsoluteUrl, getLocationOrigin } from '../../utils'\nimport { hasBasePath } from '../../../../client/has-base-path'\n\n/**\n * Detects whether a given url is routable by the Next.js router (browser only).\n */\nexport function isLocalURL(url: string): boolean {\n // prevent a hydration mismatch on href for url with anchor refs\n if (!isAbsoluteUrl(url)) return true\n try {\n // absolute urls can be local if they are on the same origin\n const locationOrigin = getLocationOrigin()\n const resolved = new URL(url, locationOrigin)\n return resolved.origin === locationOrigin && hasBasePath(resolved.pathname)\n } catch (_) {\n return false\n }\n}\n","let errorOnce = (_: string) => {}\nif (process.env.NODE_ENV !== 'production') {\n const errors = new Set<string>()\n errorOnce = (msg: string) => {\n if (!errors.has(msg)) {\n console.error(msg)\n }\n errors.add(msg)\n }\n}\n\nexport { errorOnce }\n","'use client'\n\nimport React, { createContext, useContext, useOptimistic, useRef } from 'react'\nimport type { UrlObject } from 'url'\nimport { formatUrl } from '../../shared/lib/router/utils/format-url'\nimport { AppRouterContext } from '../../shared/lib/app-router-context.shared-runtime'\nimport { useMergedRef } from '../use-merged-ref'\nimport { isAbsoluteUrl } from '../../shared/lib/utils'\nimport { addBasePath } from '../add-base-path'\nimport { warnOnce } from '../../shared/lib/utils/warn-once'\nimport type { PENDING_LINK_STATUS } from '../components/links'\nimport {\n IDLE_LINK_STATUS,\n mountLinkInstance,\n onNavigationIntent,\n unmountLinkForCurrentNavigation,\n unmountPrefetchableInstance,\n type LinkInstance,\n} from '../components/links'\nimport { isLocalURL } from '../../shared/lib/router/utils/is-local-url'\nimport {\n FetchStrategy,\n type PrefetchTaskFetchStrategy,\n} from '../components/segment-cache/types'\nimport { errorOnce } from '../../shared/lib/utils/error-once'\n\ntype Url = string | UrlObject\ntype RequiredKeys<T> = {\n [K in keyof T]-?: {} extends Pick<T, K> ? never : K\n}[keyof T]\ntype OptionalKeys<T> = {\n [K in keyof T]-?: {} extends Pick<T, K> ? K : never\n}[keyof T]\n\ntype OnNavigateEventHandler = (event: { preventDefault: () => void }) => void\n\ntype InternalLinkProps = {\n /**\n * **Required**. The path or URL to navigate to. It can also be an object (similar to `URL`).\n *\n * @example\n * ```tsx\n * // Navigate to /dashboard:\n * <Link href=\"/dashboard\">Dashboard</Link>\n *\n * // Navigate to /about?name=test:\n * <Link href={{ pathname: '/about', query: { name: 'test' } }}>\n * About\n * </Link>\n * ```\n *\n * @remarks\n * - For external URLs, use a fully qualified URL such as `https://...`.\n * - In the App Router, dynamic routes must not include bracketed segments in `href`.\n */\n href: Url\n\n /**\n * @deprecated v10.0.0: `href` props pointing to a dynamic route are\n * automatically resolved and no longer require the `as` prop.\n */\n as?: Url\n\n /**\n * Replace the current `history` state instead of adding a new URL into the stack.\n *\n * @defaultValue `false`\n *\n * @example\n * ```tsx\n * <Link href=\"/about\" replace>\n * About (replaces the history state)\n * </Link>\n * ```\n */\n replace?: boolean\n\n /**\n * Whether to override the default scroll behavior. If `true`, Next.js attempts to maintain\n * the scroll position if the newly navigated page is still visible. If not, it scrolls to the top.\n *\n * If `false`, Next.js will not modify the scroll behavior at all.\n *\n * @defaultValue `true`\n *\n * @example\n * ```tsx\n * <Link href=\"/dashboard\" scroll={false}>\n * No auto scroll\n * </Link>\n * ```\n */\n scroll?: boolean\n\n /**\n * Update the path of the current page without rerunning data fetching methods\n * like `getStaticProps`, `getServerSideProps`, or `getInitialProps`.\n *\n * @remarks\n * `shallow` only applies to the Pages Router. For the App Router, see the\n * [following documentation](https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating#using-the-native-history-api).\n *\n * @defaultValue `false`\n *\n * @example\n * ```tsx\n * <Link href=\"/blog\" shallow>\n * Shallow navigation\n * </Link>\n * ```\n */\n shallow?: boolean\n\n /**\n * Forces `Link` to pass its `href` to the child component. Useful if the child is a custom\n * component that wraps an `<a>` tag, or if you're using certain styling libraries.\n *\n * @defaultValue `false`\n *\n * @example\n * ```tsx\n * <Link href=\"/dashboard\" passHref legacyBehavior>\n * <MyStyledAnchor>Dashboard</MyStyledAnchor>\n * </Link>\n * ```\n */\n passHref?: boolean\n\n /**\n * Prefetch the page in the background.\n * Any `<Link />` that is in the viewport (initially or through scroll) will be prefetched.\n * Prefetch can be disabled by passing `prefetch={false}`.\n *\n * @remarks\n * Prefetching is only enabled in production.\n *\n * - In the **App Router**:\n * - `\"auto\"`, `null`, `undefined` (default): Prefetch behavior depends on static vs dynamic routes:\n * - Static routes: fully prefetched\n * - Dynamic routes: partial prefetch to the nearest segment with a `loading.js`\n * - `true`: Always prefetch the full route and data.\n * - `false`: Disable prefetching on both viewport and hover.\n * - In the **Pages Router**:\n * - `true` (default): Prefetches the route and data in the background on viewport or hover.\n * - `false`: Prefetch only on hover, not on viewport.\n *\n * @defaultValue `true` (Pages Router) or `null` (App Router)\n *\n * @example\n * ```tsx\n * <Link href=\"/dashboard\" prefetch={false}>\n * Dashboard\n * </Link>\n * ```\n */\n prefetch?: boolean | 'auto' | null\n\n /**\n * (unstable) Switch to a full prefetch on hover. Effectively the same as\n * updating the prefetch prop to `true` in a mouse event.\n */\n unstable_dynamicOnHover?: boolean\n\n /**\n * The active locale is automatically prepended in the Pages Router. `locale` allows for providing\n * a different locale, or can be set to `false` to opt out of automatic locale behavior.\n *\n * @remarks\n * Note: locale only applies in the Pages Router and is ignored in the App Router.\n *\n * @example\n * ```tsx\n * // Use the 'fr' locale:\n * <Link href=\"/about\" locale=\"fr\">\n * About (French)\n * </Link>\n *\n * // Disable locale prefix:\n * <Link href=\"/about\" locale={false}>\n * About (no locale prefix)\n * </Link>\n * ```\n */\n locale?: string | false\n\n /**\n * Enable legacy link behavior.\n *\n * @deprecated This will be removed in a future version\n * @defaultValue `false`\n * @see https://github.com/vercel/next.js/commit/489e65ed98544e69b0afd7e0cfc3f9f6c2b803b7\n */\n legacyBehavior?: boolean\n\n /**\n * Optional event handler for when the mouse pointer is moved onto the `<Link>`.\n */\n onMouseEnter?: React.MouseEventHandler<HTMLAnchorElement>\n\n /**\n * Optional event handler for when the `<Link>` is touched.\n */\n onTouchStart?: React.TouchEventHandler<HTMLAnchorElement>\n\n /**\n * Optional event handler for when the `<Link>` is clicked.\n */\n onClick?: React.MouseEventHandler<HTMLAnchorElement>\n\n /**\n * Optional event handler for when the `<Link>` is navigated.\n */\n onNavigate?: OnNavigateEventHandler\n}\n\n// TODO-APP: Include the full set of Anchor props\n// adding this to the publicly exported type currently breaks existing apps\n\n// `RouteInferType` is a stub here to avoid breaking `typedRoutes` when the type\n// isn't generated yet. It will be replaced when type generation runs.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport type LinkProps<RouteInferType = any> = InternalLinkProps\ntype LinkPropsRequired = RequiredKeys<LinkProps>\ntype LinkPropsOptional = OptionalKeys<Omit<InternalLinkProps, 'locale'>>\n\nfunction isModifiedEvent(event: React.MouseEvent): boolean {\n const eventTarget = event.currentTarget as HTMLAnchorElement | SVGAElement\n const target = eventTarget.getAttribute('target')\n return (\n (target && target !== '_self') ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey || // triggers resource download\n (event.nativeEvent && event.nativeEvent.which === 2)\n )\n}\n\nfunction linkClicked(\n e: React.MouseEvent,\n href: string,\n as: string,\n linkInstanceRef: React.RefObject<LinkInstance | null>,\n replace?: boolean,\n scroll?: boolean,\n onNavigate?: OnNavigateEventHandler\n): void {\n if (typeof window !== 'undefined') {\n const { nodeName } = e.currentTarget\n\n // anchors inside an svg have a lowercase nodeName\n const isAnchorNodeName = nodeName.toUpperCase() === 'A'\n if (\n (isAnchorNodeName && isModifiedEvent(e)) ||\n e.currentTarget.hasAttribute('download')\n ) {\n // ignore click for browser’s default behavior\n return\n }\n\n if (!isLocalURL(href)) {\n if (replace) {\n // browser default behavior does not replace the history state\n // so we need to do it manually\n e.preventDefault()\n location.replace(href)\n }\n\n // ignore click for browser’s default behavior\n return\n }\n\n e.preventDefault()\n\n if (onNavigate) {\n let isDefaultPrevented = false\n\n onNavigate({\n preventDefault: () => {\n isDefaultPrevented = true\n },\n })\n\n if (isDefaultPrevented) {\n return\n }\n }\n\n const { dispatchNavigateAction } =\n require('../components/app-router-instance') as typeof import('../components/app-router-instance')\n\n React.startTransition(() => {\n dispatchNavigateAction(\n as || href,\n replace ? 'replace' : 'push',\n scroll ?? true,\n linkInstanceRef.current\n )\n })\n }\n}\n\nfunction formatStringOrUrl(urlObjOrString: UrlObject | string): string {\n if (typeof urlObjOrString === 'string') {\n return urlObjOrString\n }\n\n return formatUrl(urlObjOrString)\n}\n\n/**\n * A React component that extends the HTML `<a>` element to provide\n * [prefetching](https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching)\n * and client-side navigation. This is the primary way to navigate between routes in Next.js.\n *\n * @remarks\n * - Prefetching is only enabled in production.\n *\n * @see https://nextjs.org/docs/app/api-reference/components/link\n */\nexport default function LinkComponent(\n props: LinkProps & {\n children: React.ReactNode\n ref: React.Ref<HTMLAnchorElement>\n }\n) {\n const [linkStatus, setOptimisticLinkStatus] = useOptimistic(IDLE_LINK_STATUS)\n\n let children: React.ReactNode\n\n const linkInstanceRef = useRef<LinkInstance | null>(null)\n\n const {\n href: hrefProp,\n as: asProp,\n children: childrenProp,\n prefetch: prefetchProp = null,\n passHref,\n replace,\n shallow,\n scroll,\n onClick,\n onMouseEnter: onMouseEnterProp,\n onTouchStart: onTouchStartProp,\n legacyBehavior = false,\n onNavigate,\n ref: forwardedRef,\n unstable_dynamicOnHover,\n ...restProps\n } = props\n\n children = childrenProp\n\n if (\n legacyBehavior &&\n (typeof children === 'string' || typeof children === 'number')\n ) {\n children = <a>{children}</a>\n }\n\n const router = React.useContext(AppRouterContext)\n\n const prefetchEnabled = prefetchProp !== false\n\n const fetchStrategy =\n prefetchProp !== false\n ? getFetchStrategyFromPrefetchProp(prefetchProp)\n : // TODO: it makes no sense to assign a fetchStrategy when prefetching is disabled.\n FetchStrategy.PPR\n\n if (process.env.NODE_ENV !== 'production') {\n function createPropError(args: {\n key: string\n expected: string\n actual: string\n }) {\n return new Error(\n `Failed prop type: The prop \\`${args.key}\\` expects a ${args.expected} in \\`<Link>\\`, but got \\`${args.actual}\\` instead.` +\n (typeof window !== 'undefined'\n ? \"\\nOpen your browser's console to view the Component stack trace.\"\n : '')\n )\n }\n\n // TypeScript trick for type-guarding:\n const requiredPropsGuard: Record<LinkPropsRequired, true> = {\n href: true,\n } as const\n const requiredProps: LinkPropsRequired[] = Object.keys(\n requiredPropsGuard\n ) as LinkPropsRequired[]\n requiredProps.forEach((key: LinkPropsRequired) => {\n if (key === 'href') {\n if (\n props[key] == null ||\n (typeof props[key] !== 'string' && typeof props[key] !== 'object')\n ) {\n throw createPropError({\n key,\n expected: '`string` or `object`',\n actual: props[key] === null ? 'null' : typeof props[key],\n })\n }\n } else {\n // TypeScript trick for type-guarding:\n const _: never = key\n }\n })\n\n // TypeScript trick for type-guarding:\n const optionalPropsGuard: Record<LinkPropsOptional, true> = {\n as: true,\n replace: true,\n scroll: true,\n shallow: true,\n passHref: true,\n prefetch: true,\n unstable_dynamicOnHover: true,\n onClick: true,\n onMouseEnter: true,\n onTouchStart: true,\n legacyBehavior: true,\n onNavigate: true,\n } as const\n const optionalProps: LinkPropsOptional[] = Object.keys(\n optionalPropsGuard\n ) as LinkPropsOptional[]\n optionalProps.forEach((key: LinkPropsOptional) => {\n const valType = typeof props[key]\n\n if (key === 'as') {\n if (props[key] && valType !== 'string' && valType !== 'object') {\n throw createPropError({\n key,\n expected: '`string` or `object`',\n actual: valType,\n })\n }\n } else if (\n key === 'onClick' ||\n key === 'onMouseEnter' ||\n key === 'onTouchStart' ||\n key === 'onNavigate'\n ) {\n if (props[key] && valType !== 'function') {\n throw createPropError({\n key,\n expected: '`function`',\n actual: valType,\n })\n }\n } else if (\n key === 'replace' ||\n key === 'scroll' ||\n key === 'shallow' ||\n key === 'passHref' ||\n key === 'legacyBehavior' ||\n key === 'unstable_dynamicOnHover'\n ) {\n if (props[key] != null && valType !== 'boolean') {\n throw createPropError({\n key,\n expected: '`boolean`',\n actual: valType,\n })\n }\n } else if (key === 'prefetch') {\n if (\n props[key] != null &&\n valType !== 'boolean' &&\n props[key] !== 'auto'\n ) {\n throw createPropError({\n key,\n expected: '`boolean | \"auto\"`',\n actual: valType,\n })\n }\n } else {\n // TypeScript trick for type-guarding:\n const _: never = key\n }\n })\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (props.locale) {\n warnOnce(\n 'The `locale` prop is not supported in `next/link` while using the `app` router. Read more about app router internalization: https://nextjs.org/docs/app/building-your-application/routing/internationalization'\n )\n }\n if (!asProp) {\n let href: string | undefined\n if (typeof hrefProp === 'string') {\n href = hrefProp\n } else if (\n typeof hrefProp === 'object' &&\n typeof hrefProp.pathname === 'string'\n ) {\n href = hrefProp.pathname\n }\n\n if (href) {\n const hasDynamicSegment = href\n .split('/')\n .some((segment) => segment.startsWith('[') && segment.endsWith(']'))\n\n if (hasDynamicSegment) {\n throw new Error(\n `Dynamic href \\`${href}\\` found in <Link> while using the \\`/app\\` router, this is not supported. Read more: https://nextjs.org/docs/messages/app-dir-dynamic-href`\n )\n }\n }\n }\n }\n\n const { href, as } = React.useMemo(() => {\n const resolvedHref = formatStringOrUrl(hrefProp)\n return {\n href: resolvedHref,\n as: asProp ? formatStringOrUrl(asProp) : resolvedHref,\n }\n }, [hrefProp, asProp])\n\n // This will return the first child, if multiple are provided it will throw an error\n let child: any\n if (legacyBehavior) {\n if ((children as any)?.$$typeof === Symbol.for('react.lazy')) {\n throw new Error(\n `\\`<Link legacyBehavior>\\` received a direct child that is either a Server Component, or JSX that was loaded with React.lazy(). This is not supported. Either remove legacyBehavior, or make the direct child a Client Component that renders the Link's \\`<a>\\` tag.`\n )\n }\n\n if (process.env.NODE_ENV === 'development') {\n if (onClick) {\n console.warn(\n `\"onClick\" was passed to <Link> with \\`href\\` of \\`${hrefProp}\\` but \"legacyBehavior\" was set. The legacy behavior requires onClick be set on the child of next/link`\n )\n }\n if (onMouseEnterProp) {\n console.warn(\n `\"onMouseEnter\" was passed to <Link> with \\`href\\` of \\`${hrefProp}\\` but \"legacyBehavior\" was set. The legacy behavior requires onMouseEnter be set on the child of next/link`\n )\n }\n try {\n child = React.Children.only(children)\n } catch (err) {\n if (!children) {\n throw new Error(\n `No children were passed to <Link> with \\`href\\` of \\`${hrefProp}\\` but one child is required https://nextjs.org/docs/messages/link-no-children`\n )\n }\n throw new Error(\n `Multiple children were passed to <Link> with \\`href\\` of \\`${hrefProp}\\` but only one child is supported https://nextjs.org/docs/messages/link-multiple-children` +\n (typeof window !== 'undefined'\n ? \" \\nOpen your browser's console to view the Component stack trace.\"\n : '')\n )\n }\n } else {\n child = React.Children.only(children)\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n if ((children as any)?.type === 'a') {\n throw new Error(\n 'Invalid <Link> with <a> child. Please remove <a> or use <Link legacyBehavior>.\\nLearn more: https://nextjs.org/docs/messages/invalid-new-link-with-extra-anchor'\n )\n }\n }\n }\n\n const childRef: any = legacyBehavior\n ? child && typeof child === 'object' && child.ref\n : forwardedRef\n\n // Use a callback ref to attach an IntersectionObserver to the anchor tag on\n // mount. In the future we will also use this to keep track of all the\n // currently mounted <Link> instances, e.g. so we can re-prefetch them after\n // a revalidation or refresh.\n const observeLinkVisibilityOnMount = React.useCallback(\n (element: HTMLAnchorElement | SVGAElement) => {\n if (router !== null) {\n linkInstanceRef.current = mountLinkInstance(\n element,\n href,\n router,\n fetchStrategy,\n prefetchEnabled,\n setOptimisticLinkStatus\n )\n }\n\n return () => {\n if (linkInstanceRef.current) {\n unmountLinkForCurrentNavigation(linkInstanceRef.current)\n linkInstanceRef.current = null\n }\n unmountPrefetchableInstance(element)\n }\n },\n [prefetchEnabled, href, router, fetchStrategy, setOptimisticLinkStatus]\n )\n\n const mergedRef = useMergedRef(observeLinkVisibilityOnMount, childRef)\n\n const childProps: {\n onTouchStart?: React.TouchEventHandler<HTMLAnchorElement>\n onMouseEnter: React.MouseEventHandler<HTMLAnchorElement>\n onClick: React.MouseEventHandler<HTMLAnchorElement>\n href?: string\n ref?: any\n } = {\n ref: mergedRef,\n onClick(e) {\n if (process.env.NODE_ENV !== 'production') {\n if (!e) {\n throw new Error(\n `Component rendered inside next/link has to pass click event to \"onClick\" prop.`\n )\n }\n }\n\n if (!legacyBehavior && typeof onClick === 'function') {\n onClick(e)\n }\n\n if (\n legacyBehavior &&\n child.props &&\n typeof child.props.onClick === 'function'\n ) {\n child.props.onClick(e)\n }\n\n if (!router) {\n return\n }\n if (e.defaultPrevented) {\n return\n }\n linkClicked(e, href, as, linkInstanceRef, replace, scroll, onNavigate)\n },\n onMouseEnter(e) {\n if (!legacyBehavior && typeof onMouseEnterProp === 'function') {\n onMouseEnterProp(e)\n }\n\n if (\n legacyBehavior &&\n child.props &&\n typeof child.props.onMouseEnter === 'function'\n ) {\n child.props.onMouseEnter(e)\n }\n\n if (!router) {\n return\n }\n if (!prefetchEnabled || process.env.NODE_ENV === 'development') {\n return\n }\n\n const upgradeToDynamicPrefetch = unstable_dynamicOnHover === true\n onNavigationIntent(\n e.currentTarget as HTMLAnchorElement | SVGAElement,\n upgradeToDynamicPrefetch\n )\n },\n onTouchStart: process.env.__NEXT_LINK_NO_TOUCH_START\n ? undefined\n : function onTouchStart(e) {\n if (!legacyBehavior && typeof onTouchStartProp === 'function') {\n onTouchStartProp(e)\n }\n\n if (\n legacyBehavior &&\n child.props &&\n typeof child.props.onTouchStart === 'function'\n ) {\n child.props.onTouchStart(e)\n }\n\n if (!router) {\n return\n }\n if (!prefetchEnabled) {\n return\n }\n\n const upgradeToDynamicPrefetch = unstable_dynamicOnHover === true\n onNavigationIntent(\n e.currentTarget as HTMLAnchorElement | SVGAElement,\n upgradeToDynamicPrefetch\n )\n },\n }\n\n // If the url is absolute, we can bypass the logic to prepend the basePath.\n if (isAbsoluteUrl(as)) {\n childProps.href = as\n } else if (\n !legacyBehavior ||\n passHref ||\n (child.type === 'a' && !('href' in child.props))\n ) {\n childProps.href = addBasePath(as)\n }\n\n let link: React.ReactNode\n\n if (legacyBehavior) {\n if (process.env.NODE_ENV === 'development') {\n errorOnce(\n '`legacyBehavior` is deprecated and will be removed in a future ' +\n 'release. A codemod is available to upgrade your components:\\n\\n' +\n 'npx @next/codemod@latest new-link .\\n\\n' +\n 'Learn more: https://nextjs.org/docs/app/building-your-application/upgrading/codemods#remove-a-tags-from-link-components'\n )\n }\n link = React.cloneElement(child, childProps)\n } else {\n link = (\n <a {...restProps} {...childProps}>\n {children}\n </a>\n )\n }\n\n return (\n <LinkStatusContext.Provider value={linkStatus}>\n {link}\n </LinkStatusContext.Provider>\n )\n}\n\nconst LinkStatusContext = createContext<\n typeof PENDING_LINK_STATUS | typeof IDLE_LINK_STATUS\n>(IDLE_LINK_STATUS)\n\nexport const useLinkStatus = () => {\n return useContext(LinkStatusContext)\n}\n\nfunction getFetchStrategyFromPrefetchProp(\n prefetchProp: Exclude<LinkProps['prefetch'], undefined | false>\n): PrefetchTaskFetchStrategy {\n if (process.env.__NEXT_CACHE_COMPONENTS) {\n if (prefetchProp === true) {\n return FetchStrategy.Full\n }\n\n // `null` or `\"auto\"`: this is the default \"auto\" mode, where we will prefetch partially if the link is in the viewport.\n // This will also include invalid prop values that don't match the types specified here.\n // (although those should've been filtered out by prop validation in dev)\n prefetchProp satisfies null | 'auto'\n return FetchStrategy.PPR\n } else {\n return prefetchProp === null || prefetchProp === 'auto'\n ? // We default to PPR, and we'll discover whether or not the route supports it with the initial prefetch.\n FetchStrategy.PPR\n : // In the old implementation without runtime prefetches, `prefetch={true}` forces all dynamic data to be prefetched.\n // To preserve backwards-compatibility, anything other than `false`, `null`, or `\"auto\"` results in a full prefetch.\n // (although invalid values should've been filtered out by prop validation in dev)\n FetchStrategy.Full\n }\n}\n"],"names":["assign","searchParamsToUrlQuery","urlQueryToSearchParams","searchParams","query","key","value","entries","existing","Array","isArray","push","stringifyUrlQueryParam","param","isNaN","String","URLSearchParams","Object","item","append","set","target","searchParamsList","keys","delete","formatUrl","formatWithValidation","urlObjectKeys","slashedProtocols","urlObj","auth","hostname","protocol","pathname","hash","host","encodeURIComponent","replace","indexOf","port","querystring","search","endsWith","slashes","test","url","process","env","NODE_ENV","forEach","includes","console","warn","useMergedRef","refA","refB","cleanupA","useRef","cleanupB","useCallback","current","cleanupFnA","cleanupFnB","applyRef","cleanup","DecodeError","MiddlewareNotFoundError","MissingStaticPage","NormalizeError","PageNotFoundError","SP","ST","WEB_VITALS","execOnce","getDisplayName","getLocationOrigin","getURL","isAbsoluteUrl","isResSent","loadGetInitialProps","normalizeRepeatedSlashes","stringifyError","fn","used","result","args","ABSOLUTE_URL_REGEX","window","location","href","origin","substring","length","Component","displayName","name","res","finished","headersSent","urlParts","split","urlNoQuery","slice","join","App","ctx","prototype","getInitialProps","message","Error","pageProps","props","performance","every","method","constructor","page","code","error","JSON","stringify","stack","parsePath","path","hashIndex","queryIndex","hasQuery","undefined","addPathPrefix","prefix","startsWith","removeTrailingSlash","route","normalizePathTrailingSlash","__NEXT_MANUAL_TRAILING_SLASH","__NEXT_TRAILING_SLASH","addBasePath","basePath","__NEXT_ROUTER_BASEPATH","required","__NEXT_MANUAL_CLIENT_BASE_PATH","warnOnce","_","warnings","Set","msg","has","add","FetchStrategy","NavigationResultTag","PrefetchPriority","createCacheKey","originalHref","nextUrl","originalUrl","URL","cacheKey","HasLoadingBoundary","matchSegment","existingSegment","segment","ACTION_HEADER","FLIGHT_HEADERS","NEXT_ACTION_NOT_FOUND_HEADER","NEXT_ACTION_REVALIDATED_HEADER","NEXT_DID_POSTPONE_HEADER","NEXT_HMR_REFRESH_HASH_COOKIE","NEXT_HMR_REFRESH_HEADER","NEXT_HTML_REQUEST_ID_HEADER","NEXT_IS_PRERENDER_HEADER","NEXT_REQUEST_ID_HEADER","NEXT_REWRITTEN_PATH_HEADER","NEXT_REWRITTEN_QUERY_HEADER","NEXT_ROUTER_PREFETCH_HEADER","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","NEXT_ROUTER_STALE_TIME_HEADER","NEXT_ROUTER_STATE_TREE_HEADER","NEXT_RSC_UNION_QUERY","NEXT_URL","RSC_CONTENT_TYPE_HEADER","RSC_HEADER","ACTION_HMR_REFRESH","ACTION_NAVIGATE","ACTION_REFRESH","ACTION_RESTORE","ACTION_SERVER_ACTION","ACTION_SERVER_PATCH","PrefetchKind","isThenable","promise","then","dispatchAppRouterAction","useActionQueue","dispatch","action","__DEV__","promisesWithDebugInfo","WeakMap","actionQueue","state","setState","React","useState","useAppDevRenderingIndicator","require","appDevRenderingIndicator","stateWithDebugInfo","useMemo","promiseWithDebugInfo","get","debugInfo","Promise","resolve","asyncState","_debugInfo","use","callServer","actionId","actionArgs","reject","startTransition","type","findSourceMapURL","filename","document","DEFAULT_SEGMENT_KEY","NOT_FOUND_SEGMENT_KEY","PAGE_SEGMENT_KEY","addSearchParamsIfPageSegment","computeSelectedLayoutSegment","getSegmentValue","getSelectedLayoutSegmentPath","isGroupSegment","isParallelRouteSegment","isPageSegment","stringifiedQuery","segments","parallelRouteKey","rawSegment","tree","first","segmentPath","node","parallelRoutes","children","values","segmentValue","HEAD_REQUEST_KEY","ROOT_SEGMENT_REQUEST_KEY","appendSegmentRequestKeyPart","convertSegmentPathToStaticExportFilename","createSegmentRequestKeyPart","safeName","encodeToFilesystemAndURLSafeString","paramType","encodedName","parentRequestKey","childRequestKeyPart","slotKey","simpleParamValueRegex","base64url","btoa","doesStaticSegmentAppearInURL","getCacheKeyForDynamicParam","getParamValueFromCacheKey","getRenderedPathname","getRenderedSearch","parseDynamicParamFromURLPart","urlSearchParamsToParsedUrlQuery","urlToUrlWithoutFlightMarker","response","rewrittenQuery","headers","rewrittenPath","pathnameParts","partIndex","map","s","i","paramValue","renderedSearch","pageSegmentWithSearchParams","fromEntries","urlWithoutFlightParameters","__NEXT_CONFIG_OUTPUT","paramCacheKey","isCatchAll","createHrefFromUrl","includeHash","createInitialRSCPayloadFromFallbackPrerender","getFlightDataPartsFromPath","getNextFlightSegmentPath","normalizeFlightData","prepareFlightRouterStateForRequest","flightDataPath","flightDataPathLength","seedData","head","isHeadPartial","pathToSegment","isRootRender","fallbackInitialRSCPayload","renderedPathname","canonicalUrl","originalFlightDataPath","f","originalFlightRouterState","b","c","q","fillInFallbackFlightRouterState","m","G","S","flightRouterState","filter","p","index","fillInFallbackFlightRouterStateImpl","pathnamePartsIndex","originalSegment","newSegment","doesAppearInURL","paramName","childPathnamePartsIndex","newChildren","childFlightRouterState","newState","flightSegmentPath","flightData","isHmrRefresh","stripClientOnlyDataFromFlightRouterState","_url","refreshMarker","isRootLayout","hasLoadingBoundary","cleanedSegment","stripSearchParamsFromPageSegment","cleanedParallelRoutes","childState","shouldPreserveRefreshMarker","Boolean","getAppBuildId","setAppBuildId","globalBuildId","buildId","djb2Hash","hexHash","str","char","charCodeAt","toString","computeCacheBustingSearchParam","prefetchHeader","segmentPrefetchHeader","stateTreeHeader","nextUrlHeader","setCacheBustingSearchParam","setCacheBustingSearchParamWithHash","uniqueCacheKey","existingSearch","rawQuery","pairs","pair","getDeploymentId","getDeploymentIdQueryOrEmptyString","NEXT_DEPLOYMENT_ID","deploymentId","createFetch","createFromNextReadableStream","fetchServerResponse","createFromReadableStream","createFromReadableStreamBrowser","createFromFetch","createFromFetchBrowser","createDebugChannel","__NEXT_REACT_DEBUG_CHANNEL","doMpaNavigation","isPageUnloading","addEventListener","options","isLegacyPPR","__NEXT_PPR","__NEXT_CACHE_COMPONENTS","shouldImmediatelyDecode","responseUrl","redirected","contentType","interception","postponed","staleTimeHeaderSeconds","staleTime","parseInt","isFlightResponse","ok","body","TURBOPACK","waitForWebpackRuntimeHotUpdate","flightResponsePromise","flightResponse","flightStream","createUnclosingPrefetchStream","normalizedFlightData","couldBeIntercepted","prerendered","err","fetchPriority","signal","__NEXT_TEST_MODE","self","__next_r","crypto","getRandomValues","Uint32Array","fetchOptions","credentials","priority","fetchUrl","fetchPromise","fetch","createFromNextFetch","browserResponse","__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS","MAX_REDIRECTS","n","rscResponse","status","requestHeaders","debugChannel","promiseForResponse","originalFlightStream","reader","getReader","ReadableStream","pull","controller","done","read","enqueue","deleteFromLru","lruPut","updateLruSize","didScheduleCleanup","lruSize","maxLruSize","prev","next","size","ensureCleanupIsScheduled","tail","newNodeSize","prevNodeSize","deleted","requestCleanupCallback","ninetyPercentMax","deleteMapEntry","requestIdleCallback","cb","setTimeout","Fallback","createCacheMap","deleteFromCacheMap","getFromCacheMap","isValueExpired","setInCacheMap","setSizeInCacheMap","Revalidation","cacheMap","parent","getOrInitialize","isRevalidation","entry","remainingKeys","previousKey","existingEntry","Map","newEntry","now","currentCacheVersion","rootEntry","getEntryWithFallbackImpl","staleAt","version","lazilyEvictIfNeeded","fallbackEntry","setMapEntryValue","dropRef","oldEntry","ref","parentMap","revalidatingEntry","appendLayoutVaryPath","clonePageVaryPathWithNewSearchParams","finalizeLayoutVaryPath","finalizeMetadataVaryPath","finalizePageVaryPath","getFulfilledRouteVaryPath","getRouteVaryPath","getSegmentVaryPathForRequest","varyPath","parentPath","varyPathPart","requestKey","layoutVaryPath","pageVaryPath","pageRequestKey","fetchStrategy","originalVaryPath","isPage","doesVaryOnSearchParams","Full","PPRRuntime","searchParamsVaryPath","pathParamsVaryPath","patchedVaryPath","newSearch","clonedVaryPath","ensureLeadingSlash","normalizeAppPath","normalizeRscURL","reduce","INTERCEPTION_ROUTE_MARKERS","extractInterceptionRouteInformation","isInterceptionRouteAppPath","find","interceptingRoute","marker","interceptedRoute","concat","splitInterceptingRoute","computeChangedPath","extractPathFromFlightRouterState","getSelectedParams","removeLeadingSlash","segmentToPathname","normalizeSegments","acc","some","childrenPath","childPath","computeChangedPathImpl","treeA","treeB","segmentA","parallelRoutesA","segmentB","parallelRoutesB","normalizedSegmentA","normalizedSegmentB","parallelRouterKey","changedPath","currentTree","params","parallelRoute","isDynamicParameter","handleMutable","isNotUndefined","mutable","shouldScroll","previousNextUrl","patchedTree","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","apply","scrollableSegments","onlyHashChange","hashFragment","decodeURIComponent","segmentPaths","cache","collectedDebugInfo","createRouterCacheKey","withoutSearchParameters","isNavigatingToNewRootLayout","nextTree","currentTreeSegment","nextTreeSegment","currentTreeChild","nextTreeChild","FreshnessPolicy","createInitialCacheNodeForHydration","isDeferredRsc","spawnDynamicRequests","startPPRNavigation","noop","navigatedAt","initialTree","seedHead","accumulation","separateRefreshUrls","task","createCacheNodeOnNavigation","oldUrl","oldCacheNode","oldRouterState","newRouterState","freshness","prefetchData","prefetchHead","isPrefetchHeadPartial","isSamePageNavigation","didFindRootLayout","parentNeedsDynamicRequest","parentRefreshUrl","updateCacheNodeOnNavigation","parentSegmentPath","parentParallelRouteKey","oldSegment","newRouterStateChildren","oldRouterStateChildren","seedDataChildren","prefetchDataChildren","childDidFindRootLayout","oldParallelRoutes","shouldDropSiblingCaches","shouldRefreshDynamicData","newParallelRoutes","isLeafSegment","newCacheNode","needsDynamicRequest","dropPrefetchRsc","reuseDynamicCacheNode","seedRsc","seedLoading","isSeedRscPartial","isSeedHeadPartial","readCacheNodeFromSeedData","prefetchRsc","prefetchLoading","isPrefetchRSCPartial","spawnNewCacheNode","refreshUrl","accumulateRefreshUrl","patchedRouterStateChildren","taskChildren","childNeedsDynamicRequest","dynamicRequestTreeChildren","newRouterStateChild","oldRouterStateChild","oldSegmentMapChild","seedDataChild","prefetchDataChild","newSegmentChild","seedHeadChild","prefetchHeadChild","isPrefetchHeadPartialChild","reuseActiveSegmentInDefaultSlot","newSegmentKeyChild","oldCacheNodeChild","taskChild","newCacheNodeChild","newSegmentMapChild","taskChildRoute","dynamicRequestTreeChild","dynamicRequestTree","patchRouterStateWithNewChildren","createDynamicRequestTree","DYNAMIC_STALETIME_MS","oldRsc","rsc","oldRscDidResolve","baseRouterState","clone","reusedRouterState","oldRefreshMarker","existingCacheNode","cacheNode","loading","createDeferredRsc","isHydration","previousNavigationDidMismatch","primaryUrl","freshnessPolicy","primaryRequestPromise","fetchMissingDynamicData","refreshRequestPromises","scopedDynamicRequestTree","voidPromise","finishNavigationTask","exitStatus","waitForRequestsToFinish","abortRemainingPendingTasks","isHardRetry","primaryRequestResult","dispatchRetryDueToTreeMismatch","seed","onFulfill","remainingCount","onReject","refreshRequestPromise","retryUrl","retryNextUrl","baseTree","retryAction","previousTree","mpa","convertServerPatchToFullTree","didReceiveUnknownParallelRoute","writeDynamicDataIntoNavigationTask","data","serverRouterState","dynamicData","dynamicHead","finishPendingCacheNode","serverChildren","dynamicDataChildren","serverRouterStateChild","dynamicDataChild","taskSegment","childDidReceiveUnknownParallelRoute","dynamicSegmentData","dynamicLoading","abortPendingCacheNode","childExitStatus","DEFERRED","Symbol","tag","pendingRsc","rej","responseDebugInfo","fulfilledRsc","rejectedRsc","reason","navigate","navigateToSeededRoute","currentUrl","currentCacheNode","currentFlightRouterState","Date","readRouteCacheEntry","EntryStatus","Fulfilled","snapshot","readRenderSnapshotFromCache","prefetchFlightRouterState","prefetchSeedData","headSnapshot","readHeadSnapshotFromCache","isPartial","newCanonicalUrl","navigateUsingPrefetchedRouteTree","Rejected","optimisticRoute","requestOptimisticRouteCacheEntry","newRenderedSearch","Async","navigateDynamicallyWithNoPrefetch","navigationSeed","navigationTaskToResult","MPA","Success","childRouterStates","childSeedDatas","slots","childTree","childResult","segmentEntry","readSegmentCacheEntry","Pending","promiseForFulfilledEntry","waitForSegmentCacheEntry","Empty","hasRuntimePrefetch","metadata","DynamicRequestTreeForEntireRoute","Default","HistoryTraversal","Hydration","RefreshAll","HMRRefresh","promiseForDynamicServerResponse","newUrl","debugInfoFromResponse","baseData","treePatch","dataPatch","headPatch","convertServerPatchToFullTreeImpl","updatedParallelRouteKey","baseTreeChildren","baseSeedDataChildren","newTreeChildren","newSeedDataChildren","childBaseRouterState","childBaseSeedData","clonedTree","clonedSeedData","isEmptySeedDataPartial","STATIC_STALETIME_MS","generateSegmentsFromPatch","handleExternalUrl","handleNavigationResult","navigateReducer","Number","__NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME","getStaleTimeMs","__NEXT_CLIENT_ROUTER_STATIC_STALETIME","flightRouterPatch","childSegment","asyncResult","isExternalUrl","navigateType","getElementById","navigateUsingSegmentCache","createPromiseWithResolvers","canNewFetchStrategyProvideMoreContent","convertRouteTreeToFlightRouterState","createDetachedSegmentCacheEntry","fetchRouteOnCacheMiss","fetchSegmentOnCacheMiss","fetchSegmentPrefetchesUsingDynamicRequest","getCurrentCacheVersion","overwriteRevalidatingSegmentCacheEntry","pingInvalidationListeners","readOrCreateRevalidatingSegmentEntry","readOrCreateRouteCacheEntry","readOrCreateSegmentCacheEntry","revalidateEntireCache","upgradeToPendingSegment","upsertSegmentEntry","staleTimeSeconds","Math","max","isOutputExportMode","MetadataOnlyRequestTree","routeCacheMap","segmentCacheMap","invalidationListeners","startRevalidationCooldown","pingVisibleLinks","attachInvalidationListener","onInvalidate","notifyInvalidationListener","reportError","tasks","isPrefetchTaskDirty","readRevalidatingSegmentCacheEntry","pendingEntry","promiseWithResolvers","blockedTasks","isPPREnabled","Infinity","requestedUrl","requestedSearch","urlWithoutSearchParams","routeWithNoSearchParams","createPrefetchRequestKey","canonicalUrlForRouteWithNoSearchParams","optimisticCanonicalSearch","optimisticRenderedSearch","optimisticUrl","optimisticCanonicalUrl","optimisticRouteTree","createOptimisticRouteTree","optimisticMetadataTree","optimisticEntry","clonedSlots","originalSlots","varyPathForRequest","candidateEntry","rejectedEntry","emptyEntry","PPR","pingBlockedTasks","pingPrefetchTask","fulfillRouteCacheEntry","metadataVaryPath","SubtreeHasNoLoadingBoundary","fulfilledEntry","fulfillSegmentCacheEntry","segmentCacheEntry","rejectRouteCacheEntry","rejectSegmentCacheEntry","convertRootTreePrefetchToRouteTree","rootTree","rootSegment","convertTreePrefetchToRouteTree","prefetch","partialVaryPath","prefetchSlots","childPrefetch","childParamName","childParamType","childServerSentParamKey","paramKey","childDoesAppearInURL","childPartialVaryPath","childParamValue","childParamKey","childRequestKey","SegmentHasLoadingBoundary","convertRootFlightRouterStateToRouteTree","convertFlightRouterStateToRouteTree","parentPartialVaryPath","childRouterState","routeTree","urlAfterRedirects","headResponse","fetchPrefetchResponse","addSegmentPathToUrlInOutputExportMode","varyHeader","closed","routeIsPPREnabled","prefetchStream","createPrefetchResponseStream","onResponseSizeUpdate","serverData","staleTimeMs","writeDynamicTreeResponseIntoCache","LoadingBoundary","fulfilledVaryPath","routeKey","normalizedRequestKey","requestUrl","spawnedEntries","rejectSegmentEntriesIfStillPending","fulfilledEntries","totalBytesReceivedSoFar","averageSize","isResponsePartial","rp","writeDynamicRenderResponseIntoCache","normalizedFlightDataResult","flightDatas","writeSeedDataIntoCache","fulfillEntrySpawnedByRuntimePrefetch","entriesOwnedByCurrentTask","childSeedData","ownedEntry","possiblyNewEntry","onStreamClose","totalByteLength","byteLength","staticUrl","routeDir","staticExportFilename","currentStrategy","newStrategy","cancelPrefetchTask","reschedulePrefetchTask","schedulePrefetchTask","scheduleMicrotask","queueMicrotask","catch","taskHeap","inProgressRequests","sortIdCounter","didScheduleMicrotask","mostRecentlyHoveredLink","REVALIDATION_COOLDOWN_MS","revalidationCooldownTimeoutHandle","clearTimeout","ensureWorkIsScheduled","treeAtTimeOfPrefetch","cacheVersion","phase","hasBackgroundWork","spawnedRuntimePrefetches","sortId","isCanceled","_heapIndex","trackMostRecentlyHoveredLink","heapPush","heapDelete","Intent","heapResift","Background","processQueueInMicrotask","hasNetworkBandwidth","spawnPrefetchSubtask","prefetchSubtask","onPrefetchConnectionClosed","heapPeek","pingRoute","heapPop","background","pingRootRouteTree","keyWithoutSearch","routeWithoutSearch","pingStaticHead","pingSharedPartOfCacheComponentsTree","pingRuntimeHead","requestTree","pingRuntimePrefetches","diffRouteTreeAgainstCurrent","pingStaticSegmentData","pingRouteTreeAndIncludeDynamicData","oldTree","newTree","oldTreeChildren","newTreeChild","newTreeChildSegment","oldTreeChild","oldTreeChildSegment","doesCurrentSegmentMatchCachedSegment","pingNewPartOfCacheComponentsTree","requestTreeChildren","requestTreeChild","subtreeHasLoadingBoundary","pingPPRDisabledRouteTreeUpToLoadingBoundary","refetchMarkerContext","refetchMarker","segmentHasLoadingBoundary","isInsideRefetchingParent","spawnedSegment","pingFullSegmentRevalidation","pingPPRSegmentRevalidation","revalidatingSegment","upsertSegmentOnCompletion","pendingSegment","nonEmptyRevalidatingSegment","emptySegment","fulfilled","currentSegment","cachedSegment","compareQueuePriority","a","priorityDiff","phaseDiff","heap","heapSiftUp","last","pop","heapSiftDown","parentIndex","halfLength","leftIndex","left","rightIndex","right","IDLE_LINK_STATUS","PENDING_LINK_STATUS","mountFormInstance","mountLinkInstance","onLinkVisibilityChanged","onNavigationIntent","setLinkForCurrentNavigation","unmountLinkForCurrentNavigation","unmountPrefetchableInstance","linkForMostRecentNavigation","pending","link","setOptimisticLinkStatus","prefetchable","prefetchableAndVisible","observer","IntersectionObserver","handleIntersect","rootMargin","observeVisibility","element","instance","existingInstance","observe","coercePrefetchableUrl","createPrefetchURL","reportErrorFn","router","prefetchEnabled","prefetchURL","isVisible","prefetchTask","prefetchHref","unobserve","intersectionRatio","rescheduleLinkPrefetch","unstable_upgradeToDynamicPrefetch","__NEXT_DYNAMIC_ON_HOVER","existingPrefetchTask","getCurrentAppRouterState","appRouterState","scheduleSegmentPrefetchTask","pathHasPrefix","hasBasePath","isLocalURL","locationOrigin","resolved","errorOnce","errors","LinkComponent","useLinkStatus","isModifiedEvent","event","eventTarget","currentTarget","getAttribute","metaKey","ctrlKey","shiftKey","altKey","nativeEvent","which","linkClicked","e","as","linkInstanceRef","scroll","onNavigate","nodeName","isAnchorNodeName","toUpperCase","hasAttribute","preventDefault","isDefaultPrevented","dispatchNavigateAction","formatStringOrUrl","urlObjOrString","linkStatus","useOptimistic","hrefProp","asProp","childrenProp","prefetchProp","passHref","shallow","onClick","onMouseEnter","onMouseEnterProp","onTouchStart","onTouchStartProp","legacyBehavior","forwardedRef","unstable_dynamicOnHover","restProps","useContext","AppRouterContext","getFetchStrategyFromPrefetchProp","createPropError","expected","actual","requiredPropsGuard","requiredProps","optionalPropsGuard","optionalProps","valType","locale","hasDynamicSegment","resolvedHref","child","$$typeof","for","Children","only","childRef","observeLinkVisibilityOnMount","mergedRef","childProps","defaultPrevented","upgradeToDynamicPrefetch","__NEXT_LINK_NO_TOUCH_START","cloneElement","LinkStatusContext","Provider","createContext"],"mappings":"4CAEA,SAAS,EAAyB,CAAW,EACzC,GAAuB,YAAnB,OAAO,QAAwB,OAAO,KAE1C,IAAI,EAAoB,IAAI,QACxB,EAAmB,IAAI,QAE3B,MAAO,CAAC,EAA2B,SAAS,CAAW,EACnD,OAAO,EAAc,EAAmB,CAC5C,CAAC,EAAE,EACP,CA0BA,EAAQ,CAAC,CAzBT,EAyBY,OAzBH,AAA0B,CAAG,C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