dev3000 0.0.60 → 0.0.62
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/cdp-monitor.d.ts +2 -1
- package/dist/cdp-monitor.d.ts.map +1 -1
- package/dist/cdp-monitor.js +34 -17
- package/dist/cdp-monitor.js.map +1 -1
- package/dist/cli.js +105 -13
- package/dist/cli.js.map +1 -1
- package/dist/dev-environment.d.ts +3 -0
- package/dist/dev-environment.d.ts.map +1 -1
- package/dist/dev-environment.js +93 -34
- package/dist/dev-environment.js.map +1 -1
- package/dist/services/parsers/error-detectors/base.d.ts +24 -0
- package/dist/services/parsers/error-detectors/base.d.ts.map +1 -0
- package/dist/services/parsers/error-detectors/base.js +44 -0
- package/dist/services/parsers/error-detectors/base.js.map +1 -0
- package/dist/services/parsers/error-detectors/index.d.ts +6 -0
- package/dist/services/parsers/error-detectors/index.d.ts.map +1 -0
- package/dist/services/parsers/error-detectors/index.js +6 -0
- package/dist/services/parsers/error-detectors/index.js.map +1 -0
- package/dist/services/parsers/error-detectors/nextjs.d.ts +9 -0
- package/dist/services/parsers/error-detectors/nextjs.d.ts.map +1 -0
- package/dist/services/parsers/error-detectors/nextjs.js +52 -0
- package/dist/services/parsers/error-detectors/nextjs.js.map +1 -0
- package/dist/services/parsers/index.d.ts +8 -0
- package/dist/services/parsers/index.d.ts.map +1 -0
- package/dist/services/parsers/index.js +10 -0
- package/dist/services/parsers/index.js.map +1 -0
- package/dist/services/parsers/log-parsers/base.d.ts +26 -0
- package/dist/services/parsers/log-parsers/base.d.ts.map +1 -0
- package/dist/services/parsers/log-parsers/base.js +6 -0
- package/dist/services/parsers/log-parsers/base.js.map +1 -0
- package/dist/services/parsers/log-parsers/index.d.ts +6 -0
- package/dist/services/parsers/log-parsers/index.d.ts.map +1 -0
- package/dist/services/parsers/log-parsers/index.js +5 -0
- package/dist/services/parsers/log-parsers/index.js.map +1 -0
- package/dist/services/parsers/log-parsers/standard.d.ts +9 -0
- package/dist/services/parsers/log-parsers/standard.d.ts.map +1 -0
- package/dist/services/parsers/log-parsers/standard.js +17 -0
- package/dist/services/parsers/log-parsers/standard.js.map +1 -0
- package/dist/services/parsers/output-processor.d.ts +39 -0
- package/dist/services/parsers/output-processor.d.ts.map +1 -0
- package/dist/services/parsers/output-processor.js +54 -0
- package/dist/services/parsers/output-processor.js.map +1 -0
- package/mcp-server/.next/BUILD_ID +1 -1
- package/mcp-server/.next/app-build-manifest.json +56 -15
- package/mcp-server/.next/build/chunks/[root-of-the-server]__974941ed._.js +2 -10
- package/mcp-server/.next/build/chunks/[root-of-the-server]__974941ed._.js.map +4 -4
- package/mcp-server/.next/build/chunks/[root-of-the-server]__c7ae8543._.js +2 -10
- package/mcp-server/.next/build/chunks/[root-of-the-server]__c7ae8543._.js.map +4 -4
- package/mcp-server/.next/build/chunks/node_modules__pnpm_806d01c0._.js +10 -35
- package/mcp-server/.next/build/chunks/node_modules__pnpm_806d01c0._.js.map +9 -9
- package/mcp-server/.next/build-manifest.json +9 -12
- package/mcp-server/.next/cache/.previewinfo +1 -1
- package/mcp-server/.next/cache/.rscinfo +1 -1
- package/mcp-server/.next/cache/.tsbuildinfo +1 -1
- package/mcp-server/.next/fallback-build-manifest.json +2 -2
- package/mcp-server/.next/prerender-manifest.json +106 -4
- package/mcp-server/.next/routes-manifest.json +82 -1
- package/mcp-server/.next/server/app/_global-error.html +2 -2
- package/mcp-server/.next/server/app/_global-error.rsc +1 -1
- package/mcp-server/.next/server/app/_not-found/page/app-build-manifest.json +1 -1
- package/mcp-server/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/mcp-server/.next/server/app/_not-found.html +1 -1
- package/mcp-server/.next/server/app/_not-found.rsc +2 -2
- package/mcp-server/.next/server/app/api/tools/route/app-build-manifest.json +6 -9
- package/mcp-server/.next/server/app/api/tools/route/build-manifest.json +7 -10
- package/mcp-server/.next/server/app/api/tools/route.js +5 -4
- package/mcp-server/.next/server/app/index.html +1 -1
- package/mcp-server/.next/server/app/index.rsc +3 -3
- package/mcp-server/.next/server/app/logs/page/app-build-manifest.json +1 -1
- package/mcp-server/.next/server/app/logs/page_client-reference-manifest.js +1 -1
- package/mcp-server/.next/server/app/page/app-build-manifest.json +10 -15
- package/mcp-server/.next/server/app/page/build-manifest.json +7 -10
- package/mcp-server/.next/server/app/page.js +9 -7
- package/mcp-server/.next/server/app/page_client-reference-manifest.js +1 -1
- package/mcp-server/.next/server/app/replay/page/app-build-manifest.json +1 -1
- package/mcp-server/.next/server/app/replay/page_client-reference-manifest.js +1 -1
- package/mcp-server/.next/server/app/replay.html +1 -1
- package/mcp-server/.next/server/app/replay.rsc +2 -2
- package/mcp-server/.next/server/app-paths-manifest.json +15 -1
- package/mcp-server/.next/server/chunks/[root-of-the-server]__7f1ecf7b._.js.map +1 -1
- package/mcp-server/.next/server/chunks/[root-of-the-server]__82298dd3._.js.map +1 -1
- package/mcp-server/.next/server/chunks/_next-internal_server_app_api_tools_route_actions_4a0d5a18.js +1 -5
- package/mcp-server/.next/server/chunks/_next-internal_server_app_api_tools_route_actions_4a0d5a18.js.map +1 -6
- package/mcp-server/.next/server/chunks/ssr/0916f_next_dist_client_components_builtin_forbidden_7b57efa5.js +1 -30
- package/mcp-server/.next/server/chunks/ssr/0916f_next_dist_client_components_builtin_forbidden_7b57efa5.js.map +1 -6
- package/mcp-server/.next/server/chunks/ssr/0916f_next_dist_client_components_builtin_global-error_118601bd.js +1 -22
- package/mcp-server/.next/server/chunks/ssr/0916f_next_dist_client_components_builtin_global-error_118601bd.js.map +1 -8
- package/mcp-server/.next/server/chunks/ssr/0916f_next_dist_client_components_builtin_unauthorized_6614f15c.js +1 -30
- package/mcp-server/.next/server/chunks/ssr/0916f_next_dist_client_components_builtin_unauthorized_6614f15c.js.map +1 -6
- package/mcp-server/.next/server/chunks/ssr/0916f_next_dist_client_components_f453b63e._.js +1 -148
- package/mcp-server/.next/server/chunks/ssr/0916f_next_dist_client_components_f453b63e._.js.map +1 -8
- package/mcp-server/.next/server/chunks/ssr/_dc26a647._.js +1 -1
- package/mcp-server/.next/server/chunks/ssr/_dc26a647._.js.map +1 -1
- package/mcp-server/.next/server/chunks/ssr/_next-internal_server_app_page_actions_39d4fc33.js +1 -5
- package/mcp-server/.next/server/chunks/ssr/_next-internal_server_app_page_actions_39d4fc33.js.map +1 -6
- package/mcp-server/.next/server/middleware-build-manifest.js +7 -10
- package/mcp-server/.next/server/pages/404.html +1 -1
- package/mcp-server/.next/server/pages/500.html +2 -2
- package/mcp-server/.next/server/pages-manifest.json +4 -1
- package/mcp-server/.next/server/server-reference-manifest.js +1 -1
- package/mcp-server/.next/server/server-reference-manifest.json +1 -1
- package/mcp-server/.next/standalone/.next/BUILD_ID +1 -1
- package/mcp-server/.next/standalone/.next/app-build-manifest.json +5 -5
- package/mcp-server/.next/standalone/.next/build-manifest.json +2 -2
- package/mcp-server/.next/standalone/.next/prerender-manifest.json +16 -16
- package/mcp-server/.next/standalone/.next/server/app/_global-error.html +2 -2
- package/mcp-server/.next/standalone/.next/server/app/_global-error.rsc +1 -1
- package/mcp-server/.next/standalone/.next/server/app/_not-found/page/app-build-manifest.json +1 -1
- package/mcp-server/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/mcp-server/.next/standalone/.next/server/app/_not-found.html +1 -1
- package/mcp-server/.next/standalone/.next/server/app/_not-found.rsc +2 -2
- package/mcp-server/.next/standalone/.next/server/app/index.html +1 -1
- package/mcp-server/.next/standalone/.next/server/app/index.rsc +3 -3
- package/mcp-server/.next/standalone/.next/server/app/logs/page/app-build-manifest.json +1 -1
- package/mcp-server/.next/standalone/.next/server/app/logs/page_client-reference-manifest.js +1 -1
- package/mcp-server/.next/standalone/.next/server/app/page/app-build-manifest.json +2 -2
- package/mcp-server/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
- package/mcp-server/.next/standalone/.next/server/app/replay/page/app-build-manifest.json +1 -1
- package/mcp-server/.next/standalone/.next/server/app/replay/page_client-reference-manifest.js +1 -1
- package/mcp-server/.next/standalone/.next/server/app/replay.html +1 -1
- package/mcp-server/.next/standalone/.next/server/app/replay.rsc +2 -2
- package/mcp-server/.next/standalone/.next/server/chunks/ssr/_dc26a647._.js +1 -1
- package/mcp-server/.next/standalone/.next/server/pages/404.html +1 -1
- package/mcp-server/.next/standalone/.next/server/pages/500.html +2 -2
- package/mcp-server/.next/standalone/.next/server/server-reference-manifest.js +1 -1
- package/mcp-server/.next/standalone/.next/server/server-reference-manifest.json +1 -1
- package/mcp-server/.next/standalone/app/api/mcp/[transport]/route.ts +93 -91
- package/mcp-server/.next/static/chunks/{5dfb96bedc33a0a5.css → 6634762c4edabf25.css} +1 -1
- package/mcp-server/.next/static/chunks/aac71a4d8cd0d1d1.js +1 -0
- package/mcp-server/.next/trace +1 -3
- package/package.json +1 -1
- package/mcp-server/.next/server/chunks/0916f_next_c68840f1._.js +0 -14728
- package/mcp-server/.next/server/chunks/0916f_next_c68840f1._.js.map +0 -118
- package/mcp-server/.next/server/chunks/[root-of-the-server]__3dccd82a._.js +0 -248
- package/mcp-server/.next/server/chunks/[root-of-the-server]__3dccd82a._.js.map +0 -6
- package/mcp-server/.next/server/chunks/ssr/0916f_next_dist_76a62e93._.js +0 -5831
- package/mcp-server/.next/server/chunks/ssr/0916f_next_dist_76a62e93._.js.map +0 -89
- package/mcp-server/.next/server/chunks/ssr/0916f_next_dist_d231ced7._.js +0 -15764
- package/mcp-server/.next/server/chunks/ssr/0916f_next_dist_d231ced7._.js.map +0 -145
- package/mcp-server/.next/server/chunks/ssr/0916f_next_dist_dbf009ef._.js +0 -9174
- package/mcp-server/.next/server/chunks/ssr/0916f_next_dist_dbf009ef._.js.map +0 -51
- package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__1aaf5479._.js +0 -38
- package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__1aaf5479._.js.map +0 -5
- package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__7f148858._.js +0 -62
- package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__7f148858._.js.map +0 -5
- package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__95719760._.js +0 -54
- package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__95719760._.js.map +0 -8
- package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__b1782a10._.js +0 -813
- package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__b1782a10._.js.map +0 -6
- package/mcp-server/.next/server/chunks/ssr/[turbopack]_browser_dev_hmr-client_hmr-client_ts_818f0fdf._.js +0 -467
- package/mcp-server/.next/server/chunks/ssr/[turbopack]_browser_dev_hmr-client_hmr-client_ts_818f0fdf._.js.map +0 -6
- package/mcp-server/.next/server/chunks/ssr/[turbopack]_browser_dev_hmr-client_hmr-client_ts_89c5f8e8._.js +0 -12
- package/mcp-server/.next/server/chunks/ssr/[turbopack]_browser_dev_hmr-client_hmr-client_ts_89c5f8e8._.js.map +0 -5
- package/mcp-server/.next/server/chunks/ssr/_9c0d7aa1._.js +0 -100
- package/mcp-server/.next/server/chunks/ssr/_9c0d7aa1._.js.map +0 -7
- package/mcp-server/.next/server/chunks/ssr/node_modules__pnpm_cc7262c5._.js +0 -13866
- package/mcp-server/.next/server/chunks/ssr/node_modules__pnpm_cc7262c5._.js.map +0 -152
- package/mcp-server/.next/server/chunks/ssr/node_modules__pnpm_da0d0a14._.js +0 -13866
- package/mcp-server/.next/server/chunks/ssr/node_modules__pnpm_da0d0a14._.js.map +0 -152
- package/mcp-server/.next/static/chunks/0916f_next_dist_2e70ccdb._.js +0 -4068
- package/mcp-server/.next/static/chunks/0916f_next_dist_2e70ccdb._.js.map +0 -64
- package/mcp-server/.next/static/chunks/0916f_next_dist_b3493ca8._.js +0 -2780
- package/mcp-server/.next/static/chunks/0916f_next_dist_b3493ca8._.js.map +0 -27
- package/mcp-server/.next/static/chunks/0916f_next_dist_build_polyfills_polyfill-nomodule.js +0 -1
- package/mcp-server/.next/static/chunks/0916f_next_dist_client_components_builtin_global-error_80971850.js +0 -7
- package/mcp-server/.next/static/chunks/0916f_next_dist_client_d3483330._.js +0 -10175
- package/mcp-server/.next/static/chunks/0916f_next_dist_client_d3483330._.js.map +0 -103
- package/mcp-server/.next/static/chunks/0916f_next_dist_compiled_8cc8c301._.js +0 -5009
- package/mcp-server/.next/static/chunks/0916f_next_dist_compiled_8cc8c301._.js.map +0 -21
- package/mcp-server/.next/static/chunks/0916f_next_dist_compiled_next-devtools_index_94228adb.js +0 -30477
- package/mcp-server/.next/static/chunks/0916f_next_dist_compiled_next-devtools_index_94228adb.js.map +0 -6
- package/mcp-server/.next/static/chunks/0916f_next_dist_compiled_react-dom_c74e1e00._.js +0 -14617
- package/mcp-server/.next/static/chunks/0916f_next_dist_compiled_react-dom_c74e1e00._.js.map +0 -9
- package/mcp-server/.next/static/chunks/1c2c4101e46d1c5e.js +0 -1
- package/mcp-server/.next/static/chunks/69652_@swc_helpers_cjs_77b72907._.js +0 -85
- package/mcp-server/.next/static/chunks/69652_@swc_helpers_cjs_77b72907._.js.map +0 -10
- package/mcp-server/.next/static/chunks/[turbopack]_browser_dev_hmr-client_hmr-client_ts_29af464a._.js +0 -7
- package/mcp-server/.next/static/chunks/[turbopack]_browser_dev_hmr-client_hmr-client_ts_c8c997ce._.js +0 -476
- package/mcp-server/.next/static/chunks/[turbopack]_browser_dev_hmr-client_hmr-client_ts_c8c997ce._.js.map +0 -6
- package/mcp-server/.next/static/chunks/[turbopack]_browser_dev_hmr-client_hmr-client_ts_d335a95d._.js +0 -13
- package/mcp-server/.next/static/chunks/[turbopack]_browser_dev_hmr-client_hmr-client_ts_d335a95d._.js.map +0 -5
- package/mcp-server/.next/static/chunks/_9429dbc3._.js +0 -2117
- package/mcp-server/.next/static/chunks/_9429dbc3._.js.map +0 -16
- package/mcp-server/.next/static/chunks/_a0ff3932._.js +0 -13
- package/mcp-server/.next/static/chunks/_efaa0516._.js.map +0 -10
- package/mcp-server/.next/static/chunks/app_244179ef._.css +0 -4548
- package/mcp-server/.next/static/chunks/app_244179ef._.css.map +0 -7
- package/mcp-server/.next/static/chunks/app_compiled_css_bad6b30c._.single.css +0 -2117
- package/mcp-server/.next/static/chunks/app_compiled_css_bad6b30c._.single.css.map +0 -6
- package/mcp-server/.next/static/chunks/app_globals_css_bad6b30c._.single.css +0 -2432
- package/mcp-server/.next/static/chunks/app_globals_css_bad6b30c._.single.css.map +0 -6
- package/mcp-server/.next/static/chunks/app_layout_tsx_80971850._.js +0 -7
- package/mcp-server/.next/static/chunks/app_page_tsx_6ea10ef3._.js +0 -7
- package/mcp-server/.next/static/chunks/turbopack-_efaa0516._.js +0 -1836
- package/mcp-server/.next/static/development/_ssgManifest.js +0 -1
- package/mcp-server/.next/static/vcdr8uFblpN3gCi_831po/_buildManifest.js +0 -11
- package/mcp-server/.next/static/vcdr8uFblpN3gCi_831po/_clientMiddlewareManifest.json +0 -1
- /package/mcp-server/.next/static/{development → fgx2Ltd5vbloYUQlVKX60}/_buildManifest.js +0 -0
- /package/mcp-server/.next/static/{development → fgx2Ltd5vbloYUQlVKX60}/_clientMiddlewareManifest.json +0 -0
- /package/mcp-server/.next/static/{vcdr8uFblpN3gCi_831po → fgx2Ltd5vbloYUQlVKX60}/_ssgManifest.js +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/querystring.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/format-url.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/utils.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/parse-path.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/add-path-prefix.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/remove-trailing-slash.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/normalize-trailing-slash.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/add-base-path.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/router-reducer-types.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/app-router-headers.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/is-thenable.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/use-action-queue.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/app-call-server.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/app-find-source-map-url.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/flight-data-helpers.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/app-build-id.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/hash.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/cache-busting-search-param.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/set-cache-busting-search-param.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/segment-cache/segment-value-encoding.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/route-params.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/fetch-server-response.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/create-href-from-url.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/create-router-cache-key.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/invalidate-cache-below-flight-segmentpath.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/match-segments.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/fill-lazy-items-till-leaf-with-head.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/invalidate-cache-by-router-state.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/fill-cache-with-new-subtree-data.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/apply-flight-data.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/refetch-inactive-parallel-segments.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/apply-router-state-patch-to-tree.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/should-hard-navigate.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/is-navigating-to-new-root-layout.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/page-path/ensure-leading-slash.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/app-paths.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/interception-routes.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/compute-changed-path.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/handle-mutable.ts","turbopack:///[project]/node_modules/.pnpm/@swc+helpers@0.5.15/node_modules/@swc/helpers/cjs/_class_private_field_loose_base.cjs","turbopack:///[project]/node_modules/.pnpm/@swc+helpers@0.5.15/node_modules/@swc/helpers/cjs/_class_private_field_loose_key.cjs","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/promise-queue.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/prefetch-cache-utils.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/reducers/prefetch-reducer.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/html-bots.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/is-bot.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/app-router-announcer.tsx","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/redirect-boundary.tsx","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/reducers/find-head-in-cache.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/unresolved-thenable.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/path-has-prefix.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/has-base-path.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/remove-base-path.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/nav-failure-handler.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/errors/graceful-degrade-boundary.tsx","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/navigation-untracked.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/error-boundary.tsx","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/errors/root-error-boundary.tsx","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/lib/framework/boundary-components.tsx","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/app-router.tsx","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/ppr-navigations.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/clear-cache-node-data-for-segment-path.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/aliased-prefetch-navigations.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/segment-cache.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/reducers/navigate-reducer.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/reducers/server-patch-reducer.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/reducers/restore-reducer.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/handle-segment-mismatch.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/reducers/has-interception-route-in-current-tree.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/reducers/refresh-reducer.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/reducers/hmr-refresh-reducer.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/assign-location.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/server-reference-info.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/reducers/server-action-reducer.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/router-reducer.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/app-router-instance.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/links.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/is-local-url.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/app-dir/link.tsx","turbopack:///[project]/app/page.tsx"],"sourcesContent":["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 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 runtimeConfig?: { [key: string]: any }\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","import type { CacheNode } from '../../../shared/lib/app-router-types'\nimport type {\n FlightRouterState,\n FlightSegmentPath,\n} from '../../../shared/lib/app-router-types'\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_PREFETCH = 'prefetch'\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 canonicalUrl?: string\n scrollableSegments?: FlightSegmentPath[]\n pendingPush?: boolean\n cache?: CacheNode\n prefetchCache?: AppRouterState['prefetchCache']\n hashFragment?: string\n shouldScroll?: boolean\n preserveCustomHistoryState?: boolean\n onlyHashChange?: boolean\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 origin: Location['origin']\n}\n\nexport interface HmrRefreshAction {\n type: typeof ACTION_HMR_REFRESH\n origin: Location['origin']\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 allowAliasing: 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 tree: FlightRouterState | undefined\n}\n\n/**\n * Server-patch applies the provided Flight data to the cache and router tree.\n * - Only triggered in layout-router.\n * - Creates a new cache and router state with the Flight data applied.\n */\nexport interface ServerPatchAction {\n type: typeof ACTION_SERVER_PATCH\n navigatedAt: number\n serverResponse: FetchServerResponseResult\n previousTree: FlightRouterState\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 * - `temporary` - a temporary prefetch entry is added to the cache, this is used when prefetch={false} is used in next/link or when you push a route programmatically.\n */\n\nexport enum PrefetchKind {\n AUTO = 'auto',\n FULL = 'full',\n TEMPORARY = 'temporary',\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 */\nexport interface PrefetchAction {\n type: typeof ACTION_PREFETCH\n url: URL\n kind: PrefetchKind\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\nexport type PrefetchCacheEntry = {\n treeAtTimeOfPrefetch: FlightRouterState\n data: Promise<FetchServerResponseResult>\n kind: PrefetchKind\n prefetchTime: number\n staleTime: number\n lastUsedTime: number | null\n key: string\n status: PrefetchCacheEntryStatus\n url: URL\n}\n\nexport enum PrefetchCacheEntryStatus {\n fresh = 'fresh',\n reusable = 'reusable',\n expired = 'expired',\n stale = 'stale',\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 * Prefetched data is stored separately in `prefetchCache`, that is applied during ACTION_NAVIGATE.\n */\n cache: CacheNode\n /**\n * Cache that holds prefetched Flight responses keyed by url.\n */\n prefetchCache: Map<string, PrefetchCacheEntry>\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 /**\n * The underlying \"url\" representing the UI state, which is used for intercepting routes.\n */\n nextUrl: string | null\n}\n\nexport type ReadonlyReducerState = Readonly<AppRouterState>\nexport type ReducerState = Promise<AppRouterState> | AppRouterState\nexport type ReducerActions = Readonly<\n | RefreshAction\n | NavigateAction\n | RestoreAction\n | ServerPatchAction\n | PrefetchAction\n | HmrRefreshAction\n | ServerActionAction\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 * 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 } 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\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 return isThenable(state) ? use(state) : state\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 {\n CacheNodeSeedData,\n FlightData,\n FlightDataPath,\n FlightRouterState,\n FlightSegmentPath,\n Segment,\n HeadData,\n} from '../shared/lib/app-router-types'\nimport { PAGE_SEGMENT_KEY } from '../shared/lib/segment'\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 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","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>\nexport type SegmentCacheKeyPart = Opaque<'SegmentCacheKeyPart', string>\nexport type SegmentCacheKey = Opaque<'SegmentCacheKey', string>\n\nexport const ROOT_SEGMENT_REQUEST_KEY = '' as SegmentRequestKey\nexport const ROOT_SEGMENT_CACHE_KEY = '' as SegmentCacheKey\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\nexport function createSegmentCacheKeyPart(\n requestKeyPart: SegmentRequestKeyPart,\n segment: FlightRouterStateSegment\n): SegmentCacheKeyPart {\n if (typeof segment === 'string') {\n return requestKeyPart as any as SegmentCacheKeyPart\n }\n const paramValue = segment[1]\n const safeValue = encodeToFilesystemAndURLSafeString(paramValue)\n return (requestKeyPart + '$' + safeValue) as SegmentCacheKeyPart\n}\n\nexport function appendSegmentCacheKeyPart(\n parentSegmentKey: SegmentCacheKey,\n parallelRouteKey: string,\n childCacheKeyPart: SegmentCacheKeyPart\n): SegmentCacheKey {\n const slotKey =\n parallelRouteKey === 'children'\n ? childCacheKeyPart\n : `@${encodeToFilesystemAndURLSafeString(parallelRouteKey)}/${childCacheKeyPart}`\n return (parentSegmentKey + '/' + slotKey) as SegmentCacheKey\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 { NormalizedSearch } from './components/segment-cache'\nimport type { RSCResponse } from './components/router-reducer/fetch-server-response'\n\nexport type RouteParamValue = string | Array<string> | null\n\nexport type RouteParam = {\n name: string\n value: RouteParamValue\n type: DynamicParamTypesShort\n}\n\nexport function getRenderedSearch(response: RSCResponse): 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(response: RSCResponse): string {\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 (\n rewrittenPath ?? urlToUrlWithoutFlightMarker(new URL(response.url)).pathname\n )\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 case 'ci': {\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 // 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 case 'di': {\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 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","'use client'\n\n// TODO: Explicitly import from client.browser\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { createFromReadableStream as createFromReadableStreamBrowser } from 'react-server-dom-webpack/client'\n\nimport type {\n FlightRouterState,\n NavigationFlightResponse,\n} from '../../../shared/lib/app-router-types'\n\nimport type { NEXT_ROUTER_SEGMENT_PREFETCH_HEADER } from '../app-router-headers'\nimport {\n NEXT_ROUTER_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} from '../app-router-headers'\nimport { callServer } from '../../app-call-server'\nimport { findSourceMapURL } from '../../app-find-source-map-url'\nimport { PrefetchKind } from './router-reducer-types'\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 { urlToUrlWithoutFlightMarker } from '../../route-params'\n\nconst createFromReadableStream =\n createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream']\n\nlet createDebugChannel:\n | typeof import('../../dev/debug-channel').createDebugChannel\n | undefined\n\nif (process.env.NODE_ENV !== 'production') {\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 prefetchKind?: PrefetchKind\n readonly isHmrRefresh?: boolean\n}\n\nexport type FetchServerResponseResult = {\n flightData: NormalizedFlightData[] | string\n canonicalUrl: URL | undefined\n couldBeIntercepted: boolean\n prerendered: boolean\n postponed: boolean\n staleTime: number\n}\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}\n\nfunction doMpaNavigation(url: string): FetchServerResponseResult {\n return {\n flightData: urlToUrlWithoutFlightMarker(\n new URL(url, location.origin)\n ).toString(),\n canonicalUrl: undefined,\n couldBeIntercepted: false,\n prerendered: false,\n postponed: false,\n staleTime: -1,\n }\n}\n\nlet abortController = new AbortController()\n\nif (typeof window !== 'undefined') {\n // Abort any in-flight requests when the page is unloaded, e.g. due to\n // reloading the page or performing hard navigations. This allows us to ignore\n // what would otherwise be a thrown TypeError when the browser cancels the\n // requests.\n window.addEventListener('pagehide', () => {\n abortController.abort()\n })\n\n // Use a fresh AbortController instance on pageshow, e.g. when navigating back\n // and the JavaScript execution context is restored by the browser.\n window.addEventListener('pageshow', () => {\n abortController = new AbortController()\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, prefetchKind } = 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 /**\n * Three cases:\n * - `prefetchKind` is `undefined`, it means it's a normal navigation, so we want to prefetch the page data fully\n * - `prefetchKind` is `full` - we want to prefetch the whole page so same as above\n * - `prefetchKind` is `auto` - if the page is dynamic, prefetch the page data partially, if static prefetch the page data fully\n */\n if (prefetchKind === PrefetchKind.AUTO) {\n headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'\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 try {\n // When creating a \"temporary\" prefetch (the \"on-demand\" prefetch that gets created on navigation, if one doesn't exist)\n // we send the request with a \"high\" priority as it's in response to a user interaction that could be blocking a transition.\n // Otherwise, all other prefetches are sent with a \"low\" priority.\n // We use \"auto\" for in all other cases to match the existing default, as this function is shared outside of prefetching.\n const fetchPriority = prefetchKind\n ? prefetchKind === PrefetchKind.TEMPORARY\n ? 'high'\n : 'low'\n : 'auto'\n\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 const res = await createFetch(\n url,\n headers,\n fetchPriority,\n abortController.signal\n )\n\n const responseUrl = urlToUrlWithoutFlightMarker(new URL(res.url))\n const canonicalUrl = res.redirected ? responseUrl : undefined\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 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 // Handle the `fetch` readable stream that can be unwrapped by `React.use`.\n const flightStream = postponed\n ? createUnclosingPrefetchStream(res.body)\n : res.body\n const response = await (createFromNextReadableStream(\n flightStream,\n res.headers\n ) as Promise<NavigationFlightResponse>)\n\n if (getAppBuildId() !== response.b) {\n return doMpaNavigation(res.url)\n }\n\n return {\n flightData: normalizeFlightData(response.f),\n canonicalUrl: canonicalUrl,\n couldBeIntercepted: interception,\n prerendered: response.S,\n postponed,\n staleTime,\n }\n } catch (err) {\n if (!abortController.signal.aborted) {\n console.error(\n `Failed to fetch RSC payload for ${url}. 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 {\n flightData: url.toString(),\n canonicalUrl: undefined,\n couldBeIntercepted: false,\n prerendered: false,\n postponed: false,\n staleTime: -1,\n }\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 = {\n ok: boolean\n redirected: boolean\n headers: Headers\n body: ReadableStream<Uint8Array> | null\n status: number\n url: string\n}\n\nexport async function createFetch(\n url: URL,\n headers: RequestHeaders,\n fetchPriority: 'auto' | 'high' | 'low' | null,\n signal?: AbortSignal\n): Promise<RSCResponse> {\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 if (process.env.NEXT_DEPLOYMENT_ID) {\n headers['x-deployment-id'] = process.env.NEXT_DEPLOYMENT_ID\n }\n\n if (process.env.NODE_ENV !== 'production' && self.__next_r) {\n headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r\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 browserResponse = await fetch(fetchUrl, fetchOptions)\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 fetchUrl = new URL(responseUrl)\n setCacheBustingSearchParam(fetchUrl, headers)\n browserResponse = await fetch(fetchUrl, fetchOptions)\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 = {\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\n return rscResponse\n}\n\nexport function createFromNextReadableStream(\n flightStream: ReadableStream<Uint8Array>,\n responseHeaders: Headers\n): Promise<unknown> {\n return createFromReadableStream(flightStream, {\n callServer,\n findSourceMapURL,\n debugChannel: createDebugChannel && createDebugChannel(responseHeaders),\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","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 { 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 {\n CacheNode,\n FlightSegmentPath,\n} from '../../../shared/lib/app-router-types'\nimport { createRouterCacheKey } from './create-router-cache-key'\nimport { getNextFlightSegmentPath } from '../../flight-data-helpers'\n\n/**\n * Fill cache up to the end of the flightSegmentPath, invalidating anything below it.\n */\nexport function invalidateCacheBelowFlightSegmentPath(\n newCache: CacheNode,\n existingCache: CacheNode,\n flightSegmentPath: FlightSegmentPath\n): void {\n const isLastEntry = flightSegmentPath.length <= 2\n const [parallelRouteKey, segment] = flightSegmentPath\n\n const cacheKey = createRouterCacheKey(segment)\n\n const existingChildSegmentMap =\n existingCache.parallelRoutes.get(parallelRouteKey)\n\n if (!existingChildSegmentMap) {\n // Bailout because the existing cache does not have the path to the leaf node\n // Will trigger lazy fetch in layout-router because of missing segment\n return\n }\n\n let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey)\n if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {\n childSegmentMap = new Map(existingChildSegmentMap)\n newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap)\n }\n\n // In case of last entry don't copy further down.\n if (isLastEntry) {\n childSegmentMap.delete(cacheKey)\n return\n }\n\n const existingChildCacheNode = existingChildSegmentMap.get(cacheKey)\n let childCacheNode = childSegmentMap.get(cacheKey)\n\n if (!childCacheNode || !existingChildCacheNode) {\n // Bailout because the existing cache does not have the path to the leaf node\n // Will trigger lazy fetch in layout-router because of missing segment\n return\n }\n\n if (childCacheNode === existingChildCacheNode) {\n childCacheNode = {\n lazyData: childCacheNode.lazyData,\n rsc: childCacheNode.rsc,\n prefetchRsc: childCacheNode.prefetchRsc,\n head: childCacheNode.head,\n prefetchHead: childCacheNode.prefetchHead,\n parallelRoutes: new Map(childCacheNode.parallelRoutes),\n } as CacheNode\n childSegmentMap.set(cacheKey, childCacheNode)\n }\n\n invalidateCacheBelowFlightSegmentPath(\n childCacheNode,\n existingChildCacheNode,\n getNextFlightSegmentPath(flightSegmentPath)\n )\n}\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","import type { CacheNode } from '../../../shared/lib/app-router-types'\nimport type {\n FlightRouterState,\n CacheNodeSeedData,\n} from '../../../shared/lib/app-router-types'\nimport { createRouterCacheKey } from './create-router-cache-key'\nimport {\n PrefetchCacheEntryStatus,\n type PrefetchCacheEntry,\n} from './router-reducer-types'\n\nexport function fillLazyItemsTillLeafWithHead(\n navigatedAt: number,\n newCache: CacheNode,\n existingCache: CacheNode | undefined,\n routerState: FlightRouterState,\n cacheNodeSeedData: CacheNodeSeedData | null,\n head: React.ReactNode,\n prefetchEntry: PrefetchCacheEntry | undefined\n): void {\n const isLastSegment = Object.keys(routerState[1]).length === 0\n if (isLastSegment) {\n newCache.head = head\n return\n }\n // Remove segment that we got data for so that it is filled in during rendering of rsc.\n for (const key in routerState[1]) {\n const parallelRouteState = routerState[1][key]\n const segmentForParallelRoute = parallelRouteState[0]\n const cacheKey = createRouterCacheKey(segmentForParallelRoute)\n\n // TODO: We should traverse the cacheNodeSeedData tree instead of the router\n // state tree. Ideally, they would always be the same shape, but because of\n // the loading.js pattern, cacheNodeSeedData sometimes only represents a\n // partial tree. That's why this node is sometimes null. Once PPR lands,\n // loading.js will no longer have special behavior and we can traverse the\n // data tree instead.\n //\n // We should also consider merging the router state tree and the data tree\n // in the response format, so that we don't have to send the keys twice.\n // Then the client can convert them into separate representations.\n const parallelSeedData =\n cacheNodeSeedData !== null && cacheNodeSeedData[2][key] !== undefined\n ? cacheNodeSeedData[2][key]\n : null\n if (existingCache) {\n const existingParallelRoutesCacheNode =\n existingCache.parallelRoutes.get(key)\n if (existingParallelRoutesCacheNode) {\n const hasReusablePrefetch =\n prefetchEntry?.kind === 'auto' &&\n prefetchEntry.status === PrefetchCacheEntryStatus.reusable\n\n let parallelRouteCacheNode = new Map(existingParallelRoutesCacheNode)\n const existingCacheNode = parallelRouteCacheNode.get(cacheKey)\n let newCacheNode: CacheNode\n if (parallelSeedData !== null) {\n // New data was sent from the server.\n const seedNode = parallelSeedData[1]\n const loading = parallelSeedData[3]\n newCacheNode = {\n lazyData: null,\n rsc: seedNode,\n // This is a PPR-only field. When PPR is enabled, we shouldn't hit\n // this path during a navigation, but until PPR is fully implemented\n // yet it's possible the existing node does have a non-null\n // `prefetchRsc`. As an incremental step, we'll just de-opt to the\n // old behavior — no PPR value.\n prefetchRsc: null,\n head: null,\n prefetchHead: null,\n loading,\n parallelRoutes: new Map(existingCacheNode?.parallelRoutes),\n navigatedAt,\n }\n } else if (hasReusablePrefetch && existingCacheNode) {\n // No new data was sent from the server, but the existing cache node\n // was prefetched, so we should reuse that.\n newCacheNode = {\n lazyData: existingCacheNode.lazyData,\n rsc: existingCacheNode.rsc,\n // This is a PPR-only field. Unlike the previous branch, since we're\n // just cloning the existing cache node, we might as well keep the\n // PPR value, if it exists.\n prefetchRsc: existingCacheNode.prefetchRsc,\n head: existingCacheNode.head,\n prefetchHead: existingCacheNode.prefetchHead,\n parallelRoutes: new Map(existingCacheNode.parallelRoutes),\n loading: existingCacheNode.loading,\n } as CacheNode\n } else {\n // No data available for this node. This will trigger a lazy fetch\n // during render.\n newCacheNode = {\n lazyData: null,\n rsc: null,\n prefetchRsc: null,\n head: null,\n prefetchHead: null,\n parallelRoutes: new Map(existingCacheNode?.parallelRoutes),\n loading: null,\n navigatedAt,\n }\n }\n\n // Overrides the cache key with the new cache node.\n parallelRouteCacheNode.set(cacheKey, newCacheNode)\n // Traverse deeper to apply the head / fill lazy items till the head.\n fillLazyItemsTillLeafWithHead(\n navigatedAt,\n newCacheNode,\n existingCacheNode,\n parallelRouteState,\n parallelSeedData ? parallelSeedData : null,\n head,\n prefetchEntry\n )\n\n newCache.parallelRoutes.set(key, parallelRouteCacheNode)\n continue\n }\n }\n\n let newCacheNode: CacheNode\n if (parallelSeedData !== null) {\n // New data was sent from the server.\n const seedNode = parallelSeedData[1]\n const loading = parallelSeedData[3]\n newCacheNode = {\n lazyData: null,\n rsc: seedNode,\n prefetchRsc: null,\n head: null,\n prefetchHead: null,\n parallelRoutes: new Map(),\n loading,\n navigatedAt,\n }\n } else {\n // No data available for this node. This will trigger a lazy fetch\n // during render.\n newCacheNode = {\n lazyData: null,\n rsc: null,\n prefetchRsc: null,\n head: null,\n prefetchHead: null,\n parallelRoutes: new Map(),\n loading: null,\n navigatedAt,\n }\n }\n\n const existingParallelRoutes = newCache.parallelRoutes.get(key)\n if (existingParallelRoutes) {\n existingParallelRoutes.set(cacheKey, newCacheNode)\n } else {\n newCache.parallelRoutes.set(key, new Map([[cacheKey, newCacheNode]]))\n }\n\n fillLazyItemsTillLeafWithHead(\n navigatedAt,\n newCacheNode,\n undefined,\n parallelRouteState,\n parallelSeedData,\n head,\n prefetchEntry\n )\n }\n}\n","import type {\n CacheNode,\n FlightRouterState,\n} from '../../../shared/lib/app-router-types'\nimport { createRouterCacheKey } from './create-router-cache-key'\n\n/**\n * Invalidate cache one level down from the router state.\n */\nexport function invalidateCacheByRouterState(\n newCache: CacheNode,\n existingCache: CacheNode,\n routerState: FlightRouterState\n): void {\n // Remove segment that we got data for so that it is filled in during rendering of rsc.\n for (const key in routerState[1]) {\n const segmentForParallelRoute = routerState[1][key][0]\n const cacheKey = createRouterCacheKey(segmentForParallelRoute)\n const existingParallelRoutesCacheNode =\n existingCache.parallelRoutes.get(key)\n if (existingParallelRoutesCacheNode) {\n let parallelRouteCacheNode = new Map(existingParallelRoutesCacheNode)\n parallelRouteCacheNode.delete(cacheKey)\n newCache.parallelRoutes.set(key, parallelRouteCacheNode)\n }\n }\n}\n","import type { CacheNode, Segment } from '../../../shared/lib/app-router-types'\nimport { invalidateCacheByRouterState } from './invalidate-cache-by-router-state'\nimport { fillLazyItemsTillLeafWithHead } from './fill-lazy-items-till-leaf-with-head'\nimport { createRouterCacheKey } from './create-router-cache-key'\nimport type { PrefetchCacheEntry } from './router-reducer-types'\nimport { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'\nimport type { NormalizedFlightData } from '../../flight-data-helpers'\n\n/**\n * Common logic for filling cache with new sub tree data.\n */\nfunction fillCacheHelper(\n navigatedAt: number,\n newCache: CacheNode,\n existingCache: CacheNode,\n flightData: NormalizedFlightData,\n prefetchEntry: PrefetchCacheEntry | undefined,\n fillLazyItems: boolean\n): void {\n const {\n segmentPath,\n seedData: cacheNodeSeedData,\n tree: treePatch,\n head,\n } = flightData\n let newCacheNode = newCache\n let existingCacheNode = existingCache\n\n for (let i = 0; i < segmentPath.length; i += 2) {\n const parallelRouteKey: string = segmentPath[i]\n const segment: Segment = segmentPath[i + 1]\n\n // segmentPath is a repeating tuple of parallelRouteKey and segment\n // we know we've hit the last entry we've reached our final pair\n const isLastEntry = i === segmentPath.length - 2\n const cacheKey = createRouterCacheKey(segment)\n\n const existingChildSegmentMap =\n existingCacheNode.parallelRoutes.get(parallelRouteKey)\n\n if (!existingChildSegmentMap) {\n // Bailout because the existing cache does not have the path to the leaf node\n // Will trigger lazy fetch in layout-router because of missing segment\n continue\n }\n\n let childSegmentMap = newCacheNode.parallelRoutes.get(parallelRouteKey)\n if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {\n childSegmentMap = new Map(existingChildSegmentMap)\n newCacheNode.parallelRoutes.set(parallelRouteKey, childSegmentMap)\n }\n\n const existingChildCacheNode = existingChildSegmentMap.get(cacheKey)\n let childCacheNode = childSegmentMap.get(cacheKey)\n\n if (isLastEntry) {\n if (\n cacheNodeSeedData &&\n (!childCacheNode ||\n !childCacheNode.lazyData ||\n childCacheNode === existingChildCacheNode)\n ) {\n const incomingSegment = cacheNodeSeedData[0]\n const rsc = cacheNodeSeedData[1]\n const loading = cacheNodeSeedData[3]\n\n childCacheNode = {\n lazyData: null,\n // When `fillLazyItems` is false, we only want to fill the RSC data for the layout,\n // not the page segment.\n rsc:\n fillLazyItems || incomingSegment !== PAGE_SEGMENT_KEY ? rsc : null,\n prefetchRsc: null,\n head: null,\n prefetchHead: null,\n loading,\n parallelRoutes:\n fillLazyItems && existingChildCacheNode\n ? new Map(existingChildCacheNode.parallelRoutes)\n : new Map(),\n navigatedAt,\n }\n\n if (existingChildCacheNode && fillLazyItems) {\n invalidateCacheByRouterState(\n childCacheNode,\n existingChildCacheNode,\n treePatch\n )\n }\n if (fillLazyItems) {\n fillLazyItemsTillLeafWithHead(\n navigatedAt,\n childCacheNode,\n existingChildCacheNode,\n treePatch,\n cacheNodeSeedData,\n head,\n prefetchEntry\n )\n }\n\n childSegmentMap.set(cacheKey, childCacheNode)\n }\n continue\n }\n\n if (!childCacheNode || !existingChildCacheNode) {\n // Bailout because the existing cache does not have the path to the leaf node\n // Will trigger lazy fetch in layout-router because of missing segment\n continue\n }\n\n if (childCacheNode === existingChildCacheNode) {\n childCacheNode = {\n lazyData: childCacheNode.lazyData,\n rsc: childCacheNode.rsc,\n prefetchRsc: childCacheNode.prefetchRsc,\n head: childCacheNode.head,\n prefetchHead: childCacheNode.prefetchHead,\n parallelRoutes: new Map(childCacheNode.parallelRoutes),\n loading: childCacheNode.loading,\n } as CacheNode\n childSegmentMap.set(cacheKey, childCacheNode)\n }\n\n // Move deeper into the cache nodes\n newCacheNode = childCacheNode\n existingCacheNode = existingChildCacheNode\n }\n}\n\n/**\n * Fill cache with rsc based on flightDataPath\n */\nexport function fillCacheWithNewSubTreeData(\n navigatedAt: number,\n newCache: CacheNode,\n existingCache: CacheNode,\n flightData: NormalizedFlightData,\n prefetchEntry?: PrefetchCacheEntry\n): void {\n fillCacheHelper(\n navigatedAt,\n newCache,\n existingCache,\n flightData,\n prefetchEntry,\n true\n )\n}\n\nexport function fillCacheWithNewSubTreeDataButOnlyLoading(\n navigatedAt: number,\n newCache: CacheNode,\n existingCache: CacheNode,\n flightData: NormalizedFlightData,\n prefetchEntry?: PrefetchCacheEntry\n): void {\n fillCacheHelper(\n navigatedAt,\n newCache,\n existingCache,\n flightData,\n prefetchEntry,\n false\n )\n}\n","import type { CacheNode } from '../../../shared/lib/app-router-types'\nimport { fillLazyItemsTillLeafWithHead } from './fill-lazy-items-till-leaf-with-head'\nimport { fillCacheWithNewSubTreeData } from './fill-cache-with-new-subtree-data'\nimport type { PrefetchCacheEntry } from './router-reducer-types'\nimport type { NormalizedFlightData } from '../../flight-data-helpers'\n\nexport function applyFlightData(\n navigatedAt: number,\n existingCache: CacheNode,\n cache: CacheNode,\n flightData: NormalizedFlightData,\n prefetchEntry?: PrefetchCacheEntry\n): boolean {\n // The one before last item is the router state tree patch\n const { tree: treePatch, seedData, head, isRootRender } = flightData\n\n // Handles case where prefetch only returns the router tree patch without rendered components.\n if (seedData === null) {\n return false\n }\n\n if (isRootRender) {\n const rsc = seedData[1]\n const loading = seedData[3]\n cache.loading = loading\n cache.rsc = rsc\n // This is a PPR-only field. When PPR is enabled, we shouldn't hit\n // this path during a navigation, but until PPR is fully implemented\n // yet it's possible the existing node does have a non-null\n // `prefetchRsc`. As an incremental step, we'll just de-opt to the\n // old behavior — no PPR value.\n cache.prefetchRsc = null\n fillLazyItemsTillLeafWithHead(\n navigatedAt,\n cache,\n existingCache,\n treePatch,\n seedData,\n head,\n prefetchEntry\n )\n } else {\n // Copy rsc for the root node of the cache.\n cache.rsc = existingCache.rsc\n // This is a PPR-only field. Unlike the previous branch, since we're\n // just cloning the existing cache node, we might as well keep the\n // PPR value, if it exists.\n cache.prefetchRsc = existingCache.prefetchRsc\n cache.parallelRoutes = new Map(existingCache.parallelRoutes)\n cache.loading = existingCache.loading\n // Create a copy of the existing cache with the rsc applied.\n fillCacheWithNewSubTreeData(\n navigatedAt,\n cache,\n existingCache,\n flightData,\n prefetchEntry\n )\n }\n\n return true\n}\n","import type {\n FlightRouterState,\n CacheNode,\n} from '../../../shared/lib/app-router-types'\nimport type { AppRouterState } from './router-reducer-types'\nimport { applyFlightData } from './apply-flight-data'\nimport { fetchServerResponse } from './fetch-server-response'\nimport { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'\n\ninterface RefreshInactiveParallelSegments {\n navigatedAt: number\n state: AppRouterState\n updatedTree: FlightRouterState\n updatedCache: CacheNode\n includeNextUrl: boolean\n canonicalUrl: string\n}\n\n/**\n * Refreshes inactive segments that are still in the current FlightRouterState.\n * A segment is considered \"inactive\" when the server response indicates it didn't match to a page component.\n * This happens during a soft-navigation, where the server will want to patch in the segment\n * with the \"default\" component, but we explicitly ignore the server in this case\n * and keep the existing state for that segment. New data for inactive segments are inherently\n * not part of the server response when we patch the tree, because they were associated with a response\n * from an earlier navigation/request. For each segment, once it becomes \"active\", we encode the URL that provided\n * the data for it. This function traverses parallel routes looking for these markers so that it can re-fetch\n * and patch the new data into the tree.\n */\nexport async function refreshInactiveParallelSegments(\n options: RefreshInactiveParallelSegments\n) {\n const fetchedSegments = new Set<string>()\n await refreshInactiveParallelSegmentsImpl({\n ...options,\n rootTree: options.updatedTree,\n fetchedSegments,\n })\n}\n\nasync function refreshInactiveParallelSegmentsImpl({\n navigatedAt,\n state,\n updatedTree,\n updatedCache,\n includeNextUrl,\n fetchedSegments,\n rootTree = updatedTree,\n canonicalUrl,\n}: RefreshInactiveParallelSegments & {\n fetchedSegments: Set<string>\n rootTree: FlightRouterState\n}) {\n const [, parallelRoutes, refetchPath, refetchMarker] = updatedTree\n const fetchPromises = []\n\n if (\n refetchPath &&\n refetchPath !== canonicalUrl &&\n refetchMarker === 'refresh' &&\n // it's possible for the tree to contain multiple segments that contain data at the same URL\n // we keep track of them so we can dedupe the requests\n !fetchedSegments.has(refetchPath)\n ) {\n fetchedSegments.add(refetchPath) // Mark this URL as fetched\n\n // Eagerly kick off the fetch for the refetch path & the parallel routes. This should be fine to do as they each operate\n // independently on their own cache nodes, and `applyFlightData` will copy anything it doesn't care about from the existing cache.\n const fetchPromise = fetchServerResponse(\n new URL(refetchPath, location.origin),\n {\n // refetch from the root of the updated tree, otherwise it will be scoped to the current segment\n // and might not contain the data we need to patch in interception route data (such as dynamic params from a previous segment)\n flightRouterState: [rootTree[0], rootTree[1], rootTree[2], 'refetch'],\n nextUrl: includeNextUrl ? state.nextUrl : null,\n }\n ).then(({ flightData }) => {\n if (typeof flightData !== 'string') {\n for (const flightDataPath of flightData) {\n // we only pass the new cache as this function is called after clearing the router cache\n // and filling in the new page data from the server. Meaning the existing cache is actually the cache that's\n // just been created & has been written to, but hasn't been \"committed\" yet.\n applyFlightData(\n navigatedAt,\n updatedCache,\n updatedCache,\n flightDataPath\n )\n }\n } else {\n // When flightData is a string, it suggests that the server response should have triggered an MPA navigation\n // I'm not 100% sure of this decision, but it seems unlikely that we'd want to introduce a redirect side effect\n // when refreshing on-screen data, so handling this has been ommitted.\n }\n })\n\n fetchPromises.push(fetchPromise)\n }\n\n for (const key in parallelRoutes) {\n const parallelFetchPromise = refreshInactiveParallelSegmentsImpl({\n navigatedAt,\n state,\n updatedTree: parallelRoutes[key],\n updatedCache,\n includeNextUrl,\n fetchedSegments,\n rootTree,\n canonicalUrl,\n })\n\n fetchPromises.push(parallelFetchPromise)\n }\n\n await Promise.all(fetchPromises)\n}\n\n/**\n * Walks the current parallel segments to determine if they are \"active\".\n * An active parallel route will have a `__PAGE__` segment in the FlightRouterState.\n * As opposed to a `__DEFAULT__` segment, which means there was no match for that parallel route.\n * We add a special marker here so that we know how to refresh its data when the router is revalidated.\n */\nexport function addRefreshMarkerToActiveParallelSegments(\n tree: FlightRouterState,\n path: string\n) {\n const [segment, parallelRoutes, , refetchMarker] = tree\n // a page segment might also contain concatenated search params, so we do a partial match on the key\n if (segment.includes(PAGE_SEGMENT_KEY) && refetchMarker !== 'refresh') {\n tree[2] = path\n tree[3] = 'refresh'\n }\n\n for (const key in parallelRoutes) {\n addRefreshMarkerToActiveParallelSegments(parallelRoutes[key], path)\n }\n}\n","import type {\n FlightRouterState,\n FlightSegmentPath,\n} from '../../../shared/lib/app-router-types'\nimport { DEFAULT_SEGMENT_KEY } from '../../../shared/lib/segment'\nimport { getNextFlightSegmentPath } from '../../flight-data-helpers'\nimport { matchSegment } from '../match-segments'\nimport { addRefreshMarkerToActiveParallelSegments } from './refetch-inactive-parallel-segments'\n\n/**\n * Deep merge of the two router states. Parallel route keys are preserved if the patch doesn't have them.\n */\nfunction applyPatch(\n initialTree: FlightRouterState,\n patchTree: FlightRouterState\n): FlightRouterState {\n const [initialSegment, initialParallelRoutes] = initialTree\n const [patchSegment, patchParallelRoutes] = patchTree\n\n // if the applied patch segment is __DEFAULT__ then it can be ignored in favor of the initial tree\n // this is because the __DEFAULT__ segment is used as a placeholder on navigation\n if (\n patchSegment === DEFAULT_SEGMENT_KEY &&\n initialSegment !== DEFAULT_SEGMENT_KEY\n ) {\n return initialTree\n }\n\n if (matchSegment(initialSegment, patchSegment)) {\n const newParallelRoutes: FlightRouterState[1] = {}\n for (const key in initialParallelRoutes) {\n const isInPatchTreeParallelRoutes =\n typeof patchParallelRoutes[key] !== 'undefined'\n if (isInPatchTreeParallelRoutes) {\n newParallelRoutes[key] = applyPatch(\n initialParallelRoutes[key],\n patchParallelRoutes[key]\n )\n } else {\n newParallelRoutes[key] = initialParallelRoutes[key]\n }\n }\n\n for (const key in patchParallelRoutes) {\n if (newParallelRoutes[key]) {\n continue\n }\n\n newParallelRoutes[key] = patchParallelRoutes[key]\n }\n\n const tree: FlightRouterState = [initialSegment, newParallelRoutes]\n\n // Copy over the existing tree\n if (initialTree[2]) {\n tree[2] = initialTree[2]\n }\n\n if (initialTree[3]) {\n tree[3] = initialTree[3]\n }\n\n if (initialTree[4]) {\n tree[4] = initialTree[4]\n }\n\n return tree\n }\n\n return patchTree\n}\n\n/**\n * Apply the router state from the Flight response, but skip patching default segments.\n * Useful for patching the router cache when navigating, where we persist the existing default segment if there isn't a new one.\n * Creates a new router state tree.\n */\nexport function applyRouterStatePatchToTree(\n flightSegmentPath: FlightSegmentPath,\n flightRouterState: FlightRouterState,\n treePatch: FlightRouterState,\n path: string\n): FlightRouterState | null {\n const [segment, parallelRoutes, url, refetch, isRootLayout] =\n flightRouterState\n\n // Root refresh\n if (flightSegmentPath.length === 1) {\n const tree: FlightRouterState = applyPatch(flightRouterState, treePatch)\n\n addRefreshMarkerToActiveParallelSegments(tree, path)\n\n return tree\n }\n\n const [currentSegment, parallelRouteKey] = flightSegmentPath\n\n // Tree path returned from the server should always match up with the current tree in the browser\n if (!matchSegment(currentSegment, segment)) {\n return null\n }\n\n const lastSegment = flightSegmentPath.length === 2\n\n let parallelRoutePatch\n if (lastSegment) {\n parallelRoutePatch = applyPatch(parallelRoutes[parallelRouteKey], treePatch)\n } else {\n parallelRoutePatch = applyRouterStatePatchToTree(\n getNextFlightSegmentPath(flightSegmentPath),\n parallelRoutes[parallelRouteKey],\n treePatch,\n path\n )\n\n if (parallelRoutePatch === null) {\n return null\n }\n }\n\n const tree: FlightRouterState = [\n flightSegmentPath[0],\n {\n ...parallelRoutes,\n [parallelRouteKey]: parallelRoutePatch,\n },\n url,\n refetch,\n ]\n\n // Current segment is the root layout\n if (isRootLayout) {\n tree[4] = true\n }\n\n addRefreshMarkerToActiveParallelSegments(tree, path)\n\n return tree\n}\n","import type {\n FlightRouterState,\n FlightDataPath,\n Segment,\n} from '../../../shared/lib/app-router-types'\nimport { getNextFlightSegmentPath } from '../../flight-data-helpers'\nimport { matchSegment } from '../match-segments'\n\n// TODO-APP: flightSegmentPath will be empty in case of static response, needs to be handled.\nexport function shouldHardNavigate(\n flightSegmentPath: FlightDataPath,\n flightRouterState: FlightRouterState\n): boolean {\n const [segment, parallelRoutes] = flightRouterState\n // TODO-APP: Check if `as` can be replaced.\n const [currentSegment, parallelRouteKey] = flightSegmentPath as [\n Segment,\n string,\n ]\n\n // Check if current segment matches the existing segment.\n if (!matchSegment(currentSegment, segment)) {\n // If dynamic parameter in tree doesn't match up with segment path a hard navigation is triggered.\n if (Array.isArray(currentSegment)) {\n return true\n }\n\n // If the existing segment did not match soft navigation is triggered.\n return false\n }\n const lastSegment = flightSegmentPath.length <= 2\n\n if (lastSegment) {\n return false\n }\n\n return shouldHardNavigate(\n getNextFlightSegmentPath(flightSegmentPath),\n parallelRoutes[parallelRouteKey]\n )\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","/**\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 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\nexport function extractInterceptionRouteInformation(path: string) {\n let interceptingRoute: string | undefined,\n marker: (typeof INTERCEPTION_ROUTE_MARKERS)[number] | undefined,\n 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 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 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: isNotUndefined(mutable.canonicalUrl)\n ? mutable.canonicalUrl === state.canonicalUrl\n ? state.canonicalUrl\n : mutable.canonicalUrl\n : state.canonicalUrl,\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 prefetchCache: mutable.prefetchCache\n ? mutable.prefetchCache\n : state.prefetchCache,\n // Apply patched router state.\n tree: isNotUndefined(mutable.patchedTree)\n ? mutable.patchedTree\n : state.tree,\n nextUrl,\n }\n}\n","\"use strict\";\n\nfunction _class_private_field_loose_base(receiver, privateKey) {\n if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {\n throw new TypeError(\"attempted to use private field on non-instance\");\n }\n\n return receiver;\n}\nexports._ = _class_private_field_loose_base;\n","\"use strict\";\n\nvar id = 0;\n\nfunction _class_private_field_loose_key(name) {\n return \"__private_\" + id++ + \"_\" + name;\n}\nexports._ = _class_private_field_loose_key;\n","/*\n This is a simple promise queue that allows you to limit the number of concurrent promises\n that are running at any given time. It's used to limit the number of concurrent\n prefetch requests that are being made to the server but could be used for other\n things as well.\n*/\nexport class PromiseQueue {\n #maxConcurrency: number\n #runningCount: number\n #queue: Array<{\n promiseFn: Promise<any>\n task: () => void\n }>\n\n constructor(maxConcurrency = 5) {\n this.#maxConcurrency = maxConcurrency\n this.#runningCount = 0\n this.#queue = []\n }\n\n enqueue<T>(promiseFn: () => Promise<T>): Promise<T> {\n let taskResolve: (value: T | PromiseLike<T>) => void\n let taskReject: (reason?: any) => void\n\n const taskPromise = new Promise((resolve, reject) => {\n taskResolve = resolve\n taskReject = reject\n }) as Promise<T>\n\n const task = async () => {\n try {\n this.#runningCount++\n const result = await promiseFn()\n taskResolve(result)\n } catch (error) {\n taskReject(error)\n } finally {\n this.#runningCount--\n this.#processNext()\n }\n }\n\n const enqueueResult = { promiseFn: taskPromise, task }\n // wonder if we should take a LIFO approach here\n this.#queue.push(enqueueResult)\n this.#processNext()\n\n return taskPromise\n }\n\n bump(promiseFn: Promise<any>) {\n const index = this.#queue.findIndex((item) => item.promiseFn === promiseFn)\n\n if (index > -1) {\n const bumpedItem = this.#queue.splice(index, 1)[0]\n this.#queue.unshift(bumpedItem)\n this.#processNext(true)\n }\n }\n\n #processNext(forced = false) {\n if (\n (this.#runningCount < this.#maxConcurrency || forced) &&\n this.#queue.length > 0\n ) {\n this.#queue.shift()?.task()\n }\n }\n}\n","import {\n fetchServerResponse,\n type FetchServerResponseResult,\n} from './fetch-server-response'\nimport {\n PrefetchCacheEntryStatus,\n type PrefetchCacheEntry,\n PrefetchKind,\n type ReadonlyReducerState,\n} from './router-reducer-types'\nimport { prefetchQueue } from './reducers/prefetch-reducer'\n\nconst INTERCEPTION_CACHE_KEY_MARKER = '%'\n\nexport type AliasedPrefetchCacheEntry = PrefetchCacheEntry & {\n /** This is a special property that indicates a prefetch entry associated with a different URL\n * was returned rather than the requested URL. This signals to the router that it should only\n * apply the part that doesn't depend on searchParams (specifically the loading state).\n */\n aliased?: boolean\n}\n\n/**\n * Creates a cache key for the router prefetch cache\n *\n * @param url - The URL being navigated to\n * @param nextUrl - an internal URL, primarily used for handling rewrites. Defaults to '/'.\n * @return The generated prefetch cache key.\n */\nfunction createPrefetchCacheKeyImpl(\n url: URL,\n includeSearchParams: boolean,\n prefix?: string | null\n) {\n // Initially we only use the pathname as the cache key. We don't want to include\n // search params so that multiple URLs with the same search parameter can re-use\n // loading states.\n let pathnameFromUrl = url.pathname\n\n // RSC responses can differ based on search params, specifically in the case where we aren't\n // returning a partial response (ie with `PrefetchKind.AUTO`).\n // In the auto case, since loading.js & layout.js won't have access to search params,\n // we can safely re-use that cache entry. But for full prefetches, we should not\n // re-use the cache entry as the response may differ.\n if (includeSearchParams) {\n // if we have a full prefetch, we can include the search param in the key,\n // as we'll be getting back a full response. The server might have read the search\n // params when generating the full response.\n pathnameFromUrl += url.search\n }\n\n if (prefix) {\n return `${prefix}${INTERCEPTION_CACHE_KEY_MARKER}${pathnameFromUrl}`\n }\n\n return pathnameFromUrl\n}\n\nfunction createPrefetchCacheKey(\n url: URL,\n kind: PrefetchKind | undefined,\n nextUrl?: string | null\n) {\n return createPrefetchCacheKeyImpl(url, kind === PrefetchKind.FULL, nextUrl)\n}\n\nfunction getExistingCacheEntry(\n url: URL,\n kind: PrefetchKind = PrefetchKind.TEMPORARY,\n nextUrl: string | null,\n prefetchCache: Map<string, PrefetchCacheEntry>,\n allowAliasing: boolean\n): AliasedPrefetchCacheEntry | undefined {\n // We first check if there's a more specific interception route prefetch entry\n // This is because when we detect a prefetch that corresponds with an interception route, we prefix it with nextUrl (see `createPrefetchCacheKey`)\n // to avoid conflicts with other pages that may have the same URL but render different things depending on the `Next-URL` header.\n for (const maybeNextUrl of [nextUrl, null]) {\n const cacheKeyWithParams = createPrefetchCacheKeyImpl(\n url,\n true,\n maybeNextUrl\n )\n const cacheKeyWithoutParams = createPrefetchCacheKeyImpl(\n url,\n false,\n maybeNextUrl\n )\n\n // First, we check if we have a cache entry that exactly matches the URL\n const cacheKeyToUse = url.search\n ? cacheKeyWithParams\n : cacheKeyWithoutParams\n\n const existingEntry = prefetchCache.get(cacheKeyToUse)\n if (existingEntry && allowAliasing) {\n // We know we're returning an aliased entry when the pathname matches but the search params don't,\n const isAliased =\n existingEntry.url.pathname === url.pathname &&\n existingEntry.url.search !== url.search\n\n if (isAliased) {\n return {\n ...existingEntry,\n aliased: true,\n }\n }\n\n return existingEntry\n }\n\n // If the request contains search params, and we're not doing a full prefetch, we can return the\n // param-less entry if it exists.\n // This is technically covered by the check at the bottom of this function, which iterates over cache entries,\n // but lets us arrive there quicker in the param-full case.\n const entryWithoutParams = prefetchCache.get(cacheKeyWithoutParams)\n if (\n process.env.NODE_ENV !== 'development' &&\n allowAliasing &&\n url.search &&\n kind !== PrefetchKind.FULL &&\n entryWithoutParams &&\n // We shouldn't return the aliased entry if it was relocated to a new cache key.\n // Since it's rewritten, it could respond with a completely different loading state.\n !entryWithoutParams.key.includes(INTERCEPTION_CACHE_KEY_MARKER)\n ) {\n return { ...entryWithoutParams, aliased: true }\n }\n }\n\n // If we've gotten to this point, we didn't find a specific cache entry that matched\n // the request URL.\n // We attempt a partial match by checking if there's a cache entry with the same pathname.\n // Regardless of what we find, since it doesn't correspond with the requested URL, we'll mark it \"aliased\".\n // This will signal to the router that it should only apply the loading state on the prefetched data.\n if (\n process.env.NODE_ENV !== 'development' &&\n kind !== PrefetchKind.FULL &&\n allowAliasing\n ) {\n for (const cacheEntry of prefetchCache.values()) {\n if (\n cacheEntry.url.pathname === url.pathname &&\n // We shouldn't return the aliased entry if it was relocated to a new cache key.\n // Since it's rewritten, it could respond with a completely different loading state.\n !cacheEntry.key.includes(INTERCEPTION_CACHE_KEY_MARKER)\n ) {\n return { ...cacheEntry, aliased: true }\n }\n }\n }\n\n return undefined\n}\n\n/**\n * Returns a prefetch cache entry if one exists. Otherwise creates a new one and enqueues a fetch request\n * to retrieve the prefetch data from the server.\n */\nexport function getOrCreatePrefetchCacheEntry({\n url,\n nextUrl,\n tree,\n prefetchCache,\n kind,\n allowAliasing = true,\n}: Pick<ReadonlyReducerState, 'nextUrl' | 'prefetchCache' | 'tree'> & {\n url: URL\n kind?: PrefetchKind\n allowAliasing: boolean\n}): AliasedPrefetchCacheEntry {\n const existingCacheEntry = getExistingCacheEntry(\n url,\n kind,\n nextUrl,\n prefetchCache,\n allowAliasing\n )\n\n if (existingCacheEntry) {\n // Grab the latest status of the cache entry and update it\n existingCacheEntry.status = getPrefetchEntryCacheStatus(existingCacheEntry)\n\n // when `kind` is provided, an explicit prefetch was requested.\n // if the requested prefetch is \"full\" and the current cache entry wasn't, we want to re-prefetch with the new intent\n const switchedToFullPrefetch =\n existingCacheEntry.kind !== PrefetchKind.FULL &&\n kind === PrefetchKind.FULL\n\n if (switchedToFullPrefetch) {\n // If we switched to a full prefetch, validate that the existing cache entry contained partial data.\n // It's possible that the cache entry was seeded with full data but has a cache type of \"auto\" (ie when cache entries\n // are seeded but without a prefetch intent)\n existingCacheEntry.data.then((prefetchResponse) => {\n const isFullPrefetch =\n Array.isArray(prefetchResponse.flightData) &&\n prefetchResponse.flightData.some((flightData) => {\n // If we started rendering from the root and we returned RSC data (seedData), we already had a full prefetch.\n return flightData.isRootRender && flightData.seedData !== null\n })\n\n if (!isFullPrefetch) {\n return createLazyPrefetchEntry({\n tree,\n url,\n nextUrl,\n prefetchCache,\n // If we didn't get an explicit prefetch kind, we want to set a temporary kind\n // rather than assuming the same intent as the previous entry, to be consistent with how we\n // lazily create prefetch entries when intent is left unspecified.\n kind: kind ?? PrefetchKind.TEMPORARY,\n })\n }\n })\n }\n\n // If the existing cache entry was marked as temporary, it means it was lazily created when attempting to get an entry,\n // where we didn't have the prefetch intent. Now that we have the intent (in `kind`), we want to update the entry to the more accurate kind.\n if (kind && existingCacheEntry.kind === PrefetchKind.TEMPORARY) {\n existingCacheEntry.kind = kind\n }\n\n // We've determined that the existing entry we found is still valid, so we return it.\n return existingCacheEntry\n }\n\n // If we didn't return an entry, create a new one.\n return createLazyPrefetchEntry({\n tree,\n url,\n nextUrl,\n prefetchCache,\n kind: kind || PrefetchKind.TEMPORARY,\n })\n}\n\n/*\n * Used to take an existing cache entry and prefix it with the nextUrl, if it exists.\n * This ensures that we don't have conflicting cache entries for the same URL (as is the case with route interception).\n */\nfunction prefixExistingPrefetchCacheEntry({\n url,\n nextUrl,\n prefetchCache,\n existingCacheKey,\n}: Pick<ReadonlyReducerState, 'nextUrl' | 'prefetchCache'> & {\n url: URL\n existingCacheKey: string\n}) {\n const existingCacheEntry = prefetchCache.get(existingCacheKey)\n if (!existingCacheEntry) {\n // no-op -- there wasn't an entry to move\n return\n }\n\n const newCacheKey = createPrefetchCacheKey(\n url,\n existingCacheEntry.kind,\n nextUrl\n )\n prefetchCache.set(newCacheKey, { ...existingCacheEntry, key: newCacheKey })\n prefetchCache.delete(existingCacheKey)\n\n return newCacheKey\n}\n\n/**\n * Use to seed the prefetch cache with data that has already been fetched.\n */\nexport function createSeededPrefetchCacheEntry({\n nextUrl,\n tree,\n prefetchCache,\n url,\n data,\n kind,\n}: Pick<ReadonlyReducerState, 'nextUrl' | 'tree' | 'prefetchCache'> & {\n url: URL\n data: FetchServerResponseResult\n kind: PrefetchKind\n}) {\n // The initial cache entry technically includes full data, but it isn't explicitly prefetched -- we just seed the\n // prefetch cache so that we can skip an extra prefetch request later, since we already have the data.\n // if the prefetch corresponds with an interception route, we use the nextUrl to prefix the cache key\n const prefetchCacheKey = data.couldBeIntercepted\n ? createPrefetchCacheKey(url, kind, nextUrl)\n : createPrefetchCacheKey(url, kind)\n\n const prefetchEntry = {\n treeAtTimeOfPrefetch: tree,\n data: Promise.resolve(data),\n kind,\n prefetchTime: Date.now(),\n lastUsedTime: Date.now(),\n staleTime: data.staleTime,\n key: prefetchCacheKey,\n status: PrefetchCacheEntryStatus.fresh,\n url,\n } satisfies PrefetchCacheEntry\n\n prefetchCache.set(prefetchCacheKey, prefetchEntry)\n\n return prefetchEntry\n}\n\n/**\n * Creates a prefetch entry entry and enqueues a fetch request to retrieve the data.\n */\nfunction createLazyPrefetchEntry({\n url,\n kind,\n tree,\n nextUrl,\n prefetchCache,\n}: Pick<ReadonlyReducerState, 'nextUrl' | 'tree' | 'prefetchCache'> & {\n url: URL\n kind: PrefetchKind\n}): PrefetchCacheEntry {\n const prefetchCacheKey = createPrefetchCacheKey(url, kind)\n\n // initiates the fetch request for the prefetch and attaches a listener\n // to the promise to update the prefetch cache entry when the promise resolves (if necessary)\n const data = prefetchQueue.enqueue(() =>\n fetchServerResponse(url, {\n flightRouterState: tree,\n nextUrl,\n prefetchKind: kind,\n }).then((prefetchResponse) => {\n // TODO: `fetchServerResponse` should be more tighly coupled to these prefetch cache operations\n // to avoid drift between this cache key prefixing logic\n // (which is currently directly influenced by the server response)\n let newCacheKey\n\n if (prefetchResponse.couldBeIntercepted) {\n // Determine if we need to prefix the cache key with the nextUrl\n newCacheKey = prefixExistingPrefetchCacheEntry({\n url,\n existingCacheKey: prefetchCacheKey,\n nextUrl,\n prefetchCache,\n })\n }\n\n // If the prefetch was a cache hit, we want to update the existing cache entry to reflect that it was a full prefetch.\n // This is because we know that a static response will contain the full RSC payload, and can be updated to respect the `static`\n // staleTime.\n if (prefetchResponse.prerendered) {\n const existingCacheEntry = prefetchCache.get(\n // if we prefixed the cache key due to route interception, we want to use the new key. Otherwise we use the original key\n newCacheKey ?? prefetchCacheKey\n )\n if (existingCacheEntry) {\n existingCacheEntry.kind = PrefetchKind.FULL\n if (prefetchResponse.staleTime !== -1) {\n // This is the stale time that was collected by the server during\n // static generation. Use this in place of the default stale time.\n existingCacheEntry.staleTime = prefetchResponse.staleTime\n }\n }\n }\n\n return prefetchResponse\n })\n )\n\n const prefetchEntry = {\n treeAtTimeOfPrefetch: tree,\n data,\n kind,\n prefetchTime: Date.now(),\n lastUsedTime: null,\n staleTime: -1,\n key: prefetchCacheKey,\n status: PrefetchCacheEntryStatus.fresh,\n url,\n }\n\n prefetchCache.set(prefetchCacheKey, prefetchEntry)\n\n return prefetchEntry\n}\n\nexport function prunePrefetchCache(\n prefetchCache: ReadonlyReducerState['prefetchCache']\n) {\n for (const [href, prefetchCacheEntry] of prefetchCache) {\n if (\n getPrefetchEntryCacheStatus(prefetchCacheEntry) ===\n PrefetchCacheEntryStatus.expired\n ) {\n prefetchCache.delete(href)\n }\n }\n}\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 =\n Number(process.env.__NEXT_CLIENT_ROUTER_STATIC_STALETIME) * 1000\n\nfunction getPrefetchEntryCacheStatus({\n kind,\n prefetchTime,\n lastUsedTime,\n}: PrefetchCacheEntry): PrefetchCacheEntryStatus {\n // We will re-use the cache entry data for up to the `dynamic` staletime window.\n if (Date.now() < (lastUsedTime ?? prefetchTime) + DYNAMIC_STALETIME_MS) {\n return lastUsedTime\n ? PrefetchCacheEntryStatus.reusable\n : PrefetchCacheEntryStatus.fresh\n }\n\n // For \"auto\" prefetching, we'll re-use only the loading boundary for up to `static` staletime window.\n // A stale entry will only re-use the `loading` boundary, not the full data.\n // This will trigger a \"lazy fetch\" for the full data.\n if (kind === PrefetchKind.AUTO) {\n if (Date.now() < prefetchTime + STATIC_STALETIME_MS) {\n return PrefetchCacheEntryStatus.stale\n }\n }\n\n // for \"full\" prefetching, we'll re-use the cache entry data for up to `static` staletime window.\n if (kind === PrefetchKind.FULL) {\n if (Date.now() < prefetchTime + STATIC_STALETIME_MS) {\n return PrefetchCacheEntryStatus.reusable\n }\n }\n\n return PrefetchCacheEntryStatus.expired\n}\n","import type {\n PrefetchAction,\n ReducerState,\n ReadonlyReducerState,\n} from '../router-reducer-types'\nimport { PromiseQueue } from '../../promise-queue'\nimport {\n getOrCreatePrefetchCacheEntry,\n prunePrefetchCache,\n} from '../prefetch-cache-utils'\nexport const prefetchQueue = new PromiseQueue(5)\n\nexport const prefetchReducer = process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? identityReducerWhenSegmentCacheIsEnabled\n : prefetchReducerImpl\n\nfunction identityReducerWhenSegmentCacheIsEnabled<T>(state: T): T {\n // Unlike the old implementation, the Segment Cache doesn't store its data in\n // the router reducer state.\n //\n // This shouldn't be reachable because we wrap the prefetch API in a check,\n // too, which prevents the action from being dispatched. But it's here for\n // clarity + code elimination.\n return state\n}\n\nfunction prefetchReducerImpl(\n state: ReadonlyReducerState,\n action: PrefetchAction\n): ReducerState {\n // let's prune the prefetch cache before we do anything else\n prunePrefetchCache(state.prefetchCache)\n\n const { url } = action\n\n getOrCreatePrefetchCacheEntry({\n url,\n nextUrl: state.nextUrl,\n prefetchCache: state.prefetchCache,\n kind: action.kind,\n tree: state.tree,\n allowAliasing: true,\n })\n\n return state\n}\n","// This regex contains the bots that we need to do a blocking render for and can't safely stream the response\n// due to how they parse the DOM. For example, they might explicitly check for metadata in the `head` tag, so we can't stream metadata tags after the `head` was sent.\n// Note: The pattern [\\w-]+-Google captures all Google crawlers with \"-Google\" suffix (e.g., Mediapartners-Google, AdsBot-Google, Storebot-Google)\n// as well as crawlers starting with \"Google-\" (e.g., Google-PageRenderer, Google-InspectionTool)\nexport const HTML_LIMITED_BOT_UA_RE =\n /[\\w-]+-Google|Google-[\\w-]+|Chrome-Lighthouse|Slurp|DuckDuckBot|baiduspider|yandex|sogou|bitlybot|tumblr|vkShare|quora link preview|redditbot|ia_archiver|Bingbot|BingPreview|applebot|facebookexternalhit|facebookcatalog|Twitterbot|LinkedInBot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|Yeti|googleweblight/i\n","import { HTML_LIMITED_BOT_UA_RE } from './html-bots'\n\n// Bot crawler that will spin up a headless browser and execute JS.\n// Only the main Googlebot search crawler executes JavaScript, not other Google crawlers.\n// x-ref: https://developers.google.com/search/docs/crawling-indexing/google-common-crawlers\n// This regex specifically matches \"Googlebot\" but NOT \"Mediapartners-Google\", \"AdsBot-Google\", etc.\nconst HEADLESS_BROWSER_BOT_UA_RE = /Googlebot(?!-)|Googlebot$/i\n\nexport const HTML_LIMITED_BOT_UA_RE_STRING = HTML_LIMITED_BOT_UA_RE.source\n\nexport { HTML_LIMITED_BOT_UA_RE }\n\nfunction isDomBotUA(userAgent: string) {\n return HEADLESS_BROWSER_BOT_UA_RE.test(userAgent)\n}\n\nfunction isHtmlLimitedBotUA(userAgent: string) {\n return HTML_LIMITED_BOT_UA_RE.test(userAgent)\n}\n\nexport function isBot(userAgent: string): boolean {\n return isDomBotUA(userAgent) || isHtmlLimitedBotUA(userAgent)\n}\n\nexport function getBotType(userAgent: string): 'dom' | 'html' | undefined {\n if (isDomBotUA(userAgent)) {\n return 'dom'\n }\n if (isHtmlLimitedBotUA(userAgent)) {\n return 'html'\n }\n return undefined\n}\n","import { useEffect, useRef, useState } from 'react'\nimport { createPortal } from 'react-dom'\nimport type { FlightRouterState } from '../../shared/lib/app-router-types'\n\nconst ANNOUNCER_TYPE = 'next-route-announcer'\nconst ANNOUNCER_ID = '__next-route-announcer__'\n\nfunction getAnnouncerNode() {\n const existingAnnouncer = document.getElementsByName(ANNOUNCER_TYPE)[0]\n if (existingAnnouncer?.shadowRoot?.childNodes[0]) {\n return existingAnnouncer.shadowRoot.childNodes[0] as HTMLElement\n } else {\n const container = document.createElement(ANNOUNCER_TYPE)\n container.style.cssText = 'position:absolute'\n const announcer = document.createElement('div')\n announcer.ariaLive = 'assertive'\n announcer.id = ANNOUNCER_ID\n announcer.role = 'alert'\n announcer.style.cssText =\n 'position:absolute;border:0;height:1px;margin:-1px;padding:0;width:1px;clip:rect(0 0 0 0);overflow:hidden;white-space:nowrap;word-wrap:normal'\n\n // Use shadow DOM here to avoid any potential CSS bleed\n const shadow = container.attachShadow({ mode: 'open' })\n shadow.appendChild(announcer)\n document.body.appendChild(container)\n return announcer\n }\n}\n\nexport function AppRouterAnnouncer({ tree }: { tree: FlightRouterState }) {\n const [portalNode, setPortalNode] = useState<HTMLElement | null>(null)\n\n useEffect(() => {\n const announcer = getAnnouncerNode()\n setPortalNode(announcer)\n return () => {\n const container = document.getElementsByTagName(ANNOUNCER_TYPE)[0]\n if (container?.isConnected) {\n document.body.removeChild(container)\n }\n }\n }, [])\n\n const [routeAnnouncement, setRouteAnnouncement] = useState('')\n const previousTitle = useRef<string | undefined>(undefined)\n\n useEffect(() => {\n let currentTitle = ''\n if (document.title) {\n currentTitle = document.title\n } else {\n const pageHeader = document.querySelector('h1')\n if (pageHeader) {\n currentTitle = pageHeader.innerText || pageHeader.textContent || ''\n }\n }\n\n // Only announce the title change, but not for the first load because screen\n // readers do that automatically.\n if (\n previousTitle.current !== undefined &&\n previousTitle.current !== currentTitle\n ) {\n setRouteAnnouncement(currentTitle)\n }\n previousTitle.current = currentTitle\n }, [tree])\n\n return portalNode ? createPortal(routeAnnouncement, portalNode) : null\n}\n","'use client'\nimport React, { useEffect } from 'react'\nimport type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime'\nimport { useRouter } from './navigation'\nimport { getRedirectTypeFromError, getURLFromRedirectError } from './redirect'\nimport { RedirectType, isRedirectError } from './redirect-error'\n\ninterface RedirectBoundaryProps {\n router: AppRouterInstance\n children: React.ReactNode\n}\n\nfunction HandleRedirect({\n redirect,\n reset,\n redirectType,\n}: {\n redirect: string\n redirectType: RedirectType\n reset: () => void\n}) {\n const router = useRouter()\n\n useEffect(() => {\n React.startTransition(() => {\n if (redirectType === RedirectType.push) {\n router.push(redirect, {})\n } else {\n router.replace(redirect, {})\n }\n reset()\n })\n }, [redirect, redirectType, reset, router])\n\n return null\n}\n\nexport class RedirectErrorBoundary extends React.Component<\n RedirectBoundaryProps,\n { redirect: string | null; redirectType: RedirectType | null }\n> {\n constructor(props: RedirectBoundaryProps) {\n super(props)\n this.state = { redirect: null, redirectType: null }\n }\n\n static getDerivedStateFromError(error: any) {\n if (isRedirectError(error)) {\n const url = getURLFromRedirectError(error)\n const redirectType = getRedirectTypeFromError(error)\n return { redirect: url, redirectType }\n }\n // Re-throw if error is not for redirect\n throw error\n }\n\n // Explicit type is needed to avoid the generated `.d.ts` having a wide return type that could be specific to the `@types/react` version.\n render(): React.ReactNode {\n const { redirect, redirectType } = this.state\n if (redirect !== null && redirectType !== null) {\n return (\n <HandleRedirect\n redirect={redirect}\n redirectType={redirectType}\n reset={() => this.setState({ redirect: null })}\n />\n )\n }\n\n return this.props.children\n }\n}\n\nexport function RedirectBoundary({ children }: { children: React.ReactNode }) {\n const router = useRouter()\n return (\n <RedirectErrorBoundary router={router}>{children}</RedirectErrorBoundary>\n )\n}\n","import type {\n FlightRouterState,\n CacheNode,\n} from '../../../../shared/lib/app-router-types'\nimport { DEFAULT_SEGMENT_KEY } from '../../../../shared/lib/segment'\nimport { createRouterCacheKey } from '../create-router-cache-key'\n\nexport function findHeadInCache(\n cache: CacheNode,\n parallelRoutes: FlightRouterState[1]\n): [CacheNode, string, string] | null {\n return findHeadInCacheImpl(cache, parallelRoutes, '', '')\n}\n\nfunction findHeadInCacheImpl(\n cache: CacheNode,\n parallelRoutes: FlightRouterState[1],\n keyPrefix: string,\n keyPrefixWithoutSearchParams: string\n): [CacheNode, string, string] | null {\n const isLastItem = Object.keys(parallelRoutes).length === 0\n if (isLastItem) {\n // Returns the entire Cache Node of the segment whose head we will render.\n return [cache, keyPrefix, keyPrefixWithoutSearchParams]\n }\n\n // First try the 'children' parallel route if it exists\n // when starting from the \"root\", this corresponds with the main page component\n const parallelRoutesKeys = Object.keys(parallelRoutes).filter(\n (key) => key !== 'children'\n )\n\n // if we are at the root, we need to check the children slot first\n if ('children' in parallelRoutes) {\n parallelRoutesKeys.unshift('children')\n }\n\n for (const key of parallelRoutesKeys) {\n const [segment, childParallelRoutes] = parallelRoutes[key]\n // If the parallel is not matched and using the default segment,\n // skip searching the head from it.\n if (segment === DEFAULT_SEGMENT_KEY) {\n continue\n }\n const childSegmentMap = cache.parallelRoutes.get(key)\n if (!childSegmentMap) {\n continue\n }\n\n const cacheKey = createRouterCacheKey(segment)\n const cacheKeyWithoutSearchParams = createRouterCacheKey(segment, true)\n\n const cacheNode = childSegmentMap.get(cacheKey)\n if (!cacheNode) {\n continue\n }\n\n const item = findHeadInCacheImpl(\n cacheNode,\n childParallelRoutes,\n keyPrefix + '/' + cacheKey,\n keyPrefix + '/' + cacheKeyWithoutSearchParams\n )\n\n if (item) {\n return item\n }\n }\n\n return null\n}\n","/**\n * Create a \"Thenable\" that does not resolve. This is used to suspend indefinitely when data is not available yet.\n */\nexport const unresolvedThenable = {\n then: () => {},\n} as PromiseLike<void>\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 { hasBasePath } from './has-base-path'\n\nconst basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''\n\nexport function removeBasePath(path: string): string {\n if (process.env.__NEXT_MANUAL_CLIENT_BASE_PATH) {\n if (!hasBasePath(path)) {\n return path\n }\n }\n\n // Can't trim the basePath if it has zero length!\n if (basePath.length === 0) return path\n\n path = path.slice(basePath.length)\n if (!path.startsWith('/')) path = `/${path}`\n return path\n}\n","import { useEffect } from 'react'\nimport { createHrefFromUrl } from './router-reducer/create-href-from-url'\n\nexport function handleHardNavError(error: unknown): boolean {\n if (\n error &&\n typeof window !== 'undefined' &&\n window.next.__pendingUrl &&\n createHrefFromUrl(new URL(window.location.href)) !==\n createHrefFromUrl(window.next.__pendingUrl)\n ) {\n console.error(\n `Error occurred during navigation, falling back to hard navigation`,\n error\n )\n window.location.href = window.next.__pendingUrl.toString()\n return true\n }\n return false\n}\n\nexport function useNavFailureHandler() {\n if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {\n // this if is only for DCE of the feature flag not conditional\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useEffect(() => {\n const uncaughtExceptionHandler = (\n evt: ErrorEvent | PromiseRejectionEvent\n ) => {\n const error = 'reason' in evt ? evt.reason : evt.error\n // if we have an unhandled exception/rejection during\n // a navigation we fall back to a hard navigation to\n // attempt recovering to a good state\n handleHardNavError(error)\n }\n window.addEventListener('unhandledrejection', uncaughtExceptionHandler)\n window.addEventListener('error', uncaughtExceptionHandler)\n return () => {\n window.removeEventListener('error', uncaughtExceptionHandler)\n window.removeEventListener(\n 'unhandledrejection',\n uncaughtExceptionHandler\n )\n }\n }, [])\n }\n}\n","'use client'\n\nimport { Component, createRef, type ReactNode } from 'react'\n\ninterface ErrorBoundaryProps {\n children: ReactNode\n}\n\ninterface ErrorBoundaryState {\n hasError: boolean\n}\n\nfunction getDomNodeAttributes(node: HTMLElement): Record<string, string> {\n const result: Record<string, string> = {}\n for (let i = 0; i < node.attributes.length; i++) {\n const attr = node.attributes[i]\n result[attr.name] = attr.value\n }\n return result\n}\n\nexport class GracefulDegradeBoundary extends Component<\n ErrorBoundaryProps,\n ErrorBoundaryState\n> {\n private rootHtml: string\n private htmlAttributes: Record<string, string>\n private htmlRef: React.RefObject<HTMLHtmlElement | null>\n\n constructor(props: ErrorBoundaryProps) {\n super(props)\n this.state = { hasError: false }\n this.rootHtml = ''\n this.htmlAttributes = {}\n this.htmlRef = createRef<HTMLHtmlElement>()\n }\n\n static getDerivedStateFromError(_: unknown): ErrorBoundaryState {\n return { hasError: true }\n }\n\n componentDidMount() {\n const htmlNode = this.htmlRef.current\n if (this.state.hasError && htmlNode) {\n // Reapply the cached HTML attributes to the root element\n Object.entries(this.htmlAttributes).forEach(([key, value]) => {\n htmlNode.setAttribute(key, value)\n })\n }\n }\n\n render() {\n const { hasError } = this.state\n // Cache the root HTML content on the first render\n if (typeof window !== 'undefined' && !this.rootHtml) {\n this.rootHtml = document.documentElement.innerHTML\n this.htmlAttributes = getDomNodeAttributes(document.documentElement)\n }\n\n if (hasError) {\n // Render the current HTML content without hydration\n return (\n <html\n ref={this.htmlRef}\n suppressHydrationWarning\n dangerouslySetInnerHTML={{\n __html: this.rootHtml,\n }}\n />\n )\n }\n\n return this.props.children\n }\n}\n\nexport default GracefulDegradeBoundary\n","import { useContext } from 'react'\nimport { PathnameContext } from '../../shared/lib/hooks-client-context.shared-runtime'\n\n/**\n * This checks to see if the current render has any unknown route parameters that\n * would cause the pathname to be dynamic. It's used to trigger a different\n * render path in the error boundary.\n *\n * @returns true if there are any unknown route parameters, false otherwise\n */\nfunction hasFallbackRouteParams(): boolean {\n if (typeof window === 'undefined') {\n // AsyncLocalStorage should not be included in the client bundle.\n const { workUnitAsyncStorage } =\n require('../../server/app-render/work-unit-async-storage.external') as typeof import('../../server/app-render/work-unit-async-storage.external')\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!workUnitStore) return false\n\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n const fallbackParams = workUnitStore.fallbackRouteParams\n return fallbackParams ? fallbackParams.size > 0 : false\n case 'prerender-legacy':\n case 'request':\n case 'prerender-runtime':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n break\n default:\n workUnitStore satisfies never\n }\n\n return false\n }\n\n return false\n}\n\n/**\n * This returns a `null` value if there are any unknown route parameters, and\n * otherwise returns the pathname from the context. This is an alternative to\n * `usePathname` that is used in the error boundary to avoid rendering the\n * error boundary when there are unknown route parameters. This doesn't throw\n * when accessed with unknown route parameters.\n *\n * @returns\n *\n * @internal\n */\nexport function useUntrackedPathname(): string | null {\n // If there are any unknown route parameters we would typically throw\n // an error, but this internal method allows us to return a null value instead\n // for components that do not propagate the pathname to the static shell (like\n // the error boundary).\n if (hasFallbackRouteParams()) {\n return null\n }\n\n // This shouldn't cause any issues related to conditional rendering because\n // the environment will be consistent for the render.\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return useContext(PathnameContext)\n}\n","'use client'\n\nimport React, { type JSX } from 'react'\nimport { useUntrackedPathname } from './navigation-untracked'\nimport { isNextRouterError } from './is-next-router-error'\nimport { handleHardNavError } from './nav-failure-handler'\nimport { HandleISRError } from './handle-isr-error'\nimport { isBot } from '../../shared/lib/router/utils/is-bot'\n\nconst isBotUserAgent =\n typeof window !== 'undefined' && isBot(window.navigator.userAgent)\n\nexport type ErrorComponent = React.ComponentType<{\n error: Error\n // global-error, there's no `reset` function;\n // regular error boundary, there's a `reset` function.\n reset?: () => void\n}>\n\nexport interface ErrorBoundaryProps {\n children?: React.ReactNode\n errorComponent: ErrorComponent | undefined\n errorStyles?: React.ReactNode | undefined\n errorScripts?: React.ReactNode | undefined\n}\n\ninterface ErrorBoundaryHandlerProps extends ErrorBoundaryProps {\n pathname: string | null\n errorComponent: ErrorComponent\n}\n\ninterface ErrorBoundaryHandlerState {\n error: Error | null\n previousPathname: string | null\n}\n\nexport class ErrorBoundaryHandler extends React.Component<\n ErrorBoundaryHandlerProps,\n ErrorBoundaryHandlerState\n> {\n constructor(props: ErrorBoundaryHandlerProps) {\n super(props)\n this.state = { error: null, previousPathname: this.props.pathname }\n }\n\n static getDerivedStateFromError(error: Error) {\n if (isNextRouterError(error)) {\n // Re-throw if an expected internal Next.js router error occurs\n // this means it should be handled by a different boundary (such as a NotFound boundary in a parent segment)\n throw error\n }\n\n return { error }\n }\n\n static getDerivedStateFromProps(\n props: ErrorBoundaryHandlerProps,\n state: ErrorBoundaryHandlerState\n ): ErrorBoundaryHandlerState | null {\n const { error } = state\n\n // if we encounter an error while\n // a navigation is pending we shouldn't render\n // the error boundary and instead should fallback\n // to a hard navigation to attempt recovering\n if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {\n if (error && handleHardNavError(error)) {\n // clear error so we don't render anything\n return {\n error: null,\n previousPathname: props.pathname,\n }\n }\n }\n\n /**\n * Handles reset of the error boundary when a navigation happens.\n * Ensures the error boundary does not stay enabled when navigating to a new page.\n * Approach of setState in render is safe as it checks the previous pathname and then overrides\n * it as outlined in https://react.dev/reference/react/useState#storing-information-from-previous-renders\n */\n if (props.pathname !== state.previousPathname && state.error) {\n return {\n error: null,\n previousPathname: props.pathname,\n }\n }\n return {\n error: state.error,\n previousPathname: props.pathname,\n }\n }\n\n reset = () => {\n this.setState({ error: null })\n }\n\n // Explicit type is needed to avoid the generated `.d.ts` having a wide return type that could be specific to the `@types/react` version.\n render(): React.ReactNode {\n //When it's bot request, segment level error boundary will keep rendering the children,\n // the final error will be caught by the root error boundary and determine wether need to apply graceful degrade.\n if (this.state.error && !isBotUserAgent) {\n return (\n <>\n <HandleISRError error={this.state.error} />\n {this.props.errorStyles}\n {this.props.errorScripts}\n <this.props.errorComponent\n error={this.state.error}\n reset={this.reset}\n />\n </>\n )\n }\n\n return this.props.children\n }\n}\n\n/**\n * Handles errors through `getDerivedStateFromError`.\n * Renders the provided error component and provides a way to `reset` the error boundary state.\n */\n\n/**\n * Renders error boundary with the provided \"errorComponent\" property as the fallback.\n * If no \"errorComponent\" property is provided it renders the children without an error boundary.\n */\nexport function ErrorBoundary({\n errorComponent,\n errorStyles,\n errorScripts,\n children,\n}: ErrorBoundaryProps & {\n children: React.ReactNode\n}): JSX.Element {\n // When we're rendering the missing params shell, this will return null. This\n // is because we won't be rendering any not found boundaries or error\n // boundaries for the missing params shell. When this runs on the client\n // (where these errors can occur), we will get the correct pathname.\n const pathname = useUntrackedPathname()\n if (errorComponent) {\n return (\n <ErrorBoundaryHandler\n pathname={pathname}\n errorComponent={errorComponent}\n errorStyles={errorStyles}\n errorScripts={errorScripts}\n >\n {children}\n </ErrorBoundaryHandler>\n )\n }\n\n return <>{children}</>\n}\n","'use client'\n\nimport React, { type JSX } from 'react'\nimport GracefulDegradeBoundary from './graceful-degrade-boundary'\nimport { ErrorBoundary, type ErrorBoundaryProps } from '../error-boundary'\nimport { isBot } from '../../../shared/lib/router/utils/is-bot'\n\nconst isBotUserAgent =\n typeof window !== 'undefined' && isBot(window.navigator.userAgent)\n\nexport default function RootErrorBoundary({\n children,\n errorComponent,\n errorStyles,\n errorScripts,\n}: ErrorBoundaryProps & { children: React.ReactNode }): JSX.Element {\n if (isBotUserAgent) {\n // Preserve existing DOM/HTML for bots to avoid replacing content with an error UI\n // and to keep the original SSR output intact.\n return <GracefulDegradeBoundary>{children}</GracefulDegradeBoundary>\n }\n\n return (\n <ErrorBoundary\n errorComponent={errorComponent}\n errorStyles={errorStyles}\n errorScripts={errorScripts}\n >\n {children}\n </ErrorBoundary>\n )\n}\n","'use client'\n\nimport type { ReactNode } from 'react'\nimport {\n METADATA_BOUNDARY_NAME,\n VIEWPORT_BOUNDARY_NAME,\n OUTLET_BOUNDARY_NAME,\n ROOT_LAYOUT_BOUNDARY_NAME,\n} from './boundary-constants'\n\n// We use a namespace object to allow us to recover the name of the function\n// at runtime even when production bundling/minification is used.\nconst NameSpace = {\n [METADATA_BOUNDARY_NAME]: function ({ children }: { children: ReactNode }) {\n return children\n },\n [VIEWPORT_BOUNDARY_NAME]: function ({ children }: { children: ReactNode }) {\n return children\n },\n [OUTLET_BOUNDARY_NAME]: function ({ children }: { children: ReactNode }) {\n return children\n },\n [ROOT_LAYOUT_BOUNDARY_NAME]: function ({\n children,\n }: {\n children: ReactNode\n }) {\n return children\n },\n}\n\nexport const MetadataBoundary =\n // We use slice(0) to trick the bundler into not inlining/minifying the function\n // so it retains the name inferred from the namespace object\n NameSpace[METADATA_BOUNDARY_NAME.slice(0) as typeof METADATA_BOUNDARY_NAME]\n\nexport const ViewportBoundary =\n // We use slice(0) to trick the bundler into not inlining/minifying the function\n // so it retains the name inferred from the namespace object\n NameSpace[VIEWPORT_BOUNDARY_NAME.slice(0) as typeof VIEWPORT_BOUNDARY_NAME]\n\nexport const OutletBoundary =\n // We use slice(0) to trick the bundler into not inlining/minifying the function\n // so it retains the name inferred from the namespace object\n NameSpace[OUTLET_BOUNDARY_NAME.slice(0) as typeof OUTLET_BOUNDARY_NAME]\n\nexport const RootLayoutBoundary =\n // We use slice(0) to trick the bundler into not inlining/minifying the function\n // so it retains the name inferred from the namespace object\n NameSpace[\n ROOT_LAYOUT_BOUNDARY_NAME.slice(0) as typeof ROOT_LAYOUT_BOUNDARY_NAME\n ]\n","'use client'\n\nimport React, {\n useEffect,\n useMemo,\n startTransition,\n useInsertionEffect,\n useDeferredValue,\n} from 'react'\nimport {\n AppRouterContext,\n LayoutRouterContext,\n GlobalLayoutRouterContext,\n} from '../../shared/lib/app-router-context.shared-runtime'\nimport type {\n CacheNode,\n FlightRouterState,\n} from '../../shared/lib/app-router-types'\nimport { ACTION_RESTORE } from './router-reducer/router-reducer-types'\nimport type { AppRouterState } from './router-reducer/router-reducer-types'\nimport { createHrefFromUrl } from './router-reducer/create-href-from-url'\nimport {\n SearchParamsContext,\n PathnameContext,\n PathParamsContext,\n} from '../../shared/lib/hooks-client-context.shared-runtime'\nimport { dispatchAppRouterAction, useActionQueue } from './use-action-queue'\nimport { isBot } from '../../shared/lib/router/utils/is-bot'\nimport { addBasePath } from '../add-base-path'\nimport { AppRouterAnnouncer } from './app-router-announcer'\nimport { RedirectBoundary } from './redirect-boundary'\nimport { findHeadInCache } from './router-reducer/reducers/find-head-in-cache'\nimport { unresolvedThenable } from './unresolved-thenable'\nimport { removeBasePath } from '../remove-base-path'\nimport { hasBasePath } from '../has-base-path'\nimport { getSelectedParams } from './router-reducer/compute-changed-path'\nimport { useNavFailureHandler } from './nav-failure-handler'\nimport {\n dispatchTraverseAction,\n publicAppRouterInstance,\n type AppRouterActionQueue,\n type GlobalErrorState,\n} from './app-router-instance'\nimport { getRedirectTypeFromError, getURLFromRedirectError } from './redirect'\nimport { isRedirectError, RedirectType } from './redirect-error'\nimport { pingVisibleLinks } from './links'\nimport RootErrorBoundary from './errors/root-error-boundary'\nimport DefaultGlobalError from './builtin/global-error'\nimport { RootLayoutBoundary } from '../../lib/framework/boundary-components'\nimport type { StaticIndicatorState } from '../dev/hot-reloader/app/hot-reloader-app'\n\nconst globalMutable: {\n pendingMpaPath?: string\n} = {}\n\nexport function isExternalURL(url: URL) {\n return url.origin !== window.location.origin\n}\n\n/**\n * Given a link href, constructs the URL that should be prefetched. Returns null\n * in cases where prefetching should be disabled, like external URLs, or\n * during development.\n * @param href The href passed to <Link>, router.prefetch(), or similar\n * @returns A URL object to prefetch, or null if prefetching should be disabled\n */\nexport function createPrefetchURL(href: string): URL | null {\n // Don't prefetch for bots as they don't navigate.\n if (isBot(window.navigator.userAgent)) {\n return null\n }\n\n let url: URL\n try {\n url = new URL(addBasePath(href), window.location.href)\n } catch (_) {\n // TODO: Does this need to throw or can we just console.error instead? Does\n // anyone rely on this throwing? (Seems unlikely.)\n throw new Error(\n `Cannot prefetch '${href}' because it cannot be converted to a URL.`\n )\n }\n\n // Don't prefetch during development (improves compilation performance)\n if (process.env.NODE_ENV === 'development') {\n return null\n }\n\n // External urls can't be prefetched in the same way.\n if (isExternalURL(url)) {\n return null\n }\n\n return url\n}\n\nfunction HistoryUpdater({\n appRouterState,\n}: {\n appRouterState: AppRouterState\n}) {\n useInsertionEffect(() => {\n if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {\n // clear pending URL as navigation is no longer\n // in flight\n window.next.__pendingUrl = undefined\n }\n\n const { tree, pushRef, canonicalUrl } = appRouterState\n const historyState = {\n ...(pushRef.preserveCustomHistoryState ? window.history.state : {}),\n // Identifier is shortened intentionally.\n // __NA is used to identify if the history entry can be handled by the app-router.\n // __N is used to identify if the history entry can be handled by the old router.\n __NA: true,\n __PRIVATE_NEXTJS_INTERNALS_TREE: tree,\n }\n if (\n pushRef.pendingPush &&\n // Skip pushing an additional history entry if the canonicalUrl is the same as the current url.\n // This mirrors the browser behavior for normal navigation.\n createHrefFromUrl(new URL(window.location.href)) !== canonicalUrl\n ) {\n // This intentionally mutates React state, pushRef is overwritten to ensure additional push/replace calls do not trigger an additional history entry.\n pushRef.pendingPush = false\n window.history.pushState(historyState, '', canonicalUrl)\n } else {\n window.history.replaceState(historyState, '', canonicalUrl)\n }\n }, [appRouterState])\n\n useEffect(() => {\n // The Next-Url and the base tree may affect the result of a prefetch\n // task. Re-prefetch all visible links with the updated values. In most\n // cases, this will not result in any new network requests, only if\n // the prefetch result actually varies on one of these inputs.\n if (process.env.__NEXT_CLIENT_SEGMENT_CACHE) {\n pingVisibleLinks(appRouterState.nextUrl, appRouterState.tree)\n }\n }, [appRouterState.nextUrl, appRouterState.tree])\n\n return null\n}\n\nexport function createEmptyCacheNode(): CacheNode {\n return {\n lazyData: null,\n rsc: null,\n prefetchRsc: null,\n head: null,\n prefetchHead: null,\n parallelRoutes: new Map(),\n loading: null,\n navigatedAt: -1,\n }\n}\n\nfunction copyNextJsInternalHistoryState(data: any) {\n if (data == null) data = {}\n const currentState = window.history.state\n const __NA = currentState?.__NA\n if (__NA) {\n data.__NA = __NA\n }\n const __PRIVATE_NEXTJS_INTERNALS_TREE =\n currentState?.__PRIVATE_NEXTJS_INTERNALS_TREE\n if (__PRIVATE_NEXTJS_INTERNALS_TREE) {\n data.__PRIVATE_NEXTJS_INTERNALS_TREE = __PRIVATE_NEXTJS_INTERNALS_TREE\n }\n\n return data\n}\n\nfunction Head({\n headCacheNode,\n}: {\n headCacheNode: CacheNode | null\n}): React.ReactNode {\n // If this segment has a `prefetchHead`, it's the statically prefetched data.\n // We should use that on initial render instead of `head`. Then we'll switch\n // to `head` when the dynamic response streams in.\n const head = headCacheNode !== null ? headCacheNode.head : null\n const prefetchHead =\n headCacheNode !== null ? headCacheNode.prefetchHead : null\n\n // If no prefetch data is available, then we go straight to rendering `head`.\n const resolvedPrefetchRsc = prefetchHead !== null ? prefetchHead : head\n\n // We use `useDeferredValue` to handle switching between the prefetched and\n // final values. The second argument is returned on initial render, then it\n // re-renders with the first argument.\n return useDeferredValue(head, resolvedPrefetchRsc)\n}\n\n/**\n * The global router that wraps the application components.\n */\nfunction Router({\n actionQueue,\n globalError,\n webSocket,\n staticIndicatorState,\n}: {\n actionQueue: AppRouterActionQueue\n globalError: GlobalErrorState\n webSocket: WebSocket | undefined\n staticIndicatorState: StaticIndicatorState | undefined\n}) {\n const state = useActionQueue(actionQueue)\n const { canonicalUrl } = state\n // Add memoized pathname/query for useSearchParams and usePathname.\n const { searchParams, pathname } = useMemo(() => {\n const url = new URL(\n canonicalUrl,\n typeof window === 'undefined' ? 'http://n' : window.location.href\n )\n\n return {\n // This is turned into a readonly class in `useSearchParams`\n searchParams: url.searchParams,\n pathname: hasBasePath(url.pathname)\n ? removeBasePath(url.pathname)\n : url.pathname,\n }\n }, [canonicalUrl])\n\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const { cache, prefetchCache, tree } = state\n\n // This hook is in a conditional but that is ok because `process.env.NODE_ENV` never changes\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useEffect(() => {\n // Add `window.nd` for debugging purposes.\n // This is not meant for use in applications as concurrent rendering will affect the cache/tree/router.\n // @ts-ignore this is for debugging\n window.nd = {\n router: publicAppRouterInstance,\n cache,\n prefetchCache,\n tree,\n }\n }, [cache, prefetchCache, tree])\n }\n\n useEffect(() => {\n // If the app is restored from bfcache, it's possible that\n // pushRef.mpaNavigation is true, which would mean that any re-render of this component\n // would trigger the mpa navigation logic again from the lines below.\n // This will restore the router to the initial state in the event that the app is restored from bfcache.\n function handlePageShow(event: PageTransitionEvent) {\n if (\n !event.persisted ||\n !window.history.state?.__PRIVATE_NEXTJS_INTERNALS_TREE\n ) {\n return\n }\n\n // Clear the pendingMpaPath value so that a subsequent MPA navigation to the same URL can be triggered.\n // This is necessary because if the browser restored from bfcache, the pendingMpaPath would still be set to the value\n // of the last MPA navigation.\n globalMutable.pendingMpaPath = undefined\n\n dispatchAppRouterAction({\n type: ACTION_RESTORE,\n url: new URL(window.location.href),\n tree: window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE,\n })\n }\n\n window.addEventListener('pageshow', handlePageShow)\n\n return () => {\n window.removeEventListener('pageshow', handlePageShow)\n }\n }, [])\n\n useEffect(() => {\n // Ensure that any redirect errors that bubble up outside of the RedirectBoundary\n // are caught and handled by the router.\n function handleUnhandledRedirect(\n event: ErrorEvent | PromiseRejectionEvent\n ) {\n const error = 'reason' in event ? event.reason : event.error\n if (isRedirectError(error)) {\n event.preventDefault()\n const url = getURLFromRedirectError(error)\n const redirectType = getRedirectTypeFromError(error)\n // TODO: This should access the router methods directly, rather than\n // go through the public interface.\n if (redirectType === RedirectType.push) {\n publicAppRouterInstance.push(url, {})\n } else {\n publicAppRouterInstance.replace(url, {})\n }\n }\n }\n window.addEventListener('error', handleUnhandledRedirect)\n window.addEventListener('unhandledrejection', handleUnhandledRedirect)\n\n return () => {\n window.removeEventListener('error', handleUnhandledRedirect)\n window.removeEventListener('unhandledrejection', handleUnhandledRedirect)\n }\n }, [])\n\n // When mpaNavigation flag is set do a hard navigation to the new url.\n // Infinitely suspend because we don't actually want to rerender any child\n // components with the new URL and any entangled state updates shouldn't\n // commit either (eg: useTransition isPending should stay true until the page\n // unloads).\n //\n // This is a side effect in render. Don't try this at home, kids. It's\n // probably safe because we know this is a singleton component and it's never\n // in <Offscreen>. At least I hope so. (It will run twice in dev strict mode,\n // but that's... fine?)\n const { pushRef } = state\n if (pushRef.mpaNavigation) {\n // if there's a re-render, we don't want to trigger another redirect if one is already in flight to the same URL\n if (globalMutable.pendingMpaPath !== canonicalUrl) {\n const location = window.location\n if (pushRef.pendingPush) {\n location.assign(canonicalUrl)\n } else {\n location.replace(canonicalUrl)\n }\n\n globalMutable.pendingMpaPath = canonicalUrl\n }\n // TODO-APP: Should we listen to navigateerror here to catch failed\n // navigations somehow? And should we call window.stop() if a SPA navigation\n // should interrupt an MPA one?\n // NOTE: This is intentionally using `throw` instead of `use` because we're\n // inside an externally mutable condition (pushRef.mpaNavigation), which\n // violates the rules of hooks.\n throw unresolvedThenable\n }\n\n useEffect(() => {\n const originalPushState = window.history.pushState.bind(window.history)\n const originalReplaceState = window.history.replaceState.bind(\n window.history\n )\n\n // Ensure the canonical URL in the Next.js Router is updated when the URL is changed so that `usePathname` and `useSearchParams` hold the pushed values.\n const applyUrlFromHistoryPushReplace = (\n url: string | URL | null | undefined\n ) => {\n const href = window.location.href\n const tree: FlightRouterState | undefined =\n window.history.state?.__PRIVATE_NEXTJS_INTERNALS_TREE\n\n startTransition(() => {\n dispatchAppRouterAction({\n type: ACTION_RESTORE,\n url: new URL(url ?? href, href),\n tree,\n })\n })\n }\n\n /**\n * Patch pushState to ensure external changes to the history are reflected in the Next.js Router.\n * Ensures Next.js internal history state is copied to the new history entry.\n * Ensures usePathname and useSearchParams hold the newly provided url.\n */\n window.history.pushState = function pushState(\n data: any,\n _unused: string,\n url?: string | URL | null\n ): void {\n // Avoid a loop when Next.js internals trigger pushState/replaceState\n if (data?.__NA || data?._N) {\n return originalPushState(data, _unused, url)\n }\n\n data = copyNextJsInternalHistoryState(data)\n\n if (url) {\n applyUrlFromHistoryPushReplace(url)\n }\n\n return originalPushState(data, _unused, url)\n }\n\n /**\n * Patch replaceState to ensure external changes to the history are reflected in the Next.js Router.\n * Ensures Next.js internal history state is copied to the new history entry.\n * Ensures usePathname and useSearchParams hold the newly provided url.\n */\n window.history.replaceState = function replaceState(\n data: any,\n _unused: string,\n url?: string | URL | null\n ): void {\n // Avoid a loop when Next.js internals trigger pushState/replaceState\n if (data?.__NA || data?._N) {\n return originalReplaceState(data, _unused, url)\n }\n data = copyNextJsInternalHistoryState(data)\n\n if (url) {\n applyUrlFromHistoryPushReplace(url)\n }\n return originalReplaceState(data, _unused, url)\n }\n\n /**\n * Handle popstate event, this is used to handle back/forward in the browser.\n * By default dispatches ACTION_RESTORE, however if the history entry was not pushed/replaced by app-router it will reload the page.\n * That case can happen when the old router injected the history entry.\n */\n const onPopState = (event: PopStateEvent) => {\n if (!event.state) {\n // TODO-APP: this case only happens when pushState/replaceState was called outside of Next.js. It should probably reload the page in this case.\n return\n }\n\n // This case happens when the history entry was pushed by the `pages` router.\n if (!event.state.__NA) {\n window.location.reload()\n return\n }\n\n // TODO-APP: Ideally the back button should not use startTransition as it should apply the updates synchronously\n // Without startTransition works if the cache is there for this path\n startTransition(() => {\n dispatchTraverseAction(\n window.location.href,\n event.state.__PRIVATE_NEXTJS_INTERNALS_TREE\n )\n })\n }\n\n // Register popstate event to call onPopstate.\n window.addEventListener('popstate', onPopState)\n return () => {\n window.history.pushState = originalPushState\n window.history.replaceState = originalReplaceState\n window.removeEventListener('popstate', onPopState)\n }\n }, [])\n\n const { cache, tree, nextUrl, focusAndScrollRef } = state\n\n const matchingHead = useMemo(() => {\n return findHeadInCache(cache, tree[1])\n }, [cache, tree])\n\n // Add memoized pathParams for useParams.\n const pathParams = useMemo(() => {\n return getSelectedParams(tree)\n }, [tree])\n\n const layoutRouterContext = useMemo(() => {\n return {\n parentTree: tree,\n parentCacheNode: cache,\n parentSegmentPath: null,\n // Root node always has `url`\n // Provided in AppTreeContext to ensure it can be overwritten in layout-router\n url: canonicalUrl,\n }\n }, [tree, cache, canonicalUrl])\n\n const globalLayoutRouterContext = useMemo(() => {\n return {\n tree,\n focusAndScrollRef,\n nextUrl,\n }\n }, [tree, focusAndScrollRef, nextUrl])\n\n let head\n if (matchingHead !== null) {\n // The head is wrapped in an extra component so we can use\n // `useDeferredValue` to swap between the prefetched and final versions of\n // the head. (This is what LayoutRouter does for segment data, too.)\n //\n // The `key` is used to remount the component whenever the head moves to\n // a different segment.\n const [headCacheNode, headKey, headKeyWithoutSearchParams] = matchingHead\n\n head = (\n <Head\n key={\n // Necessary for PPR: omit search params from the key to match prerendered keys\n typeof window === 'undefined' ? headKeyWithoutSearchParams : headKey\n }\n headCacheNode={headCacheNode}\n />\n )\n } else {\n head = null\n }\n\n let content = (\n <RedirectBoundary>\n {head}\n {/* RootLayoutBoundary enables detection of Suspense boundaries around the root layout.\n When users wrap their layout in <Suspense>, this creates the component stack pattern\n \"Suspense -> RootLayoutBoundary\" which dynamic-rendering.ts uses to allow dynamic rendering. */}\n <RootLayoutBoundary>{cache.rsc}</RootLayoutBoundary>\n <AppRouterAnnouncer tree={tree} />\n </RedirectBoundary>\n )\n\n if (process.env.NODE_ENV !== 'production') {\n // In development, we apply few error boundaries and hot-reloader:\n // - DevRootHTTPAccessFallbackBoundary: avoid using navigation API like notFound() in root layout\n // - HotReloader:\n // - hot-reload the app when the code changes\n // - render dev overlay\n // - catch runtime errors and display global-error when necessary\n if (typeof window !== 'undefined') {\n const { DevRootHTTPAccessFallbackBoundary } =\n require('./dev-root-http-access-fallback-boundary') as typeof import('./dev-root-http-access-fallback-boundary')\n content = (\n <DevRootHTTPAccessFallbackBoundary>\n {content}\n </DevRootHTTPAccessFallbackBoundary>\n )\n }\n const HotReloader: typeof import('../dev/hot-reloader/app/hot-reloader-app').default =\n (\n require('../dev/hot-reloader/app/hot-reloader-app') as typeof import('../dev/hot-reloader/app/hot-reloader-app')\n ).default\n\n content = (\n <HotReloader\n globalError={globalError}\n webSocket={webSocket}\n staticIndicatorState={staticIndicatorState}\n >\n {content}\n </HotReloader>\n )\n } else {\n content = (\n <RootErrorBoundary\n errorComponent={globalError[0]}\n errorStyles={globalError[1]}\n >\n {content}\n </RootErrorBoundary>\n )\n }\n\n return (\n <>\n <HistoryUpdater appRouterState={state} />\n <RuntimeStyles />\n <PathParamsContext.Provider value={pathParams}>\n <PathnameContext.Provider value={pathname}>\n <SearchParamsContext.Provider value={searchParams}>\n <GlobalLayoutRouterContext.Provider\n value={globalLayoutRouterContext}\n >\n {/* TODO: We should be able to remove this context. useRouter\n should import from app-router-instance instead. It's only\n necessary because useRouter is shared between Pages and\n App Router. We should fork that module, then remove this\n context provider. */}\n <AppRouterContext.Provider value={publicAppRouterInstance}>\n <LayoutRouterContext.Provider value={layoutRouterContext}>\n {content}\n </LayoutRouterContext.Provider>\n </AppRouterContext.Provider>\n </GlobalLayoutRouterContext.Provider>\n </SearchParamsContext.Provider>\n </PathnameContext.Provider>\n </PathParamsContext.Provider>\n </>\n )\n}\n\nexport default function AppRouter({\n actionQueue,\n globalErrorState,\n webSocket,\n staticIndicatorState,\n}: {\n actionQueue: AppRouterActionQueue\n globalErrorState: GlobalErrorState\n webSocket?: WebSocket\n staticIndicatorState?: StaticIndicatorState\n}) {\n useNavFailureHandler()\n\n const router = (\n <Router\n actionQueue={actionQueue}\n globalError={globalErrorState}\n webSocket={webSocket}\n staticIndicatorState={staticIndicatorState}\n />\n )\n\n // At the very top level, use the default GlobalError component as the final fallback.\n // When the app router itself fails, which means the framework itself fails, we show the default error.\n return (\n <RootErrorBoundary errorComponent={DefaultGlobalError}>\n {router}\n </RootErrorBoundary>\n )\n}\n\nconst runtimeStyles = new Set<string>()\nlet runtimeStyleChanged = new Set<() => void>()\n\nglobalThis._N_E_STYLE_LOAD = function (href: string) {\n let len = runtimeStyles.size\n runtimeStyles.add(href)\n if (runtimeStyles.size !== len) {\n runtimeStyleChanged.forEach((cb) => cb())\n }\n // TODO figure out how to get a promise here\n // But maybe it's not necessary as react would block rendering until it's loaded\n return Promise.resolve()\n}\n\nfunction RuntimeStyles() {\n const [, forceUpdate] = React.useState(0)\n const renderedStylesSize = runtimeStyles.size\n useEffect(() => {\n const changed = () => forceUpdate((c) => c + 1)\n runtimeStyleChanged.add(changed)\n if (renderedStylesSize !== runtimeStyles.size) {\n changed()\n }\n return () => {\n runtimeStyleChanged.delete(changed)\n }\n }, [renderedStylesSize, forceUpdate])\n\n const dplId = process.env.NEXT_DEPLOYMENT_ID\n ? `?dpl=${process.env.NEXT_DEPLOYMENT_ID}`\n : ''\n return [...runtimeStyles].map((href, i) => (\n <link\n key={i}\n rel=\"stylesheet\"\n href={`${href}${dplId}`}\n // @ts-ignore\n precedence=\"next\"\n // TODO figure out crossOrigin and nonce\n // crossOrigin={TODO}\n // nonce={TODO}\n />\n ))\n}\n","import type {\n CacheNodeSeedData,\n FlightRouterState,\n FlightSegmentPath,\n Segment,\n} from '../../../shared/lib/app-router-types'\nimport type {\n CacheNode,\n ChildSegmentMap,\n ReadyCacheNode,\n} from '../../../shared/lib/app-router-types'\nimport type {\n HeadData,\n LoadingModuleData,\n} from '../../../shared/lib/app-router-types'\nimport { DEFAULT_SEGMENT_KEY } from '../../../shared/lib/segment'\nimport { matchSegment } from '../match-segments'\nimport { createRouterCacheKey } from './create-router-cache-key'\nimport type { FetchServerResponseResult } from './fetch-server-response'\nimport { isNavigatingToNewRootLayout } from './is-navigating-to-new-root-layout'\nimport { DYNAMIC_STALETIME_MS } from './prefetch-cache-utils'\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.\ntype SPANavigationTask = {\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. If\n // `children` is null (i.e. if this is a terminal task node), then `node`\n // represents a brand new Cache Node tree, which way or may not need to be\n // filled with dynamic data from the server.\n node: CacheNode | null\n // The tree sent to the server during the dynamic request. This is the\n // same as `route`, except with the `refetch` marker set on dynamic segments.\n // If all the segments are static, then this will be null, and no server\n // request is required.\n dynamicRequestTree: FlightRouterState | null\n children: Map<string, SPANavigationTask> | null\n}\n\n// A special type used to bail out and trigger a full-page navigation.\ntype MPANavigationTask = {\n // MPA tasks are distinguised from SPA tasks by having a null `route`.\n route: null\n node: null\n dynamicRequestTree: null\n children: null\n}\n\nconst MPA_NAVIGATION_TASK: MPANavigationTask = {\n route: null,\n node: null,\n dynamicRequestTree: null,\n children: null,\n}\n\nexport type Task = SPANavigationTask | MPANavigationTask\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 oldCacheNode: CacheNode,\n oldRouterState: FlightRouterState,\n newRouterState: FlightRouterState,\n prefetchData: CacheNodeSeedData | null,\n prefetchHead: HeadData | null,\n isPrefetchHeadPartial: boolean,\n isSamePageNavigation: boolean,\n scrollableSegmentsResult: Array<FlightSegmentPath>\n): Task | null {\n const segmentPath: Array<FlightSegmentPath> = []\n return updateCacheNodeOnNavigation(\n navigatedAt,\n oldCacheNode,\n oldRouterState,\n newRouterState,\n false,\n prefetchData,\n prefetchHead,\n isPrefetchHeadPartial,\n isSamePageNavigation,\n segmentPath,\n scrollableSegmentsResult\n )\n}\n\nfunction updateCacheNodeOnNavigation(\n navigatedAt: number,\n oldCacheNode: CacheNode,\n oldRouterState: FlightRouterState,\n newRouterState: FlightRouterState,\n didFindRootLayout: boolean,\n prefetchData: CacheNodeSeedData | null,\n prefetchHead: HeadData | null,\n isPrefetchHeadPartial: boolean,\n isSamePageNavigation: boolean,\n segmentPath: FlightSegmentPath,\n scrollableSegmentsResult: Array<FlightSegmentPath>\n): Task | null {\n // Diff the old and new trees to reuse the shared layouts.\n const oldRouterStateChildren = oldRouterState[1]\n const newRouterStateChildren = newRouterState[1]\n const prefetchDataChildren = prefetchData !== null ? prefetchData[2] : null\n\n if (!didFindRootLayout) {\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. See beginRenderingNewRouteTree for context.\n const isRootLayout = newRouterState[4] === true\n if (isRootLayout) {\n // Found a matching root layout.\n didFindRootLayout = true\n }\n }\n\n const oldParallelRoutes = oldCacheNode.parallelRoutes\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 const prefetchParallelRoutes = new Map(oldParallelRoutes)\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 needsDynamicRequest = 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. needsDynamicRequest is false at the\n // 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 const newRouterStateChild: FlightRouterState =\n newRouterStateChildren[parallelRouteKey]\n const oldRouterStateChild: FlightRouterState | void =\n oldRouterStateChildren[parallelRouteKey]\n const oldSegmentMapChild = oldParallelRoutes.get(parallelRouteKey)\n const prefetchDataChild: CacheNodeSeedData | void | null =\n prefetchDataChildren !== null\n ? prefetchDataChildren[parallelRouteKey]\n : null\n\n const newSegmentChild = newRouterStateChild[0]\n const newSegmentPathChild = segmentPath.concat([\n parallelRouteKey,\n newSegmentChild,\n ])\n const newSegmentKeyChild = createRouterCacheKey(newSegmentChild)\n\n const oldSegmentChild =\n oldRouterStateChild !== undefined ? oldRouterStateChild[0] : undefined\n\n const oldCacheNodeChild =\n oldSegmentMapChild !== undefined\n ? oldSegmentMapChild.get(newSegmentKeyChild)\n : undefined\n\n let taskChild: Task | null\n if (newSegmentChild === DEFAULT_SEGMENT_KEY) {\n // This is another kind of leaf segment — a default route.\n //\n // Default routes have special behavior. When there's no matching segment\n // for a parallel route, Next.js preserves the currently active segment\n // during a client navigation — but not for initial render. The server\n // leaves it to the client to account for this. So we need to handle\n // it here.\n if (oldRouterStateChild !== undefined) {\n // Reuse the existing Router State for this segment. We spawn a \"task\"\n // just to keep track of the updated router state; unlike most, it's\n // already fulfilled and won't be affected by the dynamic response.\n taskChild = spawnReusedTask(oldRouterStateChild)\n } else {\n // There's no currently active segment. Switch to the \"create\" path.\n taskChild = beginRenderingNewRouteTree(\n navigatedAt,\n oldRouterStateChild,\n newRouterStateChild,\n oldCacheNodeChild,\n didFindRootLayout,\n prefetchDataChild !== undefined ? prefetchDataChild : null,\n prefetchHead,\n isPrefetchHeadPartial,\n newSegmentPathChild,\n scrollableSegmentsResult\n )\n }\n } else if (\n isSamePageNavigation &&\n // Check if this is a page segment.\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 Object.keys(newRouterStateChild[1]).length === 0\n ) {\n // We special case navigations to the exact same URL as the current\n // location. It's a common UI pattern for apps to refresh when you click a\n // link to the current page. So when this happens, we refresh the dynamic\n // data in the page segments.\n //\n // Note that this does not apply if the any part of the hash or search\n // query has changed. This might feel a bit weird but it makes more sense\n // when you consider that the way to trigger this behavior is to click\n // the same link multiple times.\n //\n // TODO: We should probably refresh the *entire* route when this case\n // occurs, not just the page segments. Essentially treating it the same as\n // a refresh() triggered by an action, which is the more explicit way of\n // modeling the UI pattern described above.\n //\n // Also note that this only refreshes the dynamic data, not static/\n // cached data. If the page segment is fully static and prefetched, the\n // request is skipped. (This is also how refresh() works.)\n taskChild = beginRenderingNewRouteTree(\n navigatedAt,\n oldRouterStateChild,\n newRouterStateChild,\n oldCacheNodeChild,\n didFindRootLayout,\n prefetchDataChild !== undefined ? prefetchDataChild : null,\n prefetchHead,\n isPrefetchHeadPartial,\n newSegmentPathChild,\n scrollableSegmentsResult\n )\n } else if (\n oldRouterStateChild !== undefined &&\n oldSegmentChild !== undefined &&\n matchSegment(newSegmentChild, oldSegmentChild)\n ) {\n if (\n oldCacheNodeChild !== undefined &&\n oldRouterStateChild !== undefined\n ) {\n // This segment exists in both the old and new trees. Recursively update\n // the children.\n taskChild = updateCacheNodeOnNavigation(\n navigatedAt,\n oldCacheNodeChild,\n oldRouterStateChild,\n newRouterStateChild,\n didFindRootLayout,\n prefetchDataChild,\n prefetchHead,\n isPrefetchHeadPartial,\n isSamePageNavigation,\n newSegmentPathChild,\n scrollableSegmentsResult\n )\n } else {\n // There's no existing Cache Node for this segment. Switch to the\n // \"create\" path.\n taskChild = beginRenderingNewRouteTree(\n navigatedAt,\n oldRouterStateChild,\n newRouterStateChild,\n oldCacheNodeChild,\n didFindRootLayout,\n prefetchDataChild !== undefined ? prefetchDataChild : null,\n prefetchHead,\n isPrefetchHeadPartial,\n newSegmentPathChild,\n scrollableSegmentsResult\n )\n }\n } else {\n // This is a new tree. Switch to the \"create\" path.\n taskChild = beginRenderingNewRouteTree(\n navigatedAt,\n oldRouterStateChild,\n newRouterStateChild,\n oldCacheNodeChild,\n didFindRootLayout,\n prefetchDataChild !== undefined ? prefetchDataChild : null,\n prefetchHead,\n isPrefetchHeadPartial,\n newSegmentPathChild,\n scrollableSegmentsResult\n )\n }\n\n if (taskChild !== null) {\n // Recursively propagate up the child tasks.\n\n if (taskChild.route === null) {\n // One of the child tasks discovered a change to the root layout.\n // Immediately unwind from this recursive traversal.\n return MPA_NAVIGATION_TASK\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(oldSegmentMapChild)\n newSegmentMapChild.set(newSegmentKeyChild, newCacheNodeChild)\n prefetchParallelRoutes.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 needsDynamicRequest = true\n dynamicRequestTreeChildren[parallelRouteKey] = dynamicRequestTreeChild\n } else {\n dynamicRequestTreeChildren[parallelRouteKey] = taskChildRoute\n }\n } else {\n // The child didn't change. We can use the prefetched router state.\n patchedRouterStateChildren[parallelRouteKey] = newRouterStateChild\n dynamicRequestTreeChildren[parallelRouteKey] = newRouterStateChild\n }\n }\n\n if (taskChildren === null) {\n // No new tasks were spawned.\n return null\n }\n\n const newCacheNode: ReadyCacheNode = {\n lazyData: null,\n rsc: oldCacheNode.rsc,\n // We intentionally aren't updating the prefetchRsc field, since this node\n // is already part of the current tree, because it would be weird for\n // prefetch data to be newer than the final data. It probably won't ever be\n // observable anyway, but it could happen if the segment is unmounted then\n // mounted again, because LayoutRouter will momentarily switch to rendering\n // prefetchRsc, via useDeferredValue.\n prefetchRsc: oldCacheNode.prefetchRsc,\n head: oldCacheNode.head,\n prefetchHead: oldCacheNode.prefetchHead,\n loading: oldCacheNode.loading,\n\n // Everything is cloned except for the children, which we computed above.\n parallelRoutes: prefetchParallelRoutes,\n\n navigatedAt,\n }\n\n return {\n // Return a cloned copy of the router state with updated children.\n route: patchRouterStateWithNewChildren(\n newRouterState,\n patchedRouterStateChildren\n ),\n node: newCacheNode,\n dynamicRequestTree: needsDynamicRequest\n ? patchRouterStateWithNewChildren(\n newRouterState,\n dynamicRequestTreeChildren\n )\n : null,\n children: taskChildren,\n }\n}\n\nfunction beginRenderingNewRouteTree(\n navigatedAt: number,\n oldRouterState: FlightRouterState | void,\n newRouterState: FlightRouterState,\n existingCacheNode: CacheNode | void,\n didFindRootLayout: boolean,\n prefetchData: CacheNodeSeedData | null,\n possiblyPartialPrefetchHead: HeadData | null,\n isPrefetchHeadPartial: boolean,\n segmentPath: FlightSegmentPath,\n scrollableSegmentsResult: Array<FlightSegmentPath>\n): Task {\n if (!didFindRootLayout) {\n // The route tree changed before we reached a layout. (The highest-level\n // layout in a route tree is referred to as the \"root\" layout.) This could\n // mean that we're navigating between two different root layouts. When this\n // happens, we perform a full-page (MPA-style) 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 because\n // we're re-rendering a segment outside of the root layout does not mean we\n // should trigger a full-page navigation.\n //\n // Specifically, we handle dynamic parameters differently: two segments are\n // 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 unchanged.\n // In the common case, this branch is skipped completely.\n if (\n oldRouterState === undefined ||\n isNavigatingToNewRootLayout(oldRouterState, newRouterState)\n ) {\n // The root layout changed. Perform a full-page navigation.\n return MPA_NAVIGATION_TASK\n }\n }\n return createCacheNodeOnNavigation(\n navigatedAt,\n newRouterState,\n existingCacheNode,\n prefetchData,\n possiblyPartialPrefetchHead,\n isPrefetchHeadPartial,\n segmentPath,\n scrollableSegmentsResult\n )\n}\n\nfunction createCacheNodeOnNavigation(\n navigatedAt: number,\n routerState: FlightRouterState,\n existingCacheNode: CacheNode | void,\n prefetchData: CacheNodeSeedData | null,\n possiblyPartialPrefetchHead: HeadData | null,\n isPrefetchHeadPartial: boolean,\n segmentPath: FlightSegmentPath,\n scrollableSegmentsResult: Array<FlightSegmentPath>\n): SPANavigationTask {\n // Same traversal as updateCacheNodeNavigation, but we switch to this path\n // once we reach the part of the tree that was not in the previous route. We\n // don't need to diff against the old tree, we just need to create a new one.\n\n // The head is assigned to every leaf segment delivered by the server. Based\n // on corresponding logic in fill-lazy-items-till-leaf-with-head.ts\n const routerStateChildren = routerState[1]\n const isLeafSegment = Object.keys(routerStateChildren).length === 0\n\n // Even we're rendering inside the \"new\" part of the target tree, we may have\n // a locally cached segment that we can reuse. This may come from either 1)\n // the CacheNode tree, which lives in React state and is populated by previous\n // navigations; or 2) the prefetch cache, which is a separate cache that is\n // populated by prefetches.\n let rsc: React.ReactNode\n let loading: LoadingModuleData | Promise<LoadingModuleData>\n let head: HeadData | null\n let cacheNodeNavigatedAt: number\n if (\n existingCacheNode !== undefined &&\n // DYNAMIC_STALETIME_MS defaults to 0, but it can be increased using\n // the experimental.staleTimes.dynamic config. When set, we'll avoid\n // refetching dynamic data if it was fetched within the given threshold.\n existingCacheNode.navigatedAt + DYNAMIC_STALETIME_MS > navigatedAt\n ) {\n // We have an existing CacheNode for this segment, and it's not stale. We\n // should reuse it rather than request a new one.\n rsc = existingCacheNode.rsc\n loading = existingCacheNode.loading\n head = existingCacheNode.head\n\n // Don't update the navigatedAt timestamp, since we're reusing stale data.\n cacheNodeNavigatedAt = existingCacheNode.navigatedAt\n } else if (prefetchData !== null) {\n // There's no existing CacheNode for this segment, but we do have prefetch\n // data. If the prefetch data is fully static (i.e. does not contain any\n // dynamic holes), we don't need to request it from the server.\n rsc = prefetchData[1]\n loading = prefetchData[3]\n head = isLeafSegment ? possiblyPartialPrefetchHead : null\n // Even though we're accessing the data from the prefetch cache, this is\n // conceptually a new segment, not a reused one. So we should update the\n // navigatedAt timestamp.\n cacheNodeNavigatedAt = navigatedAt\n const isPrefetchRscPartial = prefetchData[4]\n if (\n // Check if the segment data is partial\n isPrefetchRscPartial ||\n // Check if the head is partial (only relevant if this is a leaf segment)\n (isPrefetchHeadPartial && isLeafSegment)\n ) {\n // We only have partial data from this segment. Like missing segments, we\n // must request the full data from the server.\n return spawnPendingTask(\n navigatedAt,\n routerState,\n prefetchData,\n possiblyPartialPrefetchHead,\n isPrefetchHeadPartial,\n segmentPath,\n scrollableSegmentsResult\n )\n } else {\n // The prefetch data is fully static, so we can omit it from the\n // navigation request.\n }\n } else {\n // There's no prefetch for this segment. Everything from this point will be\n // requested from the server, even if there are static children below it.\n // Create a terminal task node that will later be fulfilled by\n // server response.\n return spawnPendingTask(\n navigatedAt,\n routerState,\n null,\n possiblyPartialPrefetchHead,\n isPrefetchHeadPartial,\n segmentPath,\n scrollableSegmentsResult\n )\n }\n\n // We already have a full segment we can render, so we don't need to request a\n // new one from the server. Keep traversing down the tree until we reach\n // something that requires a dynamic request.\n const prefetchDataChildren = prefetchData !== null ? prefetchData[2] : null\n const taskChildren = new Map()\n const existingCacheNodeChildren =\n existingCacheNode !== undefined ? existingCacheNode.parallelRoutes : null\n const cacheNodeChildren = new Map(existingCacheNodeChildren)\n let dynamicRequestTreeChildren: {\n [parallelRouteKey: string]: FlightRouterState\n } = {}\n let needsDynamicRequest = false\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 // 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 scrollableSegmentsResult.push(segmentPath)\n } else {\n for (let parallelRouteKey in routerStateChildren) {\n const routerStateChild: FlightRouterState =\n routerStateChildren[parallelRouteKey]\n const prefetchDataChild: CacheNodeSeedData | void | null =\n prefetchDataChildren !== null\n ? prefetchDataChildren[parallelRouteKey]\n : null\n const existingSegmentMapChild =\n existingCacheNodeChildren !== null\n ? existingCacheNodeChildren.get(parallelRouteKey)\n : undefined\n const segmentChild = routerStateChild[0]\n const segmentPathChild = segmentPath.concat([\n parallelRouteKey,\n segmentChild,\n ])\n const segmentKeyChild = createRouterCacheKey(segmentChild)\n\n const existingCacheNodeChild =\n existingSegmentMapChild !== undefined\n ? existingSegmentMapChild.get(segmentKeyChild)\n : undefined\n\n const taskChild = createCacheNodeOnNavigation(\n navigatedAt,\n routerStateChild,\n existingCacheNodeChild,\n prefetchDataChild,\n possiblyPartialPrefetchHead,\n isPrefetchHeadPartial,\n segmentPathChild,\n scrollableSegmentsResult\n )\n taskChildren.set(parallelRouteKey, taskChild)\n const dynamicRequestTreeChild = taskChild.dynamicRequestTree\n if (dynamicRequestTreeChild !== null) {\n // Something in the child tree is dynamic.\n needsDynamicRequest = true\n dynamicRequestTreeChildren[parallelRouteKey] = dynamicRequestTreeChild\n } else {\n dynamicRequestTreeChildren[parallelRouteKey] = routerStateChild\n }\n const newCacheNodeChild = taskChild.node\n if (newCacheNodeChild !== null) {\n const newSegmentMapChild: ChildSegmentMap = new Map()\n newSegmentMapChild.set(segmentKeyChild, newCacheNodeChild)\n cacheNodeChildren.set(parallelRouteKey, newSegmentMapChild)\n }\n }\n }\n\n return {\n // Since we're inside a new route tree, unlike the\n // `updateCacheNodeOnNavigation` path, the router state on the children\n // tasks is always the same as the router state we pass in. So we don't need\n // to clone/modify it.\n route: routerState,\n node: {\n lazyData: null,\n // Since this segment is already full, we don't need to use the\n // `prefetchRsc` field.\n rsc,\n prefetchRsc: null,\n head,\n prefetchHead: null,\n loading,\n parallelRoutes: cacheNodeChildren,\n navigatedAt: cacheNodeNavigatedAt,\n },\n dynamicRequestTree: needsDynamicRequest\n ? patchRouterStateWithNewChildren(routerState, dynamicRequestTreeChildren)\n : 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 spawnPendingTask(\n navigatedAt: number,\n routerState: FlightRouterState,\n prefetchData: CacheNodeSeedData | null,\n prefetchHead: HeadData | null,\n isPrefetchHeadPartial: boolean,\n segmentPath: FlightSegmentPath,\n scrollableSegmentsResult: Array<FlightSegmentPath>\n): SPANavigationTask {\n // Create a task that will later be fulfilled by data from the server.\n\n // Clone the prefetched route tree and the `refetch` marker to it. We'll send\n // this to the server so it knows where to start rendering.\n const dynamicRequestTree = patchRouterStateWithNewChildren(\n routerState,\n routerState[1]\n )\n dynamicRequestTree[3] = 'refetch'\n\n const newTask: Task = {\n route: routerState,\n\n // Corresponds to the part of the route that will be rendered on the server.\n node: createPendingCacheNode(\n navigatedAt,\n routerState,\n prefetchData,\n prefetchHead,\n isPrefetchHeadPartial,\n segmentPath,\n scrollableSegmentsResult\n ),\n // Because this is non-null, and it gets propagated up through the parent\n // tasks, the root task will know that it needs to perform a server request.\n dynamicRequestTree,\n children: null,\n }\n return newTask\n}\n\nfunction spawnReusedTask(reusedRouterState: FlightRouterState): Task {\n // Create a task that reuses an existing segment, e.g. when reusing\n // the current active segment in place of a default route.\n return {\n route: reusedRouterState,\n node: null,\n dynamicRequestTree: null,\n children: null,\n }\n}\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 listenForDynamicRequest(\n task: SPANavigationTask,\n responsePromise: Promise<FetchServerResponseResult>\n) {\n responsePromise.then(\n ({ flightData }: FetchServerResponseResult) => {\n if (typeof flightData === 'string') {\n // Happens when navigating to page in `pages` from `app`. We shouldn't\n // get here because should have already handled this during\n // the prefetch.\n return\n }\n for (const normalizedFlightData of flightData) {\n const {\n segmentPath,\n tree: serverRouterState,\n seedData: dynamicData,\n head: dynamicHead,\n } = normalizedFlightData\n\n if (!dynamicData) {\n // This shouldn't happen. PPR should always send back a response.\n // However, `FlightDataPath` is a shared type and the pre-PPR handling of\n // this might return null.\n continue\n }\n\n writeDynamicDataIntoPendingTask(\n task,\n segmentPath,\n serverRouterState,\n dynamicData,\n dynamicHead\n )\n }\n\n // Now that we've exhausted all the data we received from the server, if\n // there are any remaining pending tasks in the tree, abort them now.\n // If there's any missing data, it will trigger a lazy fetch.\n abortTask(task, null)\n },\n (error: any) => {\n // This will trigger an error during render\n abortTask(task, error)\n }\n )\n}\n\nfunction writeDynamicDataIntoPendingTask(\n rootTask: SPANavigationTask,\n segmentPath: FlightSegmentPath,\n serverRouterState: FlightRouterState,\n dynamicData: CacheNodeSeedData,\n dynamicHead: HeadData\n) {\n // The data sent by the server represents only a subtree of the app. We need\n // to find the part of the task tree that matches the server response, and\n // fulfill it using the dynamic data.\n //\n // segmentPath represents the parent path of subtree. It's a repeating pattern\n // of parallel route key and segment:\n //\n // [string, Segment, string, Segment, string, Segment, ...]\n //\n // Iterate through the path and finish any tasks that match this payload.\n let task = rootTask\n for (let i = 0; i < segmentPath.length; i += 2) {\n const parallelRouteKey: string = segmentPath[i]\n const segment: Segment = segmentPath[i + 1]\n const taskChildren = task.children\n if (taskChildren !== null) {\n const taskChild = taskChildren.get(parallelRouteKey)\n if (taskChild !== undefined) {\n const taskSegment = taskChild.route[0]\n if (matchSegment(segment, taskSegment)) {\n // Found a match for this task. Keep traversing down the task tree.\n task = taskChild\n continue\n }\n }\n }\n // We didn't find a child task that matches the server data. Exit. We won't\n // abort the task, though, because a different FlightDataPath may be able to\n // fulfill it (see loop in listenForDynamicRequest). We only abort tasks\n // once we've run out of data.\n return\n }\n\n finishTaskUsingDynamicDataPayload(\n task,\n serverRouterState,\n dynamicData,\n dynamicHead\n )\n}\n\nfunction finishTaskUsingDynamicDataPayload(\n task: SPANavigationTask,\n serverRouterState: FlightRouterState,\n dynamicData: CacheNodeSeedData,\n dynamicHead: HeadData\n) {\n if (task.dynamicRequestTree === null) {\n // Everything in this subtree is already complete. Bail out.\n return\n }\n\n // dynamicData may represent a larger subtree than the task. Before we can\n // finish the task, we need to line them up.\n const taskChildren = task.children\n const taskNode = task.node\n if (taskChildren === null) {\n // We've reached the leaf node of the pending task. The server data tree\n // lines up the pending Cache Node tree. We can now switch to the\n // normal algorithm.\n if (taskNode !== null) {\n finishPendingCacheNode(\n taskNode,\n task.route,\n serverRouterState,\n dynamicData,\n dynamicHead\n )\n // Set this to null to indicate that this task is now complete.\n task.dynamicRequestTree = null\n }\n return\n }\n // The server returned more data than we need to finish the task. Skip over\n // the extra segments until we reach the leaf task node.\n const serverChildren = serverRouterState[1]\n const dynamicDataChildren = dynamicData[2]\n\n for (const parallelRouteKey in serverRouterState) {\n const serverRouterStateChild: FlightRouterState =\n serverChildren[parallelRouteKey]\n const dynamicDataChild: CacheNodeSeedData | null | void =\n dynamicDataChildren[parallelRouteKey]\n\n const taskChild = taskChildren.get(parallelRouteKey)\n if (taskChild !== undefined) {\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 return finishTaskUsingDynamicDataPayload(\n taskChild,\n serverRouterStateChild,\n dynamicDataChild,\n dynamicHead\n )\n }\n }\n // We didn't find a child task that matches the server data. We won't abort\n // the task, though, because a different FlightDataPath may be able to\n // fulfill it (see loop in listenForDynamicRequest). We only abort tasks\n // once we've run out of data.\n }\n}\n\nfunction createPendingCacheNode(\n navigatedAt: number,\n routerState: FlightRouterState,\n prefetchData: CacheNodeSeedData | null,\n prefetchHead: HeadData | null,\n isPrefetchHeadPartial: boolean,\n segmentPath: FlightSegmentPath,\n scrollableSegmentsResult: Array<FlightSegmentPath>\n): ReadyCacheNode {\n const routerStateChildren = routerState[1]\n const prefetchDataChildren = prefetchData !== null ? prefetchData[2] : null\n\n const parallelRoutes = new Map()\n for (let parallelRouteKey in routerStateChildren) {\n const routerStateChild: FlightRouterState =\n routerStateChildren[parallelRouteKey]\n const prefetchDataChild: CacheNodeSeedData | null | void =\n prefetchDataChildren !== null\n ? prefetchDataChildren[parallelRouteKey]\n : null\n\n const segmentChild = routerStateChild[0]\n const segmentPathChild = segmentPath.concat([\n parallelRouteKey,\n segmentChild,\n ])\n const segmentKeyChild = createRouterCacheKey(segmentChild)\n\n const newCacheNodeChild = createPendingCacheNode(\n navigatedAt,\n routerStateChild,\n prefetchDataChild === undefined ? null : prefetchDataChild,\n prefetchHead,\n isPrefetchHeadPartial,\n segmentPathChild,\n scrollableSegmentsResult\n )\n\n const newSegmentMapChild: ChildSegmentMap = new Map()\n newSegmentMapChild.set(segmentKeyChild, newCacheNodeChild)\n parallelRoutes.set(parallelRouteKey, newSegmentMapChild)\n }\n\n // The head is assigned to every leaf segment delivered by the server. Based\n // on corresponding logic in fill-lazy-items-till-leaf-with-head.ts\n const isLeafSegment = parallelRoutes.size === 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 // 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 scrollableSegmentsResult.push(segmentPath)\n }\n\n const maybePrefetchRsc = prefetchData !== null ? prefetchData[1] : null\n return {\n lazyData: null,\n parallelRoutes: parallelRoutes,\n\n prefetchRsc: maybePrefetchRsc !== undefined ? maybePrefetchRsc : null,\n prefetchHead: isLeafSegment ? prefetchHead : [null, null],\n\n // Create a deferred promise. This will be fulfilled once the dynamic\n // response is received from the server.\n rsc: createDeferredRsc() as React.ReactNode,\n head: isLeafSegment ? (createDeferredRsc() as React.ReactNode) : null,\n\n // TODO: Technically, a loading boundary could contain dynamic data. We must\n // have separate `loading` and `prefetchLoading` fields to handle this, like\n // we do for the segment data and head.\n loading:\n prefetchData !== null\n ? (prefetchData[3] ?? null)\n : // If we don't have a prefetch, then we don't know if there's a loading component.\n // We'll fulfill it based on the dynamic response, just like `rsc` and `head`.\n createDeferredRsc<LoadingModuleData>(),\n\n navigatedAt,\n }\n}\n\nfunction finishPendingCacheNode(\n cacheNode: CacheNode,\n taskState: FlightRouterState,\n serverState: FlightRouterState,\n dynamicData: CacheNodeSeedData,\n dynamicHead: HeadData\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 const taskStateChildren = taskState[1]\n const serverStateChildren = serverState[1]\n const dataChildren = dynamicData[2]\n\n // The router state that we traverse the tree with (taskState) is the same one\n // that we used to construct the pending Cache Node tree. That way we're sure\n // to resolve all the pending promises.\n const parallelRoutes = cacheNode.parallelRoutes\n for (let parallelRouteKey in taskStateChildren) {\n const taskStateChild: FlightRouterState =\n taskStateChildren[parallelRouteKey]\n const serverStateChild: FlightRouterState | void =\n serverStateChildren[parallelRouteKey]\n const dataChild: CacheNodeSeedData | null | void =\n dataChildren[parallelRouteKey]\n\n const segmentMapChild = parallelRoutes.get(parallelRouteKey)\n const taskSegmentChild = taskStateChild[0]\n const taskSegmentKeyChild = createRouterCacheKey(taskSegmentChild)\n\n const cacheNodeChild =\n segmentMapChild !== undefined\n ? segmentMapChild.get(taskSegmentKeyChild)\n : undefined\n\n if (cacheNodeChild !== undefined) {\n if (\n serverStateChild !== undefined &&\n matchSegment(taskSegmentChild, serverStateChild[0])\n ) {\n if (dataChild !== undefined && dataChild !== null) {\n // This is the happy path. Recursively update all the children.\n finishPendingCacheNode(\n cacheNodeChild,\n taskStateChild,\n serverStateChild,\n dataChild,\n dynamicHead\n )\n } else {\n // The server never returned data for this segment. Trigger a lazy\n // fetch during render. This shouldn't happen because the Route Tree\n // and the Seed Data tree sent by the server should always be the same\n // shape when part of the same server response.\n abortPendingCacheNode(taskStateChild, cacheNodeChild, null)\n }\n } else {\n // The server never returned data for this segment. Trigger a lazy\n // fetch during render.\n abortPendingCacheNode(taskStateChild, cacheNodeChild, null)\n }\n } else {\n // The server response matches what was expected to receive, but there's\n // no matching Cache Node in the task tree. This is a bug in the\n // implementation because we should have created a node for every\n // segment in the tree that's associated with this task.\n }\n }\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[1]\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)\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[3]\n loading.resolve(dynamicLoading)\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)\n }\n}\n\nexport function abortTask(task: SPANavigationTask, error: any): void {\n const cacheNode = task.node\n if (cacheNode === null) {\n // This indicates the task is already complete.\n return\n }\n\n const taskChildren = task.children\n if (taskChildren === null) {\n // Reached the leaf task node. This is the root of a pending cache\n // node tree.\n abortPendingCacheNode(task.route, cacheNode, error)\n } else {\n // This is an intermediate task node. Keep traversing until we reach a\n // task node with no children. That will be the root of the cache node tree\n // that needs to be resolved.\n for (const taskChild of taskChildren.values()) {\n abortTask(taskChild, error)\n }\n }\n\n // Set this to null to indicate that this task is now complete.\n task.dynamicRequestTree = null\n}\n\nfunction abortPendingCacheNode(\n routerState: FlightRouterState,\n cacheNode: CacheNode,\n error: any\n): void {\n // For every pending segment in the tree, resolve its `rsc` promise to `null`\n // to trigger a lazy fetch during render.\n //\n // Or, if an error object is provided, it will error instead.\n const routerStateChildren = routerState[1]\n const parallelRoutes = cacheNode.parallelRoutes\n for (let parallelRouteKey in routerStateChildren) {\n const routerStateChild: FlightRouterState =\n routerStateChildren[parallelRouteKey]\n const segmentMapChild = parallelRoutes.get(parallelRouteKey)\n if (segmentMapChild === undefined) {\n // This shouldn't happen because we're traversing the same tree that was\n // used to construct the cache nodes in the first place.\n continue\n }\n const segmentChild = routerStateChild[0]\n const segmentKeyChild = createRouterCacheKey(segmentChild)\n const cacheNodeChild = segmentMapChild.get(segmentKeyChild)\n if (cacheNodeChild !== undefined) {\n abortPendingCacheNode(routerStateChild, cacheNodeChild, error)\n } else {\n // This shouldn't happen because we're traversing the same tree that was\n // used to construct the cache nodes in the first place.\n }\n }\n\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)\n } else {\n // This will trigger an error during rendering.\n rsc.reject(error)\n }\n }\n\n const loading = cacheNode.loading\n if (isDeferredRsc(loading)) {\n loading.resolve(null)\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)\n }\n}\n\nexport function updateCacheNodeOnPopstateRestoration(\n oldCacheNode: CacheNode,\n routerState: FlightRouterState\n): ReadyCacheNode {\n // A popstate navigation reads data from the local cache. It does not issue\n // new network requests (unless the cache entries have been evicted). So, we\n // update the cache to drop the prefetch data for any segment whose dynamic\n // data was already received. This prevents an unnecessary flash back to PPR\n // state during a back/forward navigation.\n //\n // This function clones the entire cache node tree and sets the `prefetchRsc`\n // field to `null` to prevent it from being rendered. We can't mutate the node\n // in place because this is a concurrent data structure.\n\n const routerStateChildren = routerState[1]\n const oldParallelRoutes = oldCacheNode.parallelRoutes\n const newParallelRoutes = new Map(oldParallelRoutes)\n for (let parallelRouteKey in routerStateChildren) {\n const routerStateChild: FlightRouterState =\n routerStateChildren[parallelRouteKey]\n const segmentChild = routerStateChild[0]\n const segmentKeyChild = createRouterCacheKey(segmentChild)\n const oldSegmentMapChild = oldParallelRoutes.get(parallelRouteKey)\n if (oldSegmentMapChild !== undefined) {\n const oldCacheNodeChild = oldSegmentMapChild.get(segmentKeyChild)\n if (oldCacheNodeChild !== undefined) {\n const newCacheNodeChild = updateCacheNodeOnPopstateRestoration(\n oldCacheNodeChild,\n routerStateChild\n )\n const newSegmentMapChild = new Map(oldSegmentMapChild)\n newSegmentMapChild.set(segmentKeyChild, newCacheNodeChild)\n newParallelRoutes.set(parallelRouteKey, newSegmentMapChild)\n }\n }\n }\n\n // Only show prefetched data if the dynamic data is still pending.\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 not\n // mean that all the dynamic data has fully streamed in. It just means that\n // _some_ of the dynamic data was received. But as a heuristic, we assume that\n // the rest dynamic data will stream in quickly, so it's still better to skip\n // the prefetch state.\n const rsc = oldCacheNode.rsc\n const shouldUsePrefetch = isDeferredRsc(rsc) && rsc.status === 'pending'\n\n return {\n lazyData: null,\n rsc,\n head: oldCacheNode.head,\n\n prefetchHead: shouldUsePrefetch ? oldCacheNode.prefetchHead : [null, null],\n prefetchRsc: shouldUsePrefetch ? oldCacheNode.prefetchRsc : null,\n loading: oldCacheNode.loading,\n\n // These are the cloned children we computed above\n parallelRoutes: newParallelRoutes,\n\n navigatedAt: oldCacheNode.navigatedAt,\n }\n}\n\nconst DEFERRED = Symbol()\n\ntype PendingDeferredRsc<T> = Promise<T> & {\n status: 'pending'\n resolve: (value: T) => void\n reject: (error: any) => void\n tag: Symbol\n}\n\ntype FulfilledDeferredRsc<T> = Promise<T> & {\n status: 'fulfilled'\n value: T\n resolve: (value: T) => void\n reject: (error: any) => void\n tag: Symbol\n}\n\ntype RejectedDeferredRsc<T> = Promise<T> & {\n status: 'rejected'\n reason: any\n resolve: (value: T) => void\n reject: (error: any) => void\n tag: Symbol\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.\nfunction 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 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) => {\n if (pendingRsc.status === 'pending') {\n const fulfilledRsc: FulfilledDeferredRsc<T> = pendingRsc as any\n fulfilledRsc.status = 'fulfilled'\n fulfilledRsc.value = value\n resolve(value)\n }\n }\n pendingRsc.reject = (error: any) => {\n if (pendingRsc.status === 'pending') {\n const rejectedRsc: RejectedDeferredRsc<T> = pendingRsc as any\n rejectedRsc.status = 'rejected'\n rejectedRsc.reason = error\n reject(error)\n }\n }\n pendingRsc.tag = DEFERRED\n return pendingRsc\n}\n","import type {\n FlightSegmentPath,\n CacheNode,\n} from '../../../shared/lib/app-router-types'\nimport { getNextFlightSegmentPath } from '../../flight-data-helpers'\nimport { createRouterCacheKey } from './create-router-cache-key'\n\n/**\n * This will clear the CacheNode data for a particular segment path. This will cause a lazy-fetch in layout router to fill in new data.\n */\nexport function clearCacheNodeDataForSegmentPath(\n newCache: CacheNode,\n existingCache: CacheNode,\n flightSegmentPath: FlightSegmentPath\n): void {\n const isLastEntry = flightSegmentPath.length <= 2\n\n const [parallelRouteKey, segment] = flightSegmentPath\n const cacheKey = createRouterCacheKey(segment)\n\n const existingChildSegmentMap =\n existingCache.parallelRoutes.get(parallelRouteKey)\n\n let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey)\n\n if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {\n childSegmentMap = new Map(existingChildSegmentMap)\n newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap)\n }\n\n const existingChildCacheNode = existingChildSegmentMap?.get(cacheKey)\n let childCacheNode = childSegmentMap.get(cacheKey)\n\n // In case of last segment start off the fetch at this level and don't copy further down.\n if (isLastEntry) {\n if (\n !childCacheNode ||\n !childCacheNode.lazyData ||\n childCacheNode === existingChildCacheNode\n ) {\n childSegmentMap.set(cacheKey, {\n lazyData: null,\n rsc: null,\n prefetchRsc: null,\n head: null,\n prefetchHead: null,\n parallelRoutes: new Map(),\n loading: null,\n navigatedAt: -1,\n })\n }\n return\n }\n\n if (!childCacheNode || !existingChildCacheNode) {\n // Start fetch in the place where the existing cache doesn't have the data yet.\n if (!childCacheNode) {\n childSegmentMap.set(cacheKey, {\n lazyData: null,\n rsc: null,\n prefetchRsc: null,\n head: null,\n prefetchHead: null,\n parallelRoutes: new Map(),\n loading: null,\n navigatedAt: -1,\n })\n }\n return\n }\n\n if (childCacheNode === existingChildCacheNode) {\n childCacheNode = {\n lazyData: childCacheNode.lazyData,\n rsc: childCacheNode.rsc,\n prefetchRsc: childCacheNode.prefetchRsc,\n head: childCacheNode.head,\n prefetchHead: childCacheNode.prefetchHead,\n parallelRoutes: new Map(childCacheNode.parallelRoutes),\n loading: childCacheNode.loading,\n } as CacheNode\n childSegmentMap.set(cacheKey, childCacheNode)\n }\n\n return clearCacheNodeDataForSegmentPath(\n childCacheNode,\n existingChildCacheNode,\n getNextFlightSegmentPath(flightSegmentPath)\n )\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 {\n addSearchParamsIfPageSegment,\n DEFAULT_SEGMENT_KEY,\n PAGE_SEGMENT_KEY,\n} from '../../../shared/lib/segment'\nimport type { NormalizedFlightData } from '../../flight-data-helpers'\nimport { createEmptyCacheNode } from '../app-router'\nimport { applyRouterStatePatchToTree } from './apply-router-state-patch-to-tree'\nimport { createHrefFromUrl } from './create-href-from-url'\nimport { createRouterCacheKey } from './create-router-cache-key'\nimport { fillCacheWithNewSubTreeDataButOnlyLoading } from './fill-cache-with-new-subtree-data'\nimport { handleMutable } from './handle-mutable'\nimport { generateSegmentsFromPatch } from './reducers/navigate-reducer'\nimport type { Mutable, ReadonlyReducerState } from './router-reducer-types'\n\n/**\n * This is a stop-gap until per-segment caching is implemented. It leverages the `aliased` flag that is added\n * to prefetch entries when it's determined that the loading state from that entry should be used for this navigation.\n * This function takes the aliased entry and only applies the loading state to the updated cache node.\n * We should remove this once per-segment fetching is implemented as ideally the prefetch cache will contain a\n * more granular segment map and so the router will be able to simply re-use the loading segment for the new navigation.\n */\nexport function handleAliasedPrefetchEntry(\n navigatedAt: number,\n state: ReadonlyReducerState,\n flightData: string | NormalizedFlightData[],\n url: URL,\n mutable: Mutable\n) {\n let currentTree = state.tree\n let currentCache = state.cache\n const href = createHrefFromUrl(url)\n let applied\n let scrollableSegments: FlightSegmentPath[] = []\n\n if (typeof flightData === 'string') {\n return false\n }\n\n for (const normalizedFlightData of flightData) {\n // If the segment doesn't have a loading component, we don't need to do anything.\n if (!hasLoadingComponentInSeedData(normalizedFlightData.seedData)) {\n continue\n }\n\n let treePatch = normalizedFlightData.tree\n // Segments are keyed by searchParams (e.g. __PAGE__?{\"foo\":\"bar\"}). We might return a less specific, param-less entry,\n // so we ensure that the final tree contains the correct searchParams (reflected in the URL) are provided in the updated FlightRouterState tree.\n // We only do this on the first read, as otherwise we'd be overwriting the searchParams that may have already been set\n treePatch = addSearchParamsToPageSegments(\n treePatch,\n Object.fromEntries(url.searchParams)\n )\n\n const { seedData, isRootRender, pathToSegment } = normalizedFlightData\n // TODO-APP: remove ''\n const flightSegmentPathWithLeadingEmpty = ['', ...pathToSegment]\n\n // Segments are keyed by searchParams (e.g. __PAGE__?{\"foo\":\"bar\"}). We might return a less specific, param-less entry,\n // so we ensure that the final tree contains the correct searchParams (reflected in the URL) are provided in the updated FlightRouterState tree.\n // We only do this on the first read, as otherwise we'd be overwriting the searchParams that may have already been set\n treePatch = addSearchParamsToPageSegments(\n treePatch,\n Object.fromEntries(url.searchParams)\n )\n\n let newTree = applyRouterStatePatchToTree(\n flightSegmentPathWithLeadingEmpty,\n currentTree,\n treePatch,\n href\n )\n\n const newCache = createEmptyCacheNode()\n\n // The prefetch cache entry was aliased -- this signals that we only fill in the cache with the\n // loading state and not the actual parallel route seed data.\n if (isRootRender && seedData) {\n // Fill in the cache with the new loading / rsc data\n const rsc = seedData[1]\n const loading = seedData[3]\n newCache.loading = loading\n newCache.rsc = rsc\n\n // Construct a new tree and apply the aliased loading state for each parallel route\n fillNewTreeWithOnlyLoadingSegments(\n navigatedAt,\n newCache,\n currentCache,\n treePatch,\n seedData\n )\n } else {\n // Copy rsc for the root node of the cache.\n newCache.rsc = currentCache.rsc\n newCache.prefetchRsc = currentCache.prefetchRsc\n newCache.loading = currentCache.loading\n newCache.parallelRoutes = new Map(currentCache.parallelRoutes)\n\n // copy the loading state only into the leaf node (the part that changed)\n fillCacheWithNewSubTreeDataButOnlyLoading(\n navigatedAt,\n newCache,\n currentCache,\n normalizedFlightData\n )\n }\n\n // If we don't have an updated tree, there's no reason to update the cache, as the tree\n // dictates what cache nodes to render.\n if (newTree) {\n currentTree = newTree\n currentCache = newCache\n applied = true\n }\n\n for (const subSegment of generateSegmentsFromPatch(treePatch)) {\n const scrollableSegmentPath = [\n ...normalizedFlightData.pathToSegment,\n ...subSegment,\n ]\n // Filter out the __DEFAULT__ paths as they shouldn't be scrolled to in this case.\n if (\n scrollableSegmentPath[scrollableSegmentPath.length - 1] !==\n DEFAULT_SEGMENT_KEY\n ) {\n scrollableSegments.push(scrollableSegmentPath)\n }\n }\n }\n\n if (!applied) {\n return false\n }\n\n mutable.patchedTree = currentTree\n mutable.cache = currentCache\n mutable.canonicalUrl = href\n mutable.hashFragment = url.hash\n mutable.scrollableSegments = scrollableSegments\n\n return handleMutable(state, mutable)\n}\n\nfunction hasLoadingComponentInSeedData(seedData: CacheNodeSeedData | null) {\n if (!seedData) return false\n\n const parallelRoutes = seedData[2]\n const loading = seedData[3]\n\n if (loading) {\n return true\n }\n\n for (const key in parallelRoutes) {\n if (hasLoadingComponentInSeedData(parallelRoutes[key])) {\n return true\n }\n }\n\n return false\n}\n\nfunction fillNewTreeWithOnlyLoadingSegments(\n navigatedAt: number,\n newCache: CacheNode,\n existingCache: CacheNode,\n routerState: FlightRouterState,\n cacheNodeSeedData: CacheNodeSeedData | null\n) {\n const isLastSegment = Object.keys(routerState[1]).length === 0\n if (isLastSegment) {\n return\n }\n\n for (const key in routerState[1]) {\n const parallelRouteState = routerState[1][key]\n const segmentForParallelRoute = parallelRouteState[0]\n const cacheKey = createRouterCacheKey(segmentForParallelRoute)\n\n const parallelSeedData =\n cacheNodeSeedData !== null && cacheNodeSeedData[2][key] !== undefined\n ? cacheNodeSeedData[2][key]\n : null\n\n let newCacheNode: CacheNode\n if (parallelSeedData !== null) {\n // New data was sent from the server.\n const rsc = parallelSeedData[1]\n const loading = parallelSeedData[3]\n newCacheNode = {\n lazyData: null,\n // copy the layout but null the page segment as that's not meant to be used\n rsc: segmentForParallelRoute.includes(PAGE_SEGMENT_KEY) ? null : rsc,\n prefetchRsc: null,\n head: null,\n prefetchHead: null,\n parallelRoutes: new Map(),\n loading,\n navigatedAt,\n }\n } else {\n // No data available for this node. This will trigger a lazy fetch\n // during render.\n newCacheNode = {\n lazyData: null,\n rsc: null,\n prefetchRsc: null,\n head: null,\n prefetchHead: null,\n parallelRoutes: new Map(),\n loading: null,\n navigatedAt: -1,\n }\n }\n\n const existingParallelRoutes = newCache.parallelRoutes.get(key)\n if (existingParallelRoutes) {\n existingParallelRoutes.set(cacheKey, newCacheNode)\n } else {\n newCache.parallelRoutes.set(key, new Map([[cacheKey, newCacheNode]]))\n }\n\n fillNewTreeWithOnlyLoadingSegments(\n navigatedAt,\n newCacheNode,\n existingCache,\n parallelRouteState,\n parallelSeedData\n )\n }\n}\n\n/**\n * Add search params to the page segments in the flight router state\n * Page segments that are associated with search params have a page segment key\n * followed by a query string. This function will add those params to the page segment.\n * This is useful if we return an aliased prefetch entry (ie, won't have search params)\n * but the canonical router URL has search params.\n */\nexport function addSearchParamsToPageSegments(\n flightRouterState: FlightRouterState,\n searchParams: Record<string, string | string[] | undefined>\n): FlightRouterState {\n const [segment, parallelRoutes, ...rest] = flightRouterState\n\n // If it's a page segment, modify the segment by adding search params\n if (segment.includes(PAGE_SEGMENT_KEY)) {\n const newSegment = addSearchParamsIfPageSegment(segment, searchParams)\n return [newSegment, parallelRoutes, ...rest]\n }\n\n // Otherwise, recurse through the parallel routes and return a new tree\n const updatedParallelRoutes: { [key: string]: FlightRouterState } = {}\n\n for (const [key, parallelRoute] of Object.entries(parallelRoutes)) {\n updatedParallelRoutes[key] = addSearchParamsToPageSegments(\n parallelRoute,\n searchParams\n )\n }\n\n return [segment, updatedParallelRoutes, ...rest]\n}\n","/**\n * Entry point to the Segment Cache implementation.\n *\n * All code related to the Segment Cache lives `segment-cache-impl` directory.\n * Callers access it through this indirection.\n *\n * This is to ensure the code is dead code eliminated from the bundle if the\n * flag is disabled.\n *\n * TODO: This is super tedious. Since experimental flags are an essential part\n * of our workflow, we should establish a better pattern for dead code\n * elimination. Ideally it would be done at the bundler level, like how React's\n * build process works. In the React repo, you don't even need to add any extra\n * configuration per experiment — if the code is not reachable, it gets stripped\n * from the build automatically by Rollup. Or, shorter term, we could stub out\n * experimental modules at build time by updating the build config, i.e. a more\n * automated version of what I'm doing manually in this file.\n */\n\nexport type { NavigationResult } from './segment-cache-impl/navigation'\nexport type { PrefetchTask } from './segment-cache-impl/scheduler'\nexport type { NormalizedSearch } from './segment-cache-impl/cache-key'\n\nconst notEnabled: any = () => {\n throw new Error(\n 'Segment Cache experiment is not enabled. This is a bug in Next.js.'\n )\n}\n\nexport const prefetch: typeof import('./segment-cache-impl/prefetch').prefetch =\n process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? function (...args) {\n return (\n require('./segment-cache-impl/prefetch') as typeof import('./segment-cache-impl/prefetch')\n ).prefetch(...args)\n }\n : notEnabled\n\nexport const navigate: typeof import('./segment-cache-impl/navigation').navigate =\n process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? function (...args) {\n return (\n require('./segment-cache-impl/navigation') as typeof import('./segment-cache-impl/navigation')\n ).navigate(...args)\n }\n : notEnabled\n\nexport const revalidateEntireCache: typeof import('./segment-cache-impl/cache').revalidateEntireCache =\n process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? function (...args) {\n return (\n require('./segment-cache-impl/cache') as typeof import('./segment-cache-impl/cache')\n ).revalidateEntireCache(...args)\n }\n : notEnabled\n\nexport const getCurrentCacheVersion: typeof import('./segment-cache-impl/cache').getCurrentCacheVersion =\n process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? function (...args) {\n return (\n require('./segment-cache-impl/cache') as typeof import('./segment-cache-impl/cache')\n ).getCurrentCacheVersion(...args)\n }\n : notEnabled\n\nexport const schedulePrefetchTask: typeof import('./segment-cache-impl/scheduler').schedulePrefetchTask =\n process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? function (...args) {\n return (\n require('./segment-cache-impl/scheduler') as typeof import('./segment-cache-impl/scheduler')\n ).schedulePrefetchTask(...args)\n }\n : notEnabled\n\nexport const cancelPrefetchTask: typeof import('./segment-cache-impl/scheduler').cancelPrefetchTask =\n process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? function (...args) {\n return (\n require('./segment-cache-impl/scheduler') as typeof import('./segment-cache-impl/scheduler')\n ).cancelPrefetchTask(...args)\n }\n : notEnabled\n\nexport const reschedulePrefetchTask: typeof import('./segment-cache-impl/scheduler').reschedulePrefetchTask =\n process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? function (...args) {\n return (\n require('./segment-cache-impl/scheduler') as typeof import('./segment-cache-impl/scheduler')\n ).reschedulePrefetchTask(...args)\n }\n : notEnabled\n\nexport const isPrefetchTaskDirty: typeof import('./segment-cache-impl/scheduler').isPrefetchTaskDirty =\n process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? function (...args) {\n return (\n require('./segment-cache-impl/scheduler') as typeof import('./segment-cache-impl/scheduler')\n ).isPrefetchTaskDirty(...args)\n }\n : notEnabled\n\nexport const createCacheKey: typeof import('./segment-cache-impl/cache-key').createCacheKey =\n process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? function (...args) {\n return (\n require('./segment-cache-impl/cache-key') as typeof import('./segment-cache-impl/cache-key')\n ).createCacheKey(...args)\n }\n : notEnabled\n\n/**\n * Below are public constants. They're small enough that we don't need to\n * DCE them.\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","import type { CacheNode } from '../../../../shared/lib/app-router-types'\nimport type {\n FlightRouterState,\n FlightSegmentPath,\n} from '../../../../shared/lib/app-router-types'\nimport { fetchServerResponse } from '../fetch-server-response'\nimport { createHrefFromUrl } from '../create-href-from-url'\nimport { invalidateCacheBelowFlightSegmentPath } from '../invalidate-cache-below-flight-segmentpath'\nimport { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'\nimport { shouldHardNavigate } from '../should-hard-navigate'\nimport { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'\nimport {\n PrefetchCacheEntryStatus,\n type Mutable,\n type NavigateAction,\n type ReadonlyReducerState,\n type ReducerState,\n} from '../router-reducer-types'\nimport { handleMutable } from '../handle-mutable'\nimport { applyFlightData } from '../apply-flight-data'\nimport { prefetchQueue } from './prefetch-reducer'\nimport { createEmptyCacheNode } from '../../app-router'\nimport { DEFAULT_SEGMENT_KEY } from '../../../../shared/lib/segment'\nimport { listenForDynamicRequest, startPPRNavigation } from '../ppr-navigations'\nimport {\n getOrCreatePrefetchCacheEntry,\n prunePrefetchCache,\n} from '../prefetch-cache-utils'\nimport { clearCacheNodeDataForSegmentPath } from '../clear-cache-node-data-for-segment-path'\nimport { handleAliasedPrefetchEntry } from '../aliased-prefetch-navigations'\nimport {\n navigate as navigateUsingSegmentCache,\n NavigationResultTag,\n type NavigationResult,\n} from '../../segment-cache'\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\nfunction triggerLazyFetchForLeafSegments(\n newCache: CacheNode,\n currentCache: CacheNode,\n flightSegmentPath: FlightSegmentPath,\n treePatch: FlightRouterState\n) {\n let appliedPatch = false\n\n newCache.rsc = currentCache.rsc\n newCache.prefetchRsc = currentCache.prefetchRsc\n newCache.loading = currentCache.loading\n newCache.parallelRoutes = new Map(currentCache.parallelRoutes)\n\n const segmentPathsToFill = generateSegmentsFromPatch(treePatch).map(\n (segment) => [...flightSegmentPath, ...segment]\n )\n\n for (const segmentPaths of segmentPathsToFill) {\n clearCacheNodeDataForSegmentPath(newCache, currentCache, segmentPaths)\n\n appliedPatch = true\n }\n\n return appliedPatch\n}\n\nfunction 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.NoOp: {\n // The server responded with no change to the current page. However, if\n // the URL changed, we still need to update that.\n const newCanonicalUrl = result.data.canonicalUrl\n mutable.canonicalUrl = newCanonicalUrl\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.Success: {\n // Received a new result.\n mutable.cache = result.data.cacheNode\n mutable.patchedTree = result.data.flightRouterState\n mutable.canonicalUrl = result.data.canonicalUrl\n mutable.scrollableSegments = result.data.scrollableSegments\n mutable.shouldScroll = result.data.shouldScroll\n mutable.hashFragment = result.data.hash\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, allowAliasing } =\n action\n const mutable: Mutable = {}\n const { hash } = url\n const href = createHrefFromUrl(url)\n const pendingPush = navigateType === 'push'\n // we want to prune the prefetch cache on every navigation to avoid it growing too large\n prunePrefetchCache(state.prefetchCache)\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 if (process.env.__NEXT_CLIENT_SEGMENT_CACHE) {\n // (Very Early Experimental Feature) Segment Cache\n //\n // Bypass the normal prefetch cache and use the new per-segment cache\n // implementation instead. This is only supported if PPR is enabled, too.\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 result = navigateUsingSegmentCache(\n url,\n state.cache,\n state.tree,\n state.nextUrl,\n shouldScroll\n )\n return handleNavigationResult(url, state, mutable, pendingPush, result)\n }\n\n const prefetchValues = getOrCreatePrefetchCacheEntry({\n url,\n nextUrl: state.nextUrl,\n tree: state.tree,\n prefetchCache: state.prefetchCache,\n allowAliasing,\n })\n const { treeAtTimeOfPrefetch, data } = prefetchValues\n\n prefetchQueue.bump(data)\n\n return data.then(\n ({ flightData, canonicalUrl: canonicalUrlOverride, postponed }) => {\n const navigatedAt = Date.now()\n\n let isFirstRead = false\n // we only want to mark this once\n if (!prefetchValues.lastUsedTime) {\n // important: we should only mark the cache node as dirty after we unsuspend from the call above\n prefetchValues.lastUsedTime = navigatedAt\n isFirstRead = true\n }\n\n if (prefetchValues.aliased) {\n // When alias is enabled, search param may not be included in the canonicalUrl.\n // But we want to set url to canonicalUrl so that we use redirected path for fetching dynamic data.\n const urlWithCanonicalPathname = new URL(url.href)\n if (canonicalUrlOverride) {\n urlWithCanonicalPathname.pathname = canonicalUrlOverride.pathname\n }\n\n const result = handleAliasedPrefetchEntry(\n navigatedAt,\n state,\n flightData,\n urlWithCanonicalPathname,\n mutable\n )\n\n // We didn't return new router state because we didn't apply the aliased entry for some reason.\n // We'll re-invoke the navigation handler but ensure that we don't attempt to use the aliased entry. This\n // will create an on-demand prefetch entry.\n if (result === false) {\n return navigateReducer(state, { ...action, allowAliasing: false })\n }\n\n return result\n }\n\n // Handle case when navigating to page in `pages` from `app`\n if (typeof flightData === 'string') {\n return handleExternalUrl(state, mutable, flightData, pendingPush)\n }\n\n const updatedCanonicalUrl = canonicalUrlOverride\n ? createHrefFromUrl(canonicalUrlOverride)\n : href\n\n const onlyHashChange =\n !!hash &&\n state.canonicalUrl.split('#', 1)[0] ===\n updatedCanonicalUrl.split('#', 1)[0]\n\n // If only the hash has changed, the server hasn't sent us any new data. We can just update\n // the mutable properties responsible for URL and scroll handling and return early.\n if (onlyHashChange) {\n mutable.onlyHashChange = true\n mutable.canonicalUrl = updatedCanonicalUrl\n mutable.shouldScroll = shouldScroll\n mutable.hashFragment = hash\n mutable.scrollableSegments = []\n return handleMutable(state, mutable)\n }\n\n let currentTree = state.tree\n let currentCache = state.cache\n let scrollableSegments: FlightSegmentPath[] = []\n for (const normalizedFlightData of flightData) {\n const {\n pathToSegment: flightSegmentPath,\n seedData,\n head,\n isHeadPartial,\n isRootRender,\n } = normalizedFlightData\n let treePatch = normalizedFlightData.tree\n\n // TODO-APP: remove ''\n const flightSegmentPathWithLeadingEmpty = ['', ...flightSegmentPath]\n\n // Create new tree based on the flightSegmentPath and router state patch\n let newTree = applyRouterStatePatchToTree(\n // TODO-APP: remove ''\n flightSegmentPathWithLeadingEmpty,\n currentTree,\n treePatch,\n href\n )\n\n // If the tree patch can't be applied to the current tree then we use the tree at time of prefetch\n // TODO-APP: This should instead fill in the missing pieces in `currentTree` with the data from `treeAtTimeOfPrefetch`, then apply the patch.\n if (newTree === null) {\n newTree = applyRouterStatePatchToTree(\n // TODO-APP: remove ''\n flightSegmentPathWithLeadingEmpty,\n treeAtTimeOfPrefetch,\n treePatch,\n href\n )\n }\n\n if (newTree !== null) {\n if (\n // This is just a paranoid check. When a route is PPRed, the server\n // will send back a static response that's rendered from\n // the root. If for some reason it doesn't, we fall back to the\n // non-PPR implementation.\n // TODO: We should get rid of the else branch and do all navigations\n // via startPPRNavigation. The current structure is just\n // an incremental step.\n seedData &&\n isRootRender &&\n postponed\n ) {\n const task = startPPRNavigation(\n navigatedAt,\n currentCache,\n currentTree,\n treePatch,\n seedData,\n head,\n isHeadPartial,\n false,\n scrollableSegments\n )\n\n if (task !== null) {\n if (task.route === null) {\n // Detected a change to the root layout. Perform an full-\n // page navigation.\n return handleExternalUrl(state, mutable, href, pendingPush)\n }\n // Use the tree computed by startPPRNavigation instead\n // of the one computed by applyRouterStatePatchToTree.\n // TODO: We should remove applyRouterStatePatchToTree\n // from the PPR path entirely.\n const patchedRouterState: FlightRouterState = task.route\n newTree = patchedRouterState\n\n const newCache = task.node\n if (newCache !== null) {\n // We've created a new Cache Node tree that contains a prefetched\n // version of the next page. This can be rendered instantly.\n mutable.cache = newCache\n }\n const dynamicRequestTree = task.dynamicRequestTree\n if (dynamicRequestTree !== null) {\n // The prefetched tree has dynamic holes in it. We initiate a\n // dynamic request to fill them in.\n //\n // Do not block on the result. We'll immediately render the Cache\n // Node tree and suspend on the dynamic parts. When the request\n // comes in, we'll fill in missing data and ping React to\n // re-render. Unlike the lazy fetching model in the non-PPR\n // implementation, this is modeled as a single React update +\n // streaming, rather than multiple top-level updates. (However,\n // even in the new model, we'll still need to sometimes update the\n // root multiple times per navigation, like if the server sends us\n // a different response than we expected. For now, we revert back\n // to the lazy fetching mechanism in that case.)\n const dynamicRequest = fetchServerResponse(\n new URL(updatedCanonicalUrl, url.origin),\n {\n flightRouterState: dynamicRequestTree,\n nextUrl: state.nextUrl,\n }\n )\n\n listenForDynamicRequest(task, dynamicRequest)\n // We store the dynamic request on the `lazyData` property of the CacheNode\n // because we're not going to await the dynamic request here. Since we're not blocking\n // on the dynamic request, `layout-router` will\n // task.node.lazyData = dynamicRequest\n } else {\n // The prefetched tree does not contain dynamic holes — it's\n // fully static. We can skip the dynamic request.\n }\n } else {\n // Nothing changed, so reuse the old cache.\n // TODO: What if the head changed but not any of the segment data?\n // Is that possible? If so, we should clone the whole tree and\n // update the head.\n newTree = treePatch\n }\n } else {\n // The static response does not include any dynamic holes, so\n // there's no need to do a second request.\n // TODO: As an incremental step this just reverts back to the\n // non-PPR implementation. We can simplify this branch further,\n // given that PPR prefetches are always static and return the whole\n // tree. Or in the meantime we could factor it out into a\n // separate function.\n\n if (isNavigatingToNewRootLayout(currentTree, newTree)) {\n return handleExternalUrl(state, mutable, href, pendingPush)\n }\n\n const cache: CacheNode = createEmptyCacheNode()\n let applied = false\n\n if (\n prefetchValues.status === PrefetchCacheEntryStatus.stale &&\n !isFirstRead\n ) {\n // When we have a stale prefetch entry, we only want to re-use the loading state of the route we're navigating to, to support instant loading navigations\n // this will trigger a lazy fetch for the actual page data by nulling the `rsc` and `prefetchRsc` values for page data,\n // while copying over the `loading` for the segment that contains the page data.\n // We only do this on subsequent reads, as otherwise there'd be no loading data to re-use.\n\n // We skip this branch if only the hash fragment has changed, as we don't want to trigger a lazy fetch in that case\n applied = triggerLazyFetchForLeafSegments(\n cache,\n currentCache,\n flightSegmentPath,\n treePatch\n )\n // since we re-used the stale cache's loading state & refreshed the data,\n // update the `lastUsedTime` so that it can continue to be re-used for the next 30s\n prefetchValues.lastUsedTime = navigatedAt\n } else {\n applied = applyFlightData(\n navigatedAt,\n currentCache,\n cache,\n normalizedFlightData,\n prefetchValues\n )\n }\n\n const hardNavigate = shouldHardNavigate(\n // TODO-APP: remove ''\n flightSegmentPathWithLeadingEmpty,\n currentTree\n )\n\n if (hardNavigate) {\n // Copy rsc for the root node of the cache.\n cache.rsc = currentCache.rsc\n cache.prefetchRsc = currentCache.prefetchRsc\n\n invalidateCacheBelowFlightSegmentPath(\n cache,\n currentCache,\n flightSegmentPath\n )\n // Ensure the existing cache value is used when the cache was not invalidated.\n mutable.cache = cache\n } else if (applied) {\n mutable.cache = cache\n // If we applied the cache, we update the \"current cache\" value so any other\n // segments in the FlightDataPath will be able to reference the updated cache.\n currentCache = cache\n }\n\n for (const subSegment of generateSegmentsFromPatch(treePatch)) {\n const scrollableSegmentPath = [\n ...flightSegmentPath,\n ...subSegment,\n ]\n // Filter out the __DEFAULT__ paths as they shouldn't be scrolled to in this case.\n if (\n scrollableSegmentPath[scrollableSegmentPath.length - 1] !==\n DEFAULT_SEGMENT_KEY\n ) {\n scrollableSegments.push(scrollableSegmentPath)\n }\n }\n }\n\n currentTree = newTree\n }\n }\n\n mutable.patchedTree = currentTree\n mutable.canonicalUrl = updatedCanonicalUrl\n mutable.scrollableSegments = scrollableSegments\n mutable.hashFragment = hash\n mutable.shouldScroll = shouldScroll\n\n return handleMutable(state, mutable)\n },\n () => state\n )\n}\n","import { createHrefFromUrl } from '../create-href-from-url'\nimport { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'\nimport { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'\nimport type {\n ServerPatchAction,\n ReducerState,\n ReadonlyReducerState,\n Mutable,\n} from '../router-reducer-types'\nimport { handleExternalUrl } from './navigate-reducer'\nimport { applyFlightData } from '../apply-flight-data'\nimport { handleMutable } from '../handle-mutable'\nimport type { CacheNode } from '../../../../shared/lib/app-router-types'\nimport { createEmptyCacheNode } from '../../app-router'\n\nexport function serverPatchReducer(\n state: ReadonlyReducerState,\n action: ServerPatchAction\n): ReducerState {\n const {\n serverResponse: { flightData, canonicalUrl: canonicalUrlOverride },\n navigatedAt,\n } = action\n\n const mutable: Mutable = {}\n\n mutable.preserveCustomHistoryState = false\n\n // Handle case when navigating to page in `pages` from `app`\n if (typeof flightData === 'string') {\n return handleExternalUrl(\n state,\n mutable,\n flightData,\n state.pushRef.pendingPush\n )\n }\n\n let currentTree = state.tree\n let currentCache = state.cache\n\n for (const normalizedFlightData of flightData) {\n const { segmentPath: flightSegmentPath, tree: treePatch } =\n normalizedFlightData\n\n const newTree = applyRouterStatePatchToTree(\n // TODO-APP: remove ''\n ['', ...flightSegmentPath],\n currentTree,\n treePatch,\n state.canonicalUrl\n )\n\n // `applyRouterStatePatchToTree` returns `null` when it determined that the server response is not applicable to the current tree.\n // In other words, the server responded with a tree that doesn't match what the client is currently rendering.\n // This can happen if the server patch action took longer to resolve than a subsequent navigation which would have changed the tree.\n // Previously this case triggered an MPA navigation but it should be safe to simply discard the server response rather than forcing\n // the entire page to reload.\n if (newTree === null) {\n return state\n }\n\n if (isNavigatingToNewRootLayout(currentTree, newTree)) {\n return handleExternalUrl(\n state,\n mutable,\n state.canonicalUrl,\n state.pushRef.pendingPush\n )\n }\n\n const canonicalUrlOverrideHref = canonicalUrlOverride\n ? createHrefFromUrl(canonicalUrlOverride)\n : undefined\n\n if (canonicalUrlOverrideHref) {\n mutable.canonicalUrl = canonicalUrlOverrideHref\n }\n\n const cache: CacheNode = createEmptyCacheNode()\n applyFlightData(navigatedAt, currentCache, cache, normalizedFlightData)\n\n mutable.patchedTree = newTree\n mutable.cache = cache\n\n currentCache = cache\n currentTree = newTree\n }\n\n return handleMutable(state, mutable)\n}\n","import { createHrefFromUrl } from '../create-href-from-url'\nimport type {\n ReadonlyReducerState,\n ReducerState,\n RestoreAction,\n} from '../router-reducer-types'\nimport { extractPathFromFlightRouterState } from '../compute-changed-path'\nimport { updateCacheNodeOnPopstateRestoration } from '../ppr-navigations'\n\nexport function restoreReducer(\n state: ReadonlyReducerState,\n action: RestoreAction\n): ReducerState {\n const { url, tree } = action\n const href = createHrefFromUrl(url)\n // This action is used to restore the router state from the history state.\n // However, it's possible that the history state no longer contains the `FlightRouterState`.\n // We will copy over the internal state on pushState/replaceState events, but if a history entry\n // occurred before hydration, or if the user navigated to a hash using a regular anchor link,\n // the history state will not contain the `FlightRouterState`.\n // In this case, we'll continue to use the existing tree so the router doesn't get into an invalid state.\n const treeToRestore = tree || state.tree\n\n const oldCache = state.cache\n const newCache = process.env.__NEXT_PPR\n ? // When PPR is enabled, we update the cache to drop the prefetch\n // data for any segment whose dynamic data was already received. This\n // prevents an unnecessary flash back to PPR state during a\n // back/forward navigation.\n updateCacheNodeOnPopstateRestoration(oldCache, treeToRestore)\n : oldCache\n\n return {\n // Set canonical url\n canonicalUrl: href,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // Ensures that the custom history state that was set is preserved when applying this update.\n preserveCustomHistoryState: true,\n },\n focusAndScrollRef: state.focusAndScrollRef,\n cache: newCache,\n prefetchCache: state.prefetchCache,\n // Restore provided tree\n tree: treeToRestore,\n nextUrl: extractPathFromFlightRouterState(treeToRestore) ?? url.pathname,\n }\n}\n","import type { FlightRouterState } from '../../../shared/lib/app-router-types'\nimport { handleExternalUrl } from './reducers/navigate-reducer'\nimport type {\n ReadonlyReducerState,\n ReducerActions,\n} from './router-reducer-types'\n\n/**\n * Handles the case where the client router attempted to patch the tree but, due to a mismatch, the patch failed.\n * This will perform an MPA navigation to return the router to a valid state.\n */\nexport function handleSegmentMismatch(\n state: ReadonlyReducerState,\n action: ReducerActions,\n treePatch: FlightRouterState\n) {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Performing hard navigation because your application experienced an unrecoverable error. If this keeps occurring, please file a Next.js issue.\\n\\n' +\n 'Reason: Segment mismatch\\n' +\n `Last Action: ${action.type}\\n\\n` +\n `Current Tree: ${JSON.stringify(state.tree)}\\n\\n` +\n `Tree Patch Payload: ${JSON.stringify(treePatch)}`\n )\n }\n\n return handleExternalUrl(state, {}, state.canonicalUrl, true)\n}\n","import type { FlightRouterState } from '../../../../shared/lib/app-router-types'\nimport { isInterceptionRouteAppPath } from '../../../../shared/lib/router/utils/interception-routes'\n\nexport function hasInterceptionRouteInCurrentTree([\n segment,\n parallelRoutes,\n]: FlightRouterState): boolean {\n // If we have a dynamic segment, it's marked as an interception route by the presence of the `i` suffix.\n if (Array.isArray(segment) && (segment[2] === 'di' || segment[2] === 'ci')) {\n return true\n }\n\n // If segment is not an array, apply the existing string-based check\n if (typeof segment === 'string' && isInterceptionRouteAppPath(segment)) {\n return true\n }\n\n // Iterate through parallelRoutes if they exist\n if (parallelRoutes) {\n for (const key in parallelRoutes) {\n if (hasInterceptionRouteInCurrentTree(parallelRoutes[key])) {\n return true\n }\n }\n }\n\n return false\n}\n","import { fetchServerResponse } from '../fetch-server-response'\nimport { createHrefFromUrl } from '../create-href-from-url'\nimport { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'\nimport { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'\nimport type {\n Mutable,\n ReadonlyReducerState,\n ReducerState,\n RefreshAction,\n} from '../router-reducer-types'\nimport { handleExternalUrl } from './navigate-reducer'\nimport { handleMutable } from '../handle-mutable'\nimport type { CacheNode } from '../../../../shared/lib/app-router-types'\nimport { fillLazyItemsTillLeafWithHead } from '../fill-lazy-items-till-leaf-with-head'\nimport { createEmptyCacheNode } from '../../app-router'\nimport { handleSegmentMismatch } from '../handle-segment-mismatch'\nimport { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'\nimport { refreshInactiveParallelSegments } from '../refetch-inactive-parallel-segments'\nimport { revalidateEntireCache } from '../../segment-cache'\n\nexport function refreshReducer(\n state: ReadonlyReducerState,\n action: RefreshAction\n): ReducerState {\n const { origin } = action\n const mutable: Mutable = {}\n const href = state.canonicalUrl\n\n let currentTree = state.tree\n\n mutable.preserveCustomHistoryState = false\n\n const cache: CacheNode = createEmptyCacheNode()\n\n // If the current tree was intercepted, the nextUrl should be included in the request.\n // This is to ensure that the refresh request doesn't get intercepted, accidentally triggering the interception route.\n const includeNextUrl = hasInterceptionRouteInCurrentTree(state.tree)\n\n // TODO-APP: verify that `href` is not an external url.\n // Fetch data from the root of the tree.\n cache.lazyData = fetchServerResponse(new URL(href, origin), {\n flightRouterState: [\n currentTree[0],\n currentTree[1],\n currentTree[2],\n 'refetch',\n ],\n nextUrl: includeNextUrl ? state.nextUrl : null,\n })\n\n const navigatedAt = Date.now()\n return cache.lazyData.then(\n async ({ flightData, canonicalUrl: canonicalUrlOverride }) => {\n // Handle case when navigating to page in `pages` from `app`\n if (typeof flightData === 'string') {\n return handleExternalUrl(\n state,\n mutable,\n flightData,\n state.pushRef.pendingPush\n )\n }\n\n // Remove cache.lazyData as it has been resolved at this point.\n cache.lazyData = null\n\n for (const normalizedFlightData of flightData) {\n const {\n tree: treePatch,\n seedData: cacheNodeSeedData,\n head,\n isRootRender,\n } = normalizedFlightData\n\n if (!isRootRender) {\n // TODO-APP: handle this case better\n console.log('REFRESH FAILED')\n return state\n }\n\n const newTree = applyRouterStatePatchToTree(\n // TODO-APP: remove ''\n [''],\n currentTree,\n treePatch,\n state.canonicalUrl\n )\n\n if (newTree === null) {\n return handleSegmentMismatch(state, action, treePatch)\n }\n\n if (isNavigatingToNewRootLayout(currentTree, newTree)) {\n return handleExternalUrl(\n state,\n mutable,\n href,\n state.pushRef.pendingPush\n )\n }\n\n const canonicalUrlOverrideHref = canonicalUrlOverride\n ? createHrefFromUrl(canonicalUrlOverride)\n : undefined\n\n if (canonicalUrlOverride) {\n mutable.canonicalUrl = canonicalUrlOverrideHref\n }\n\n // Handles case where prefetch only returns the router tree patch without rendered components.\n if (cacheNodeSeedData !== null) {\n const rsc = cacheNodeSeedData[1]\n const loading = cacheNodeSeedData[3]\n cache.rsc = rsc\n cache.prefetchRsc = null\n cache.loading = loading\n fillLazyItemsTillLeafWithHead(\n navigatedAt,\n cache,\n // Existing cache is not passed in as `router.refresh()` has to invalidate the entire cache.\n undefined,\n treePatch,\n cacheNodeSeedData,\n head,\n undefined\n )\n if (process.env.__NEXT_CLIENT_SEGMENT_CACHE) {\n revalidateEntireCache(state.nextUrl, newTree)\n } else {\n mutable.prefetchCache = new Map()\n }\n }\n\n await refreshInactiveParallelSegments({\n navigatedAt,\n state,\n updatedTree: newTree,\n updatedCache: cache,\n includeNextUrl,\n canonicalUrl: mutable.canonicalUrl || state.canonicalUrl,\n })\n\n mutable.cache = cache\n mutable.patchedTree = newTree\n\n currentTree = newTree\n }\n\n return handleMutable(state, mutable)\n },\n () => state\n )\n}\n","import { fetchServerResponse } from '../fetch-server-response'\nimport { createHrefFromUrl } from '../create-href-from-url'\nimport { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'\nimport { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'\nimport type {\n ReadonlyReducerState,\n ReducerState,\n HmrRefreshAction,\n Mutable,\n} from '../router-reducer-types'\nimport { handleExternalUrl } from './navigate-reducer'\nimport { handleMutable } from '../handle-mutable'\nimport { applyFlightData } from '../apply-flight-data'\nimport type { CacheNode } from '../../../../shared/lib/app-router-types'\nimport { createEmptyCacheNode } from '../../app-router'\nimport { handleSegmentMismatch } from '../handle-segment-mismatch'\nimport { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'\n\n// A version of refresh reducer that keeps the cache around instead of wiping all of it.\nfunction hmrRefreshReducerImpl(\n state: ReadonlyReducerState,\n action: HmrRefreshAction\n): ReducerState {\n const { origin } = action\n const mutable: Mutable = {}\n const href = state.canonicalUrl\n\n mutable.preserveCustomHistoryState = false\n\n const cache: CacheNode = createEmptyCacheNode()\n // If the current tree was intercepted, the nextUrl should be included in the request.\n // This is to ensure that the refresh request doesn't get intercepted, accidentally triggering the interception route.\n const includeNextUrl = hasInterceptionRouteInCurrentTree(state.tree)\n\n // TODO-APP: verify that `href` is not an external url.\n // Fetch data from the root of the tree.\n const navigatedAt = Date.now()\n cache.lazyData = fetchServerResponse(new URL(href, origin), {\n flightRouterState: [state.tree[0], state.tree[1], state.tree[2], 'refetch'],\n nextUrl: includeNextUrl ? state.nextUrl : null,\n isHmrRefresh: true,\n })\n\n return cache.lazyData.then(\n ({ flightData, canonicalUrl: canonicalUrlOverride }) => {\n // Handle case when navigating to page in `pages` from `app`\n if (typeof flightData === 'string') {\n return handleExternalUrl(\n state,\n mutable,\n flightData,\n state.pushRef.pendingPush\n )\n }\n\n // Remove cache.lazyData as it has been resolved at this point.\n cache.lazyData = null\n\n let currentTree = state.tree\n let currentCache = state.cache\n\n for (const normalizedFlightData of flightData) {\n const { tree: treePatch, isRootRender } = normalizedFlightData\n if (!isRootRender) {\n // TODO-APP: handle this case better\n console.log('REFRESH FAILED')\n return state\n }\n\n const newTree = applyRouterStatePatchToTree(\n // TODO-APP: remove ''\n [''],\n currentTree,\n treePatch,\n state.canonicalUrl\n )\n\n if (newTree === null) {\n return handleSegmentMismatch(state, action, treePatch)\n }\n\n if (isNavigatingToNewRootLayout(currentTree, newTree)) {\n return handleExternalUrl(\n state,\n mutable,\n href,\n state.pushRef.pendingPush\n )\n }\n\n const canonicalUrlOverrideHref = canonicalUrlOverride\n ? createHrefFromUrl(canonicalUrlOverride)\n : undefined\n\n if (canonicalUrlOverride) {\n mutable.canonicalUrl = canonicalUrlOverrideHref\n }\n const applied = applyFlightData(\n navigatedAt,\n currentCache,\n cache,\n normalizedFlightData\n )\n\n if (applied) {\n mutable.cache = cache\n currentCache = cache\n }\n\n mutable.patchedTree = newTree\n mutable.canonicalUrl = href\n\n currentTree = newTree\n }\n return handleMutable(state, mutable)\n },\n () => state\n )\n}\n\nfunction hmrRefreshReducerNoop(\n state: ReadonlyReducerState,\n _action: HmrRefreshAction\n): ReducerState {\n return state\n}\n\nexport const hmrRefreshReducer =\n process.env.NODE_ENV === 'production'\n ? hmrRefreshReducerNoop\n : hmrRefreshReducerImpl\n","import { addBasePath } from './add-base-path'\n\n/**\n * Function to correctly assign location to URL\n *\n * The method will add basePath, and will also correctly add location (including if it is a relative path)\n * @param location Location that should be added to the url\n * @param url Base URL to which the location should be assigned\n */\nexport function assignLocation(location: string, url: URL): URL {\n if (location.startsWith('.')) {\n const urlBase = url.origin + url.pathname\n return new URL(\n // In order for a relative path to be added to the current url correctly, the current url must end with a slash\n // new URL('./relative', 'https://example.com/subdir').href -> 'https://example.com/relative'\n // new URL('./relative', 'https://example.com/subdir/').href -> 'https://example.com/subdir/relative'\n (urlBase.endsWith('/') ? urlBase : urlBase + '/') + location\n )\n }\n\n return new URL(addBasePath(location), url.href)\n}\n","export interface ServerReferenceInfo {\n type: 'server-action' | 'use-cache'\n usedArgs: [boolean, boolean, boolean, boolean, boolean, boolean]\n hasRestArgs: boolean\n}\n\n/**\n * Extracts info about the server reference for the given server reference ID by\n * parsing the first byte of the hex-encoded ID.\n *\n * ```\n * Bit positions: [7] [6] [5] [4] [3] [2] [1] [0]\n * Bits: typeBit argMask restArgs\n * ```\n *\n * If the `typeBit` is `1` the server reference represents a `\"use cache\"`\n * function, otherwise a server action.\n *\n * The `argMask` encodes whether the function uses the argument at the\n * respective position.\n *\n * The `restArgs` bit indicates whether the function uses a rest parameter. It's\n * also set to 1 if the function has more than 6 args.\n *\n * @param id hex-encoded server reference ID\n */\nexport function extractInfoFromServerReferenceId(\n id: string\n): ServerReferenceInfo {\n const infoByte = parseInt(id.slice(0, 2), 16)\n const typeBit = (infoByte >> 7) & 0x1\n const argMask = (infoByte >> 1) & 0x3f\n const restArgs = infoByte & 0x1\n const usedArgs = Array(6)\n\n for (let index = 0; index < 6; index++) {\n const bitPosition = 5 - index\n const bit = (argMask >> bitPosition) & 0x1\n usedArgs[index] = bit === 1\n }\n\n return {\n type: typeBit === 1 ? 'use-cache' : 'server-action',\n usedArgs: usedArgs as [\n boolean,\n boolean,\n boolean,\n boolean,\n boolean,\n boolean,\n ],\n hasRestArgs: restArgs === 1,\n }\n}\n\n/**\n * Creates a sparse array containing only the used arguments based on the\n * provided action info.\n */\nexport function omitUnusedArgs(\n args: unknown[],\n info: ServerReferenceInfo\n): unknown[] {\n const filteredArgs = new Array(args.length)\n\n for (let index = 0; index < args.length; index++) {\n if (\n (index < 6 && info.usedArgs[index]) ||\n // This assumes that the server reference info byte has the restArgs bit\n // set to 1 if there are more than 6 args.\n (index >= 6 && info.hasRestArgs)\n ) {\n filteredArgs[index] = args[index]\n }\n }\n\n return filteredArgs\n}\n","import type {\n ActionFlightResponse,\n ActionResult,\n} from '../../../../shared/lib/app-router-types'\nimport { callServer } from '../../../app-call-server'\nimport { findSourceMapURL } from '../../../app-find-source-map-url'\nimport {\n ACTION_HEADER,\n NEXT_ACTION_NOT_FOUND_HEADER,\n NEXT_IS_PRERENDER_HEADER,\n NEXT_HTML_REQUEST_ID_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_URL,\n RSC_CONTENT_TYPE_HEADER,\n} from '../../app-router-headers'\nimport { UnrecognizedActionError } from '../../unrecognized-action-error'\n\n// TODO: Explicitly import from client.browser\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n createFromFetch as createFromFetchBrowser,\n createTemporaryReferenceSet,\n encodeReply,\n} from 'react-server-dom-webpack/client'\n\nimport {\n PrefetchKind,\n type ReadonlyReducerState,\n type ReducerState,\n type ServerActionAction,\n type ServerActionMutable,\n} from '../router-reducer-types'\nimport { assignLocation } from '../../../assign-location'\nimport { createHrefFromUrl } from '../create-href-from-url'\nimport { handleExternalUrl } from './navigate-reducer'\nimport { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'\nimport { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'\nimport type { CacheNode } from '../../../../shared/lib/app-router-types'\nimport { handleMutable } from '../handle-mutable'\nimport { fillLazyItemsTillLeafWithHead } from '../fill-lazy-items-till-leaf-with-head'\nimport { createEmptyCacheNode } from '../../app-router'\nimport { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'\nimport { handleSegmentMismatch } from '../handle-segment-mismatch'\nimport { refreshInactiveParallelSegments } from '../refetch-inactive-parallel-segments'\nimport {\n normalizeFlightData,\n prepareFlightRouterStateForRequest,\n type NormalizedFlightData,\n} from '../../../flight-data-helpers'\nimport { getRedirectError } from '../../redirect'\nimport { RedirectType } from '../../redirect-error'\nimport { createSeededPrefetchCacheEntry } from '../prefetch-cache-utils'\nimport { removeBasePath } from '../../../remove-base-path'\nimport { hasBasePath } from '../../../has-base-path'\nimport {\n extractInfoFromServerReferenceId,\n omitUnusedArgs,\n} from '../../../../shared/lib/server-reference-info'\nimport { revalidateEntireCache } from '../../segment-cache'\n\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 (process.env.NODE_ENV !== 'production') {\n createDebugChannel = (\n require('../../../dev/debug-channel') as typeof import('../../../dev/debug-channel')\n ).createDebugChannel\n}\n\ntype FetchServerActionResult = {\n redirectLocation: URL | undefined\n redirectType: RedirectType | undefined\n actionResult: ActionResult | undefined\n actionFlightData: NormalizedFlightData[] | string | undefined\n isPrerender: boolean\n revalidatedParts: {\n tag: boolean\n cookie: boolean\n paths: string[]\n }\n}\n\nasync function fetchServerAction(\n state: ReadonlyReducerState,\n nextUrl: ReadonlyReducerState['nextUrl'],\n { actionId, actionArgs }: ServerActionAction\n): Promise<FetchServerActionResult> {\n const temporaryReferences = createTemporaryReferenceSet()\n const info = extractInfoFromServerReferenceId(actionId)\n\n // TODO: Currently, we're only omitting unused args for the experimental \"use\n // cache\" functions. Once the server reference info byte feature is stable, we\n // should apply this to server actions as well.\n const usedArgs =\n info.type === 'use-cache' ? omitUnusedArgs(actionArgs, info) : actionArgs\n\n const body = await encodeReply(usedArgs, { temporaryReferences })\n\n const headers: Record<string, string> = {\n Accept: RSC_CONTENT_TYPE_HEADER,\n [ACTION_HEADER]: actionId,\n [NEXT_ROUTER_STATE_TREE_HEADER]: prepareFlightRouterStateForRequest(\n state.tree\n ),\n }\n\n if (process.env.NEXT_DEPLOYMENT_ID) {\n headers['x-deployment-id'] = process.env.NEXT_DEPLOYMENT_ID\n }\n\n if (nextUrl) {\n headers[NEXT_URL] = nextUrl\n }\n\n if (process.env.NODE_ENV !== 'production' && self.__next_r) {\n headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r\n }\n\n const res = await fetch(state.canonicalUrl, { method: 'POST', headers, body })\n\n // Handle server actions that the server didn't recognize.\n const unrecognizedActionHeader = res.headers.get(NEXT_ACTION_NOT_FOUND_HEADER)\n if (unrecognizedActionHeader === '1') {\n throw new UnrecognizedActionError(\n `Server Action \"${actionId}\" was not found on the server. \\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`\n )\n }\n\n const redirectHeader = res.headers.get('x-action-redirect')\n const [location, _redirectType] = redirectHeader?.split(';') || []\n let redirectType: RedirectType | undefined\n switch (_redirectType) {\n case 'push':\n redirectType = RedirectType.push\n break\n case 'replace':\n redirectType = RedirectType.replace\n break\n default:\n redirectType = undefined\n }\n\n const isPrerender = !!res.headers.get(NEXT_IS_PRERENDER_HEADER)\n let revalidatedParts: FetchServerActionResult['revalidatedParts']\n try {\n const revalidatedHeader = JSON.parse(\n res.headers.get('x-action-revalidated') || '[[],0,0]'\n )\n revalidatedParts = {\n paths: revalidatedHeader[0] || [],\n tag: !!revalidatedHeader[1],\n cookie: revalidatedHeader[2],\n }\n } catch (e) {\n revalidatedParts = NO_REVALIDATED_PARTS\n }\n\n const redirectLocation = location\n ? assignLocation(\n location,\n new URL(state.canonicalUrl, window.location.href)\n )\n : undefined\n\n const contentType = res.headers.get('content-type')\n const isRscResponse = !!(\n contentType && contentType.startsWith(RSC_CONTENT_TYPE_HEADER)\n )\n\n // Handle invalid server action responses.\n // A valid response must have `content-type: text/x-component`, unless it's an external redirect.\n // (external redirects have an 'x-action-redirect' header, but the body is an empty 'text/plain')\n if (!isRscResponse && !redirectLocation) {\n // The server can respond with a text/plain error message, but we'll fallback to something generic\n // if there isn't one.\n const message =\n res.status >= 400 && contentType === 'text/plain'\n ? await res.text()\n : 'An unexpected response was received from the server.'\n\n throw new Error(message)\n }\n\n let actionResult: FetchServerActionResult['actionResult']\n let actionFlightData: FetchServerActionResult['actionFlightData']\n\n if (isRscResponse) {\n const response: ActionFlightResponse = await createFromFetch(\n Promise.resolve(res),\n {\n callServer,\n findSourceMapURL,\n temporaryReferences,\n debugChannel: createDebugChannel && createDebugChannel(res.headers),\n }\n )\n\n // An internal redirect can send an RSC response, but does not have a useful `actionResult`.\n actionResult = redirectLocation ? undefined : response.a\n actionFlightData = normalizeFlightData(response.f)\n } else {\n // An external redirect doesn't contain RSC data.\n actionResult = undefined\n actionFlightData = undefined\n }\n\n return {\n actionResult,\n actionFlightData,\n redirectLocation,\n redirectType,\n revalidatedParts,\n isPrerender,\n }\n}\n\nconst NO_REVALIDATED_PARTS = {\n paths: [],\n tag: false,\n cookie: false,\n}\n\n/*\n * This reducer is responsible for calling the server action and processing any side-effects from the server action.\n * It does not mutate the state by itself but rather delegates to other reducers to do the actual mutation.\n */\nexport function serverActionReducer(\n state: ReadonlyReducerState,\n action: ServerActionAction\n): ReducerState {\n const { resolve, reject } = action\n const mutable: ServerActionMutable = {}\n\n let currentTree = state.tree\n\n mutable.preserveCustomHistoryState = false\n\n // only pass along the `nextUrl` param (used for interception routes) if the current route was intercepted.\n // If the route has been intercepted, the action should be as well.\n // Otherwise the server action might be intercepted with the wrong action id\n // (ie, one that corresponds with the intercepted route)\n const nextUrl =\n state.nextUrl && hasInterceptionRouteInCurrentTree(state.tree)\n ? state.nextUrl\n : null\n\n const navigatedAt = Date.now()\n\n return fetchServerAction(state, nextUrl, action).then(\n async ({\n actionResult,\n actionFlightData: flightData,\n redirectLocation,\n redirectType,\n isPrerender,\n revalidatedParts,\n }) => {\n let redirectHref: string | undefined\n\n // honor the redirect type instead of defaulting to push in case of server actions.\n if (redirectLocation) {\n if (redirectType === RedirectType.replace) {\n state.pushRef.pendingPush = false\n mutable.pendingPush = false\n } else {\n state.pushRef.pendingPush = true\n mutable.pendingPush = true\n }\n\n redirectHref = createHrefFromUrl(redirectLocation, false)\n mutable.canonicalUrl = redirectHref\n }\n\n if (!flightData) {\n resolve(actionResult)\n\n // If there is a redirect but no flight data we need to do a mpaNavigation.\n if (redirectLocation) {\n return handleExternalUrl(\n state,\n mutable,\n redirectLocation.href,\n state.pushRef.pendingPush\n )\n }\n return state\n }\n\n if (typeof flightData === 'string') {\n // Handle case when navigating to page in `pages` from `app`\n resolve(actionResult)\n\n return handleExternalUrl(\n state,\n mutable,\n flightData,\n state.pushRef.pendingPush\n )\n }\n\n const actionRevalidated =\n revalidatedParts.paths.length > 0 ||\n revalidatedParts.tag ||\n revalidatedParts.cookie\n\n // Store whether this action triggered any revalidation\n // The action queue will use this information to potentially\n // trigger a refresh action if the action was discarded\n // (ie, due to a navigation, before the action completed)\n if (actionRevalidated) {\n action.didRevalidate = true\n }\n\n for (const normalizedFlightData of flightData) {\n const {\n tree: treePatch,\n seedData: cacheNodeSeedData,\n head,\n isRootRender,\n } = normalizedFlightData\n\n if (!isRootRender) {\n // TODO-APP: handle this case better\n console.log('SERVER ACTION APPLY FAILED')\n resolve(actionResult)\n\n return state\n }\n\n // Given the path can only have two items the items are only the router state and rsc for the root.\n const newTree = applyRouterStatePatchToTree(\n // TODO-APP: remove ''\n [''],\n currentTree,\n treePatch,\n redirectHref ? redirectHref : state.canonicalUrl\n )\n\n if (newTree === null) {\n resolve(actionResult)\n\n return handleSegmentMismatch(state, action, treePatch)\n }\n\n if (isNavigatingToNewRootLayout(currentTree, newTree)) {\n resolve(actionResult)\n\n return handleExternalUrl(\n state,\n mutable,\n redirectHref || state.canonicalUrl,\n state.pushRef.pendingPush\n )\n }\n\n // The server sent back RSC data for the server action, so we need to apply it to the cache.\n if (cacheNodeSeedData !== null) {\n const rsc = cacheNodeSeedData[1]\n const cache: CacheNode = createEmptyCacheNode()\n cache.rsc = rsc\n cache.prefetchRsc = null\n cache.loading = cacheNodeSeedData[3]\n fillLazyItemsTillLeafWithHead(\n navigatedAt,\n cache,\n // Existing cache is not passed in as server actions have to invalidate the entire cache.\n undefined,\n treePatch,\n cacheNodeSeedData,\n head,\n undefined\n )\n\n mutable.cache = cache\n if (process.env.__NEXT_CLIENT_SEGMENT_CACHE) {\n revalidateEntireCache(state.nextUrl, newTree)\n } else {\n mutable.prefetchCache = new Map()\n }\n if (actionRevalidated) {\n await refreshInactiveParallelSegments({\n navigatedAt,\n state,\n updatedTree: newTree,\n updatedCache: cache,\n includeNextUrl: Boolean(nextUrl),\n canonicalUrl: mutable.canonicalUrl || state.canonicalUrl,\n })\n }\n }\n\n mutable.patchedTree = newTree\n currentTree = newTree\n }\n\n if (redirectLocation && redirectHref) {\n if (!process.env.__NEXT_CLIENT_SEGMENT_CACHE && !actionRevalidated) {\n // Because the RedirectBoundary will trigger a navigation, we need to seed the prefetch cache\n // with the FlightData that we got from the server action for the target page, so that it's\n // available when the page is navigated to and doesn't need to be re-fetched.\n // We only do this if the server action didn't revalidate any data, as in that case the\n // client cache will be cleared and the data will be re-fetched anyway.\n // NOTE: We don't do this in the Segment Cache implementation.\n // Dynamic data should never be placed into the cache, unless it's\n // \"converted\" to static data using <Link prefetch={true}>. What we\n // do instead is re-prefetch links and forms whenever the cache is\n // invalidated.\n createSeededPrefetchCacheEntry({\n url: redirectLocation,\n data: {\n flightData,\n canonicalUrl: undefined,\n couldBeIntercepted: false,\n prerendered: false,\n postponed: false,\n // TODO: We should be able to set this if the server action\n // returned a fully static response.\n staleTime: -1,\n },\n tree: state.tree,\n prefetchCache: state.prefetchCache,\n nextUrl: state.nextUrl,\n kind: isPrerender ? PrefetchKind.FULL : PrefetchKind.AUTO,\n })\n mutable.prefetchCache = state.prefetchCache\n }\n\n // If the action triggered a redirect, the action promise will be rejected with\n // a redirect so that it's handled by RedirectBoundary as we won't have a valid\n // action result to resolve the promise with. This will effectively reset the state of\n // the component that called the action as the error boundary will remount the tree.\n // The status code doesn't matter here as the action handler will have already sent\n // a response with the correct status code.\n reject(\n getRedirectError(\n hasBasePath(redirectHref)\n ? removeBasePath(redirectHref)\n : redirectHref,\n redirectType || RedirectType.push\n )\n )\n } else {\n resolve(actionResult)\n }\n\n return handleMutable(state, mutable)\n },\n (e: any) => {\n // When the server action is rejected we don't update the state and instead call the reject handler of the promise.\n reject(e)\n\n return state\n }\n )\n}\n","import {\n ACTION_NAVIGATE,\n ACTION_SERVER_PATCH,\n ACTION_RESTORE,\n ACTION_REFRESH,\n ACTION_PREFETCH,\n ACTION_HMR_REFRESH,\n ACTION_SERVER_ACTION,\n} from './router-reducer-types'\nimport type {\n ReducerActions,\n ReducerState,\n ReadonlyReducerState,\n} from './router-reducer-types'\nimport { navigateReducer } from './reducers/navigate-reducer'\nimport { serverPatchReducer } from './reducers/server-patch-reducer'\nimport { restoreReducer } from './reducers/restore-reducer'\nimport { refreshReducer } from './reducers/refresh-reducer'\nimport { prefetchReducer } from './reducers/prefetch-reducer'\nimport { hmrRefreshReducer } from './reducers/hmr-refresh-reducer'\nimport { serverActionReducer } from './reducers/server-action-reducer'\n\n/**\n * Reducer that handles the app-router state updates.\n */\nfunction clientReducer(\n state: ReadonlyReducerState,\n action: ReducerActions\n): ReducerState {\n switch (action.type) {\n case ACTION_NAVIGATE: {\n return navigateReducer(state, action)\n }\n case ACTION_SERVER_PATCH: {\n return serverPatchReducer(state, action)\n }\n case ACTION_RESTORE: {\n return restoreReducer(state, action)\n }\n case ACTION_REFRESH: {\n return refreshReducer(state, action)\n }\n case ACTION_HMR_REFRESH: {\n return hmrRefreshReducer(state, action)\n }\n case ACTION_PREFETCH: {\n return prefetchReducer(state, action)\n }\n case ACTION_SERVER_ACTION: {\n return serverActionReducer(state, action)\n }\n // This case should never be hit as dispatch is strongly typed.\n default:\n throw new Error('Unknown action')\n }\n}\n\nfunction serverReducer(\n state: ReadonlyReducerState,\n _action: ReducerActions\n): ReducerState {\n return state\n}\n\n// we don't run the client reducer on the server, so we use a noop function for better tree shaking\nexport const reducer =\n typeof window === 'undefined' ? serverReducer : clientReducer\n","import {\n type AppRouterState,\n type ReducerActions,\n type ReducerState,\n ACTION_REFRESH,\n ACTION_SERVER_ACTION,\n ACTION_NAVIGATE,\n ACTION_RESTORE,\n type NavigateAction,\n ACTION_HMR_REFRESH,\n PrefetchKind,\n ACTION_PREFETCH,\n} from './router-reducer/router-reducer-types'\nimport { reducer } from './router-reducer/router-reducer'\nimport { startTransition } from 'react'\nimport { isThenable } from '../../shared/lib/is-thenable'\nimport {\n FetchStrategy,\n prefetch as prefetchWithSegmentCache,\n type PrefetchTaskFetchStrategy,\n} from './segment-cache'\nimport { dispatchAppRouterAction } from './use-action-queue'\nimport { addBasePath } from '../add-base-path'\nimport { createPrefetchURL, isExternalURL } from './app-router'\nimport { prefetchReducer } from './router-reducer/reducers/prefetch-reducer'\nimport type {\n AppRouterInstance,\n NavigateOptions,\n PrefetchOptions,\n} from '../../shared/lib/app-router-context.shared-runtime'\nimport { setLinkForCurrentNavigation, type LinkInstance } from './links'\nimport type { FlightRouterState } from '../../shared/lib/app-router-types'\nimport type { ClientInstrumentationHooks } from '../app-index'\nimport type { GlobalErrorComponent } from './builtin/global-error'\n\nexport type DispatchStatePromise = React.Dispatch<ReducerState>\n\nexport type AppRouterActionQueue = {\n state: AppRouterState\n dispatch: (payload: ReducerActions, setState: DispatchStatePromise) => void\n action: (state: AppRouterState, action: ReducerActions) => ReducerState\n\n onRouterTransitionStart:\n | ((url: string, type: 'push' | 'replace' | 'traverse') => void)\n | null\n\n pending: ActionQueueNode | null\n needsRefresh?: boolean\n last: ActionQueueNode | null\n}\n\nexport type GlobalErrorState = [\n GlobalError: GlobalErrorComponent,\n styles: React.ReactNode,\n]\n\nexport type ActionQueueNode = {\n payload: ReducerActions\n next: ActionQueueNode | null\n resolve: (value: ReducerState) => void\n reject: (err: Error) => void\n discarded?: boolean\n}\n\nfunction runRemainingActions(\n actionQueue: AppRouterActionQueue,\n setState: DispatchStatePromise\n) {\n if (actionQueue.pending !== null) {\n actionQueue.pending = actionQueue.pending.next\n if (actionQueue.pending !== null) {\n runAction({\n actionQueue,\n action: actionQueue.pending,\n setState,\n })\n }\n } else {\n // Check for refresh when pending is already null\n // This handles the case where a discarded server action completes\n // after the navigation has already finished and the queue is empty\n if (actionQueue.needsRefresh) {\n actionQueue.needsRefresh = false\n actionQueue.dispatch(\n {\n type: ACTION_REFRESH,\n origin: window.location.origin,\n },\n setState\n )\n }\n }\n}\n\nasync function runAction({\n actionQueue,\n action,\n setState,\n}: {\n actionQueue: AppRouterActionQueue\n action: ActionQueueNode\n setState: DispatchStatePromise\n}) {\n const prevState = actionQueue.state\n\n actionQueue.pending = action\n\n const payload = action.payload\n const actionResult = actionQueue.action(prevState, payload)\n\n function handleResult(nextState: AppRouterState) {\n // if we discarded this action, the state should also be discarded\n if (action.discarded) {\n // Check if the discarded server action revalidated data\n if (\n action.payload.type === ACTION_SERVER_ACTION &&\n action.payload.didRevalidate\n ) {\n // The server action was discarded but it revalidated data,\n // mark that we need to refresh after all actions complete\n actionQueue.needsRefresh = true\n }\n // Still need to run remaining actions even for discarded actions\n // to potentially trigger the refresh\n runRemainingActions(actionQueue, setState)\n return\n }\n\n actionQueue.state = nextState\n\n runRemainingActions(actionQueue, setState)\n action.resolve(nextState)\n }\n\n // if the action is a promise, set up a callback to resolve it\n if (isThenable(actionResult)) {\n actionResult.then(handleResult, (err) => {\n runRemainingActions(actionQueue, setState)\n action.reject(err)\n })\n } else {\n handleResult(actionResult)\n }\n}\n\nfunction dispatchAction(\n actionQueue: AppRouterActionQueue,\n payload: ReducerActions,\n setState: DispatchStatePromise\n) {\n let resolvers: {\n resolve: (value: ReducerState) => void\n reject: (reason: any) => void\n } = { resolve: setState, reject: () => {} }\n\n // most of the action types are async with the exception of restore\n // it's important that restore is handled quickly since it's fired on the popstate event\n // and we don't want to add any delay on a back/forward nav\n // this only creates a promise for the async actions\n if (payload.type !== ACTION_RESTORE) {\n // Create the promise and assign the resolvers to the object.\n const deferredPromise = new Promise<AppRouterState>((resolve, reject) => {\n resolvers = { resolve, reject }\n })\n\n startTransition(() => {\n // we immediately notify React of the pending promise -- the resolver is attached to the action node\n // and will be called when the associated action promise resolves\n setState(deferredPromise)\n })\n }\n\n const newAction: ActionQueueNode = {\n payload,\n next: null,\n resolve: resolvers.resolve,\n reject: resolvers.reject,\n }\n\n // Check if the queue is empty\n if (actionQueue.pending === null) {\n // The queue is empty, so add the action and start it immediately\n // Mark this action as the last in the queue\n actionQueue.last = newAction\n\n runAction({\n actionQueue,\n action: newAction,\n setState,\n })\n } else if (\n payload.type === ACTION_NAVIGATE ||\n payload.type === ACTION_RESTORE\n ) {\n // Navigations (including back/forward) take priority over any pending actions.\n // Mark the pending action as discarded (so the state is never applied) and start the navigation action immediately.\n actionQueue.pending.discarded = true\n\n // The rest of the current queue should still execute after this navigation.\n // (Note that it can't contain any earlier navigations, because we always put those into `actionQueue.pending` by calling `runAction`)\n newAction.next = actionQueue.pending.next\n\n runAction({\n actionQueue,\n action: newAction,\n setState,\n })\n } else {\n // The queue is not empty, so add the action to the end of the queue\n // It will be started by runRemainingActions after the previous action finishes\n if (actionQueue.last !== null) {\n actionQueue.last.next = newAction\n }\n actionQueue.last = newAction\n }\n}\n\nlet globalActionQueue: AppRouterActionQueue | null = null\n\nexport function createMutableActionQueue(\n initialState: AppRouterState,\n instrumentationHooks: ClientInstrumentationHooks | null\n): AppRouterActionQueue {\n const actionQueue: AppRouterActionQueue = {\n state: initialState,\n dispatch: (payload: ReducerActions, setState: DispatchStatePromise) =>\n dispatchAction(actionQueue, payload, setState),\n action: async (state: AppRouterState, action: ReducerActions) => {\n const result = reducer(state, action)\n return result\n },\n pending: null,\n last: null,\n onRouterTransitionStart:\n instrumentationHooks !== null &&\n typeof instrumentationHooks.onRouterTransitionStart === 'function'\n ? // This profiling hook will be called at the start of every navigation.\n instrumentationHooks.onRouterTransitionStart\n : null,\n }\n\n if (typeof window !== 'undefined') {\n // The action queue is lazily created on hydration, but after that point\n // it doesn't change. So we can store it in a global rather than pass\n // it around everywhere via props/context.\n if (globalActionQueue !== null) {\n throw new Error(\n 'Internal Next.js Error: createMutableActionQueue was called more ' +\n 'than once'\n )\n }\n globalActionQueue = actionQueue\n }\n\n return actionQueue\n}\n\nexport function getCurrentAppRouterState(): AppRouterState | null {\n return globalActionQueue !== null ? globalActionQueue.state : null\n}\n\nfunction getAppRouterActionQueue(): AppRouterActionQueue {\n if (globalActionQueue === null) {\n throw new Error(\n 'Internal Next.js error: Router action dispatched before initialization.'\n )\n }\n return globalActionQueue\n}\n\nfunction getProfilingHookForOnNavigationStart() {\n if (globalActionQueue !== null) {\n return globalActionQueue.onRouterTransitionStart\n }\n return null\n}\n\nexport function dispatchNavigateAction(\n href: string,\n navigateType: NavigateAction['navigateType'],\n shouldScroll: boolean,\n linkInstanceRef: LinkInstance | null\n): void {\n // TODO: This stuff could just go into the reducer. Leaving as-is for now\n // since we're about to rewrite all the router reducer stuff anyway.\n const url = new URL(addBasePath(href), location.href)\n if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {\n window.next.__pendingUrl = url\n }\n\n setLinkForCurrentNavigation(linkInstanceRef)\n\n const onRouterTransitionStart = getProfilingHookForOnNavigationStart()\n if (onRouterTransitionStart !== null) {\n onRouterTransitionStart(href, navigateType)\n }\n\n dispatchAppRouterAction({\n type: ACTION_NAVIGATE,\n url,\n isExternalUrl: isExternalURL(url),\n locationSearch: location.search,\n shouldScroll,\n navigateType,\n allowAliasing: true,\n })\n}\n\nexport function dispatchTraverseAction(\n href: string,\n tree: FlightRouterState | undefined\n) {\n const onRouterTransitionStart = getProfilingHookForOnNavigationStart()\n if (onRouterTransitionStart !== null) {\n onRouterTransitionStart(href, 'traverse')\n }\n dispatchAppRouterAction({\n type: ACTION_RESTORE,\n url: new URL(href),\n tree,\n })\n}\n\n/**\n * The app router that is exposed through `useRouter`. These are public API\n * methods. Internal Next.js code should call the lower level methods directly\n * (although there's lots of existing code that doesn't do that).\n */\nexport const publicAppRouterInstance: AppRouterInstance = {\n back: () => window.history.back(),\n forward: () => window.history.forward(),\n prefetch: process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? // Unlike the old implementation, the Segment Cache doesn't store its\n // data in the router reducer state; it writes into a global mutable\n // cache. So we don't need to dispatch an action.\n (href: string, options?: PrefetchOptions) => {\n const actionQueue = getAppRouterActionQueue()\n const prefetchKind = options?.kind ?? PrefetchKind.AUTO\n\n // We don't currently offer a way to issue a runtime prefetch via `router.prefetch()`.\n // This will be possible when we update its API to not take a PrefetchKind.\n let fetchStrategy: PrefetchTaskFetchStrategy\n switch (prefetchKind) {\n case PrefetchKind.AUTO: {\n // We default to PPR. We'll discover whether or not the route supports it with the initial prefetch.\n fetchStrategy = FetchStrategy.PPR\n break\n }\n case PrefetchKind.FULL: {\n fetchStrategy = FetchStrategy.Full\n break\n }\n case PrefetchKind.TEMPORARY: {\n // This concept doesn't exist in the segment cache implementation.\n return\n }\n default: {\n prefetchKind satisfies never\n // Despite typescript thinking that this can't happen,\n // we might get an unexpected value from user code.\n // We don't know what they want, but we know they want a prefetch,\n // so use the default.\n fetchStrategy = FetchStrategy.PPR\n }\n }\n\n prefetchWithSegmentCache(\n href,\n actionQueue.state.nextUrl,\n actionQueue.state.tree,\n fetchStrategy,\n options?.onInvalidate ?? null\n )\n }\n : (href: string, options?: PrefetchOptions) => {\n // Use the old prefetch implementation.\n const actionQueue = getAppRouterActionQueue()\n const url = createPrefetchURL(href)\n if (url !== null) {\n // The prefetch reducer doesn't actually update any state or\n // trigger a rerender. It just writes to a mutable cache. So we\n // shouldn't bother calling setState/dispatch; we can just re-run\n // the reducer directly using the current state.\n // TODO: Refactor this away from a \"reducer\" so it's\n // less confusing.\n prefetchReducer(actionQueue.state, {\n type: ACTION_PREFETCH,\n url,\n kind: options?.kind ?? PrefetchKind.FULL,\n })\n }\n },\n replace: (href: string, options?: NavigateOptions) => {\n startTransition(() => {\n dispatchNavigateAction(href, 'replace', options?.scroll ?? true, null)\n })\n },\n push: (href: string, options?: NavigateOptions) => {\n startTransition(() => {\n dispatchNavigateAction(href, 'push', options?.scroll ?? true, null)\n })\n },\n refresh: () => {\n startTransition(() => {\n dispatchAppRouterAction({\n type: ACTION_REFRESH,\n origin: window.location.origin,\n })\n })\n },\n hmrRefresh: () => {\n if (process.env.NODE_ENV !== 'development') {\n throw new Error(\n 'hmrRefresh can only be used in development mode. Please use refresh instead.'\n )\n } else {\n startTransition(() => {\n dispatchAppRouterAction({\n type: ACTION_HMR_REFRESH,\n origin: window.location.origin,\n })\n })\n }\n },\n}\n\n// Exists for debugging purposes. Don't use in application code.\nif (typeof window !== 'undefined' && window.next) {\n window.next.router = publicAppRouterInstance\n}\n","import type { FlightRouterState } from '../../shared/lib/app-router-types'\nimport type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime'\nimport { getCurrentAppRouterState } from './app-router-instance'\nimport { createPrefetchURL } from './app-router'\nimport {\n FetchStrategy,\n isPrefetchTaskDirty,\n type PrefetchTaskFetchStrategy,\n} from './segment-cache'\nimport { createCacheKey } from './segment-cache'\nimport {\n type PrefetchTask,\n PrefetchPriority,\n schedulePrefetchTask as scheduleSegmentPrefetchTask,\n cancelPrefetchTask,\n reschedulePrefetchTask,\n} from './segment-cache'\nimport { startTransition } from 'react'\nimport { PrefetchKind } from './router-reducer/router-reducer-types'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\ntype Element = HTMLAnchorElement | 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 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}\n\nexport function mountLinkInstance(\n element: HTMLAnchorElement,\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,\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 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 if (!process.env.__NEXT_CLIENT_SEGMENT_CACHE) {\n // The old prefetch implementation does not have different priority levels.\n // Just schedule a new prefetch task.\n prefetchWithOldCacheImplementation(instance)\n return\n }\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\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\nfunction prefetchWithOldCacheImplementation(instance: PrefetchableInstance) {\n // This is the path used when the Segment Cache is not enabled.\n if (typeof window === 'undefined') {\n return\n }\n\n const doPrefetch = async () => {\n // note that `appRouter.prefetch()` is currently sync,\n // so we have to wrap this call in an async function to be able to catch() errors below.\n\n let prefetchKind: PrefetchKind\n switch (instance.fetchStrategy) {\n case FetchStrategy.PPR: {\n prefetchKind = PrefetchKind.AUTO\n break\n }\n case FetchStrategy.Full: {\n prefetchKind = PrefetchKind.FULL\n break\n }\n case FetchStrategy.PPRRuntime: {\n // We can only get here if Client Segment Cache is off, and in that case\n // it shouldn't be possible for a link to request a runtime prefetch.\n throw new InvariantError(\n 'FetchStrategy.PPRRuntime should never be used when `experimental.clientSegmentCache` is disabled'\n )\n }\n default: {\n instance.fetchStrategy satisfies never\n // Unreachable, but otherwise typescript will consider the variable unassigned\n prefetchKind = undefined!\n }\n }\n\n return instance.router.prefetch(instance.prefetchHref, {\n kind: prefetchKind,\n })\n }\n\n // Prefetch the page if asked (only in the client)\n // We need to handle a prefetch error here since we may be\n // loading with priority which can reject but we don't\n // want to force navigation since this is only a prefetch\n doPrefetch().catch((err) => {\n if (process.env.NODE_ENV !== 'production') {\n // rethrow to show invalid URL errors\n throw err\n }\n })\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","'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 { dispatchNavigateAction } from '../components/app-router-instance'\nimport {\n FetchStrategy,\n type PrefetchTaskFetchStrategy,\n} from '../components/segment-cache'\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 * 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 | 'unstable_forceStale'\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 * 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<HTMLAnchorElement>): boolean {\n const eventTarget = event.currentTarget\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<HTMLAnchorElement>,\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 (isModifiedEvent(e) || e.currentTarget.hasAttribute('download')) {\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 React.startTransition(() => {\n dispatchNavigateAction(\n as || href,\n replace ? 'replace' : 'push',\n scroll ?? true,\n linkInstanceRef.current\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 const linkInstanceRef = useRef<LinkInstance | null>(null)\n\n const {\n href: hrefProp,\n as: asProp,\n children,\n prefetch: prefetchProp = null,\n replace,\n shallow,\n scroll,\n onClick,\n onMouseEnter: onMouseEnterProp,\n onTouchStart: onTouchStartProp,\n onNavigate,\n ref: forwardedRef,\n unstable_dynamicOnHover,\n ...restProps\n } = props\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 // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 prefetch: true,\n unstable_dynamicOnHover: true,\n onClick: true,\n onMouseEnter: true,\n onTouchStart: 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 === '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 props[key] !== 'unstable_forceStale'\n ) {\n throw createPropError({\n key,\n expected: '`boolean | \"auto\" | \"unstable_forceStale\"`',\n actual: valType,\n })\n }\n } else {\n // TypeScript trick for type-guarding:\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 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>.\\nLearn more: https://nextjs.org/docs/messages/invalid-new-link-with-extra-anchor'\n )\n }\n }\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) => {\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, forwardedRef)\n\n const anchorProps: React.DetailedHTMLProps<\n React.AnchorHTMLAttributes<HTMLAnchorElement>,\n HTMLAnchorElement\n > = {\n ref: mergedRef,\n onClick(e) {\n if (typeof onClick === 'function') {\n onClick(e)\n }\n\n if (!router) {\n return\n }\n\n if (e.defaultPrevented) {\n return\n }\n\n linkClicked(e, href, as, linkInstanceRef, replace, scroll, onNavigate)\n },\n onMouseEnter(e) {\n if (typeof onMouseEnterProp === 'function') {\n onMouseEnterProp(e)\n }\n\n if (!router) {\n return\n }\n\n if (!prefetchEnabled || process.env.NODE_ENV === 'development') {\n return\n }\n\n const upgradeToDynamicPrefetch = unstable_dynamicOnHover === true\n onNavigationIntent(e.currentTarget, upgradeToDynamicPrefetch)\n },\n onTouchStart: process.env.__NEXT_LINK_NO_TOUCH_START\n ? undefined\n : function onTouchStart(e) {\n if (typeof onTouchStartProp === 'function') {\n onTouchStartProp(e)\n }\n\n if (!router) {\n return\n }\n\n if (!prefetchEnabled) {\n return\n }\n\n const upgradeToDynamicPrefetch = unstable_dynamicOnHover === true\n onNavigationIntent(e.currentTarget, upgradeToDynamicPrefetch)\n },\n }\n\n // If the url is absolute, we can bypass the logic to prepend the basePath.\n if (isAbsoluteUrl(as)) {\n anchorProps.href = as\n } else {\n anchorProps.href = addBasePath(as)\n }\n\n return (\n <LinkStatusContext.Provider value={linkStatus}>\n <a {...restProps} {...anchorProps}>\n {children}\n </a>\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 (\n process.env.__NEXT_CACHE_COMPONENTS &&\n process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ) {\n // In the new implementation:\n // - `prefetch={true}` is a runtime prefetch\n // (includes cached IO + params + cookies, with dynamic holes for uncached IO).\n // - `unstable_forceStale` is a \"full\" prefetch\n // (forces inclusion of all dynamic data, i.e. the old behavior of `prefetch={true}`)\n if (prefetchProp === true) {\n return FetchStrategy.PPRRuntime\n }\n if (prefetchProp === 'unstable_forceStale') {\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 // In `clientSegmentCache`, we default to PPR, and we'll discover whether or not the route supports it with the initial prefetch.\n // If we're not using `clientSegmentCache`, this will be converted into a `PrefetchKind.AUTO`.\n return FetchStrategy.PPR\n } else {\n return prefetchProp === null || prefetchProp === 'auto'\n ? // In `clientSegmentCache`, we default to PPR, and we'll discover whether or not the route supports it with the initial prefetch.\n // If we're not using `clientSegmentCache`, this will be converted into a `PrefetchKind.AUTO`.\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","\"use client\"\n\nimport { useEffect, useState } from \"react\"\nimport Link from \"next/link\"\n\ninterface MCPTool {\n name: string\n description: string\n category: string\n parameters: Array<{\n name: string\n type: string\n optional?: boolean\n description: string\n }>\n}\n\ninterface ToolsResponse {\n tools: MCPTool[]\n endpoint: string\n totalTools: number\n categories: string[]\n}\n\nexport default function HomePage() {\n const [tools, setTools] = useState<ToolsResponse | null>(null)\n const [loading, setLoading] = useState(true)\n\n useEffect(() => {\n fetch(\"/api/tools\")\n .then((res) => res.json())\n .then((data) => {\n setTools(data)\n setLoading(false)\n })\n .catch(() => {\n setLoading(false)\n })\n }, [])\n\n const toolsByCategory = tools?.tools.reduce((acc, tool) => {\n if (!acc[tool.category]) {\n acc[tool.category] = []\n }\n acc[tool.category].push(tool)\n return acc\n }, {} as Record<string, MCPTool[]>) || {}\n\n const categoryIcons: Record<string, string> = {\n \"Primary Debugging\": \"🚨\",\n \"Error Analysis\": \"🔍\",\n \"Monitoring\": \"⏰\",\n \"Log Analysis\": \"📊\",\n \"Browser Debugging\": \"🌐\",\n \"Browser Automation\": \"🪄\",\n \"System\": \"⚙️\"\n }\n\n return (\n <div className=\"min-h-screen bg-white\">\n {/* Header */}\n <header className=\"bg-gray-50 border-b border-gray-200\">\n <div className=\"max-w-6xl mx-auto px-4 py-6\">\n <div className=\"flex items-center justify-between\">\n <div>\n <div className=\"flex items-center gap-3 mb-2\">\n <div className=\"w-10 h-10 bg-black rounded-lg flex items-center justify-center\">\n <span className=\"text-white font-mono font-bold\">d3k</span>\n </div>\n <div>\n <h1 className=\"text-2xl font-bold text-gray-900\">dev3000 MCP Server</h1>\n <div className=\"flex items-center gap-2 mt-1\">\n <span className=\"inline-flex items-center gap-1 text-sm text-green-600 font-medium\">\n <span className=\"w-2 h-2 bg-green-500 rounded-full\"></span>\n Server Running\n </span>\n <span className=\"text-gray-300\">•</span>\n <span className=\"text-sm text-gray-600\">Port 3684</span>\n </div>\n </div>\n </div>\n </div>\n <div className=\"flex items-center gap-3\">\n <Link \n href=\"/logs\"\n className=\"inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors\"\n >\n 📊 View Logs\n </Link>\n <a\n href=\"https://github.com/vercel-labs/dev3000#setup\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"inline-flex items-center gap-2 px-4 py-2 border border-gray-300 text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-50 transition-colors\"\n >\n 📖 Setup Guide\n </a>\n </div>\n </div>\n </div>\n </header>\n\n {/* Main Content */}\n <main className=\"max-w-6xl mx-auto px-4 py-8\">\n {/* Quick Start */}\n <section className=\"mb-12\">\n <div className=\"bg-blue-50 border border-blue-200 rounded-lg p-6\">\n <h2 className=\"text-lg font-semibold text-blue-900 mb-3\">🚀 Quick Start</h2>\n <div className=\"space-y-3\">\n <div>\n <span className=\"text-sm font-medium text-blue-800\">MCP Endpoint:</span>\n <code className=\"ml-2 px-3 py-1 bg-blue-100 text-blue-800 text-sm font-mono rounded\">\n {tools?.endpoint || \"http://localhost:3684/api/mcp/mcp\"}\n </code>\n </div>\n <div className=\"text-sm text-blue-700\">\n <p className=\"mb-2\">Connect your AI tools to this MCP server for real-time development debugging:</p>\n <div className=\"flex gap-4\">\n <a href=\"https://github.com/vercel-labs/dev3000#claude-desktop\" \n target=\"_blank\" \n rel=\"noopener noreferrer\"\n className=\"text-blue-600 hover:text-blue-800 font-medium\">\n Claude Desktop Setup →\n </a>\n <a href=\"https://github.com/vercel-labs/dev3000#cursor\" \n target=\"_blank\" \n rel=\"noopener noreferrer\"\n className=\"text-blue-600 hover:text-blue-800 font-medium\">\n Cursor Setup →\n </a>\n </div>\n </div>\n </div>\n </div>\n </section>\n\n {/* Tools Documentation */}\n <section>\n <div className=\"flex items-center justify-between mb-8\">\n <div>\n <h2 className=\"text-2xl font-bold text-gray-900 mb-2\">Available Tools</h2>\n <p className=\"text-gray-600\">\n {loading \n ? \"Loading MCP tools...\" \n : `${tools?.totalTools || 0} tools across ${tools?.categories.length || 0} categories for AI-powered development debugging`\n }\n </p>\n </div>\n </div>\n\n {loading ? (\n <div className=\"text-center py-12\">\n <div className=\"inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600\"></div>\n <p className=\"mt-4 text-gray-600\">Loading tool documentation...</p>\n </div>\n ) : tools ? (\n <div className=\"space-y-8\">\n {Object.entries(toolsByCategory).map(([category, categoryTools]) => (\n <div key={category}>\n <h3 className=\"text-xl font-semibold text-gray-900 mb-4 flex items-center gap-2\">\n <span>{categoryIcons[category] || \"🔧\"}</span>\n {category}\n <span className=\"text-sm font-normal text-gray-500\">({categoryTools.length})</span>\n </h3>\n <div className=\"grid gap-4 md:grid-cols-2\">\n {categoryTools.map((tool) => (\n <div key={tool.name} className=\"border border-gray-200 rounded-lg p-5 hover:border-gray-300 transition-colors\">\n <div className=\"mb-3\">\n <h4 className=\"text-lg font-semibold text-gray-900 font-mono\">{tool.name}</h4>\n <p className=\"text-sm text-gray-600 mt-2 leading-relaxed\">\n {tool.description.replace(/🚨|⏰|🔍|🪄|📊|🌐|⚙️/g, '').trim()}\n </p>\n </div>\n {tool.parameters.length > 0 && (\n <div>\n <h5 className=\"text-sm font-medium text-gray-800 mb-2\">Parameters:</h5>\n <div className=\"space-y-1\">\n {tool.parameters.map((param) => (\n <div key={param.name} className=\"text-xs\">\n <span className=\"font-mono text-blue-600\">{param.name}</span>\n <span className=\"text-gray-500\">\n {param.optional ? \" (optional)\" : \" (required)\"}\n </span>\n <span className=\"text-gray-400\"> - {param.type}</span>\n {param.description && (\n <div className=\"text-gray-600 ml-2\">{param.description}</div>\n )}\n </div>\n ))}\n </div>\n </div>\n )}\n </div>\n ))}\n </div>\n </div>\n ))}\n </div>\n ) : (\n <div className=\"text-center py-12\">\n <p className=\"text-red-600 mb-4\">Failed to load tool documentation</p>\n <button \n onClick={() => window.location.reload()}\n className=\"px-4 py-2 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 transition-colors\"\n >\n Retry\n </button>\n </div>\n )}\n </section>\n\n {/* Magic Workflow */}\n <section className=\"mt-16 bg-gradient-to-r from-purple-50 to-blue-50 border border-purple-200 rounded-lg p-8\">\n <h2 className=\"text-xl font-semibold text-gray-900 mb-4 flex items-center gap-2\">\n 🪄 The Magic Workflow\n </h2>\n <div className=\"grid md:grid-cols-3 gap-6 text-sm\">\n <div className=\"text-center\">\n <div className=\"w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-3\">\n <span className=\"text-blue-600 font-bold\">1</span>\n </div>\n <h3 className=\"font-semibold mb-2\">AI Finds Issues</h3>\n <p className=\"text-gray-600\">Tools like debug_my_app and monitor_for_new_errors automatically detect problems</p>\n </div>\n <div className=\"text-center\">\n <div className=\"w-12 h-12 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-3\">\n <span className=\"text-purple-600 font-bold\">2</span>\n </div>\n <h3 className=\"font-semibold mb-2\">AI Fixes Code</h3>\n <p className=\"text-gray-600\">AI analyzes errors and edits your code files to resolve issues</p>\n </div>\n <div className=\"text-center\">\n <div className=\"w-12 h-12 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-3\">\n <span className=\"text-green-600 font-bold\">3</span>\n </div>\n <h3 className=\"font-semibold mb-2\">AI Verifies Fixes</h3>\n <p className=\"text-gray-600\">execute_browser_action tests the fixes in real-time with screenshots</p>\n </div>\n </div>\n </section>\n </main>\n\n {/* Footer */}\n <footer className=\"border-t border-gray-200 mt-16\">\n <div className=\"max-w-6xl mx-auto px-4 py-6\">\n <div className=\"flex items-center justify-between text-sm text-gray-600\">\n <div>\n <span className=\"font-semibold\">dev3000 MCP Server</span> - AI-powered development monitoring\n </div>\n <div className=\"flex items-center gap-6\">\n <a href=\"https://github.com/vercel-labs/dev3000\" \n target=\"_blank\" \n rel=\"noopener noreferrer\"\n className=\"hover:text-gray-900 transition-colors\">\n GitHub\n </a>\n <a href=\"https://dev3000.ai\" \n target=\"_blank\" \n rel=\"noopener noreferrer\"\n className=\"hover:text-gray-900 transition-colors\">\n Homepage\n </a>\n <Link href=\"/logs\" className=\"hover:text-gray-900 transition-colors\">\n Logs\n </Link>\n </div>\n </div>\n </div>\n </footer>\n </div>\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","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","ACTION_HMR_REFRESH","ACTION_NAVIGATE","ACTION_PREFETCH","ACTION_REFRESH","ACTION_RESTORE","ACTION_SERVER_ACTION","ACTION_SERVER_PATCH","PrefetchCacheEntryStatus","PrefetchKind","ACTION_HEADER","FLIGHT_HEADERS","NEXT_ACTION_NOT_FOUND_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","isThenable","promise","then","dispatchAppRouterAction","useActionQueue","dispatch","action","actionQueue","state","setState","React","useState","useAppDevRenderingIndicator","require","appDevRenderingIndicator","use","callServer","actionId","actionArgs","Promise","resolve","reject","startTransition","type","findSourceMapURL","filename","document","URL","getFlightDataPartsFromPath","getNextFlightSegmentPath","normalizeFlightData","prepareFlightRouterStateForRequest","flightDataPath","flightDataPathLength","tree","seedData","head","isHeadPartial","segmentPath","pathToSegment","segment","isRootRender","flightSegmentPath","flightData","map","flightRouterState","isHmrRefresh","stripClientOnlyDataFromFlightRouterState","parallelRoutes","_url","refreshMarker","isRootLayout","hasLoadingBoundary","cleanedSegment","stripSearchParamsFromPageSegment","cleanedParallelRoutes","childState","shouldPreserveRefreshMarker","PAGE_SEGMENT_KEY","Boolean","getAppBuildId","setAppBuildId","globalBuildId","buildId","djb2Hash","hexHash","str","i","char","charCodeAt","toString","computeCacheBustingSearchParam","prefetchHeader","segmentPrefetchHeader","stateTreeHeader","nextUrlHeader","setCacheBustingSearchParam","setCacheBustingSearchParamWithHash","headers","uniqueCacheKey","existingSearch","rawQuery","pairs","filter","pair","ROOT_SEGMENT_CACHE_KEY","ROOT_SEGMENT_REQUEST_KEY","appendSegmentCacheKeyPart","appendSegmentRequestKeyPart","convertSegmentPathToStaticExportFilename","createSegmentCacheKeyPart","createSegmentRequestKeyPart","safeName","encodeToFilesystemAndURLSafeString","paramType","encodedName","parentRequestKey","parallelRouteKey","childRequestKeyPart","slotKey","requestKeyPart","paramValue","safeValue","parentSegmentKey","childCacheKeyPart","simpleParamValueRegex","base64url","btoa","doesStaticSegmentAppearInURL","getCacheKeyForDynamicParam","getParamValueFromCacheKey","getRenderedPathname","getRenderedSearch","parseDynamicParamFromURLPart","urlToUrlWithoutFlightMarker","response","rewrittenQuery","get","rewrittenPath","pathnameParts","partIndex","s","DEFAULT_SEGMENT_KEY","renderedSearch","pageSegmentWithSearchParams","addSearchParamsIfPageSegment","fromEntries","urlWithoutFlightParameters","__NEXT_CONFIG_OUTPUT","paramCacheKey","isCatchAll","createFetch","createFromNextReadableStream","fetchServerResponse","createFromReadableStream","createFromReadableStreamBrowser","createDebugChannel","doMpaNavigation","canonicalUrl","couldBeIntercepted","prerendered","postponed","staleTime","abortController","AbortController","addEventListener","abort","options","nextUrl","prefetchKind","AUTO","fetchPriority","TEMPORARY","signal","responseUrl","redirected","contentType","interception","staleTimeHeaderSeconds","parseInt","isFlightResponse","ok","body","TURBOPACK","waitForWebpackRuntimeHotUpdate","flightStream","createUnclosingPrefetchStream","b","f","S","err","aborted","__NEXT_TEST_MODE","NEXT_DEPLOYMENT_ID","self","__next_r","fetchOptions","credentials","priority","fetchUrl","browserResponse","fetch","__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS","MAX_REDIRECTS","n","rscResponse","status","responseHeaders","debugChannel","originalFlightStream","reader","getReader","ReadableStream","pull","controller","done","read","enqueue","createHrefFromUrl","includeHash","createRouterCacheKey","withoutSearchParameters","invalidateCacheBelowFlightSegmentPath","newCache","existingCache","isLastEntry","cacheKey","existingChildSegmentMap","childSegmentMap","Map","existingChildCacheNode","childCacheNode","lazyData","rsc","prefetchRsc","prefetchHead","matchSegment","existingSegment","fillLazyItemsTillLeafWithHead","navigatedAt","routerState","cacheNodeSeedData","prefetchEntry","isLastSegment","parallelRouteState","segmentForParallelRoute","parallelSeedData","existingParallelRoutesCacheNode","hasReusablePrefetch","kind","reusable","parallelRouteCacheNode","existingCacheNode","newCacheNode","seedNode","loading","existingParallelRoutes","invalidateCacheByRouterState","fillCacheWithNewSubTreeData","fillCacheWithNewSubTreeDataButOnlyLoading","fillCacheHelper","fillLazyItems","treePatch","incomingSegment","applyFlightData","cache","addRefreshMarkerToActiveParallelSegments","refreshInactiveParallelSegments","fetchedSegments","Set","refreshInactiveParallelSegmentsImpl","rootTree","updatedTree","updatedCache","includeNextUrl","refetchPath","refetchMarker","fetchPromises","has","add","fetchPromise","parallelFetchPromise","all","applyRouterStatePatchToTree","applyPatch","initialTree","patchTree","initialSegment","initialParallelRoutes","patchSegment","patchParallelRoutes","newParallelRoutes","isInPatchTreeParallelRoutes","refetch","currentSegment","lastSegment","parallelRoutePatch","shouldHardNavigate","isNavigatingToNewRootLayout","currentTree","nextTree","currentTreeSegment","nextTreeSegment","currentTreeChild","values","nextTreeChild","ensureLeadingSlash","normalizeAppPath","normalizeRscURL","reduce","index","segments","isGroupSegment","INTERCEPTION_ROUTE_MARKERS","extractInterceptionRouteInformation","isInterceptionRouteAppPath","find","m","interceptingRoute","marker","interceptedRoute","concat","splitInterceptingRoute","computeChangedPath","extractPathFromFlightRouterState","getSelectedParams","removeLeadingSlash","segmentToPathname","normalizeSegments","acc","some","childrenPath","children","childPath","computeChangedPathImpl","treeA","treeB","segmentA","parallelRoutesA","segmentB","parallelRoutesB","normalizedSegmentA","normalizedSegmentB","parallelRouterKey","changedPath","params","parallelRoute","isDynamicParameter","segmentValue","handleMutable","isNotUndefined","mutable","shouldScroll","patchedTree","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","apply","scrollableSegments","onlyHashChange","hashFragment","decodeURIComponent","segmentPaths","prefetchCache","PromiseQueue","promiseFn","taskResolve","taskReject","taskPromise","task","enqueueResult","bump","findIndex","bumpedItem","splice","unshift","maxConcurrency","forced","shift","DYNAMIC_STALETIME_MS","STATIC_STALETIME_MS","createSeededPrefetchCacheEntry","getOrCreatePrefetchCacheEntry","prunePrefetchCache","INTERCEPTION_CACHE_KEY_MARKER","createPrefetchCacheKeyImpl","includeSearchParams","pathnameFromUrl","createPrefetchCacheKey","FULL","getExistingCacheEntry","allowAliasing","maybeNextUrl","cacheKeyWithParams","cacheKeyWithoutParams","cacheKeyToUse","existingEntry","isAliased","aliased","entryWithoutParams","cacheEntry","existingCacheEntry","getPrefetchEntryCacheStatus","switchedToFullPrefetch","data","prefetchResponse","isFullPrefetch","createLazyPrefetchEntry","prefixExistingPrefetchCacheEntry","existingCacheKey","newCacheKey","prefetchCacheKey","treeAtTimeOfPrefetch","prefetchTime","Date","now","lastUsedTime","fresh","prefetchQueue","prefetchCacheEntry","expired","Number","__NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME","__NEXT_CLIENT_ROUTER_STATIC_STALETIME","stale","prefetchReducer","__NEXT_CLIENT_SEGMENT_CACHE","identityReducerWhenSegmentCacheIsEnabled","prefetchReducerImpl","HTML_LIMITED_BOT_UA_RE","HTML_LIMITED_BOT_UA_RE_STRING","getBotType","isBot","HEADLESS_BROWSER_BOT_UA_RE","source","isDomBotUA","userAgent","isHtmlLimitedBotUA","AppRouterAnnouncer","ANNOUNCER_TYPE","ANNOUNCER_ID","getAnnouncerNode","existingAnnouncer","getElementsByName","shadowRoot","childNodes","container","createElement","style","cssText","announcer","ariaLive","id","role","shadow","attachShadow","mode","appendChild","portalNode","setPortalNode","useEffect","getElementsByTagName","isConnected","removeChild","routeAnnouncement","setRouteAnnouncement","previousTitle","useRef","currentTitle","title","pageHeader","querySelector","innerText","textContent","current","createPortal","RedirectBoundary","RedirectErrorBoundary","HandleRedirect","redirect","reset","redirectType","router","useRouter","RedirectType","getDerivedStateFromError","isRedirectError","getURLFromRedirectError","getRedirectTypeFromError","render","findHeadInCache","findHeadInCacheImpl","keyPrefix","keyPrefixWithoutSearchParams","isLastItem","parallelRoutesKeys","childParallelRoutes","cacheKeyWithoutSearchParams","cacheNode","unresolvedThenable","pathHasPrefix","hasBasePath","removeBasePath","handleHardNavError","useNavFailureHandler","next","__pendingUrl","__NEXT_APP_NAV_FAIL_HANDLING","uncaughtExceptionHandler","evt","reason","removeEventListener","GracefulDegradeBoundary","getDomNodeAttributes","node","attributes","attr","_","hasError","componentDidMount","htmlNode","htmlRef","htmlAttributes","setAttribute","rootHtml","documentElement","innerHTML","html","ref","suppressHydrationWarning","dangerouslySetInnerHTML","__html","createRef","useUntrackedPathname","hasFallbackRouteParams","workUnitAsyncStorage","workUnitStore","getStore","fallbackParams","fallbackRouteParams","size","useContext","PathnameContext","ErrorBoundary","ErrorBoundaryHandler","isBotUserAgent","navigator","isNextRouterError","getDerivedStateFromProps","previousPathname","HandleISRError","errorStyles","errorScripts","this","errorComponent","RootErrorBoundary","MetadataBoundary","OutletBoundary","RootLayoutBoundary","ViewportBoundary","NameSpace","METADATA_BOUNDARY_NAME","VIEWPORT_BOUNDARY_NAME","OUTLET_BOUNDARY_NAME","ROOT_LAYOUT_BOUNDARY_NAME","createEmptyCacheNode","createPrefetchURL","AppRouter","isExternalURL","globalMutable","HistoryUpdater","appRouterState","useInsertionEffect","historyState","history","__NA","__PRIVATE_NEXTJS_INTERNALS_TREE","pushState","replaceState","pingVisibleLinks","copyNextJsInternalHistoryState","currentState","Head","headCacheNode","resolvedPrefetchRsc","useDeferredValue","Router","globalError","webSocket","staticIndicatorState","useMemo","nd","publicAppRouterInstance","handlePageShow","event","persisted","pendingMpaPath","handleUnhandledRedirect","preventDefault","originalPushState","bind","originalReplaceState","applyUrlFromHistoryPushReplace","_unused","_N","onPopState","reload","dispatchTraverseAction","matchingHead","pathParams","layoutRouterContext","parentTree","parentCacheNode","parentSegmentPath","globalLayoutRouterContext","headKey","headKeyWithoutSearchParams","content","DevRootHTTPAccessFallbackBoundary","HotReloader","default","RuntimeStyles","PathParamsContext","Provider","SearchParamsContext","GlobalLayoutRouterContext","AppRouterContext","LayoutRouterContext","globalErrorState","DefaultGlobalError","runtimeStyles","runtimeStyleChanged","globalThis","_N_E_STYLE_LOAD","len","cb","forceUpdate","renderedStylesSize","changed","c","dplId","link","rel","precedence","abortTask","listenForDynamicRequest","startPPRNavigation","updateCacheNodeOnPopstateRestoration","MPA_NAVIGATION_TASK","dynamicRequestTree","oldCacheNode","oldRouterState","newRouterState","prefetchData","isPrefetchHeadPartial","isSamePageNavigation","scrollableSegmentsResult","updateCacheNodeOnNavigation","didFindRootLayout","oldRouterStateChildren","newRouterStateChildren","prefetchDataChildren","oldParallelRoutes","prefetchParallelRoutes","patchedRouterStateChildren","taskChildren","needsDynamicRequest","dynamicRequestTreeChildren","newRouterStateChild","oldRouterStateChild","oldSegmentMapChild","prefetchDataChild","newSegmentChild","newSegmentPathChild","newSegmentKeyChild","oldSegmentChild","oldCacheNodeChild","taskChild","spawnReusedTask","beginRenderingNewRouteTree","newCacheNodeChild","newSegmentMapChild","taskChildRoute","dynamicRequestTreeChild","patchRouterStateWithNewChildren","possiblyPartialPrefetchHead","createCacheNodeOnNavigation","routerStateChildren","isLeafSegment","cacheNodeNavigatedAt","isPrefetchRscPartial","spawnPendingTask","existingCacheNodeChildren","cacheNodeChildren","routerStateChild","existingSegmentMapChild","segmentChild","segmentPathChild","segmentKeyChild","existingCacheNodeChild","baseRouterState","newChildren","clone","newTask","createPendingCacheNode","reusedRouterState","responsePromise","normalizedFlightData","serverRouterState","dynamicData","dynamicHead","writeDynamicDataIntoPendingTask","rootTask","taskSegment","finishTaskUsingDynamicDataPayload","taskNode","finishPendingCacheNode","serverChildren","dynamicDataChildren","serverRouterStateChild","dynamicDataChild","maybePrefetchRsc","createDeferredRsc","taskState","serverState","taskStateChildren","serverStateChildren","dataChildren","taskStateChild","serverStateChild","dataChild","segmentMapChild","taskSegmentChild","taskSegmentKeyChild","cacheNodeChild","abortPendingCacheNode","dynamicSegmentData","isDeferredRsc","dynamicLoading","shouldUsePrefetch","DEFERRED","Symbol","tag","pendingRsc","rej","fulfilledRsc","rejectedRsc","clearCacheNodeDataForSegmentPath","addSearchParamsToPageSegments","handleAliasedPrefetchEntry","currentCache","applied","hasLoadingComponentInSeedData","flightSegmentPathWithLeadingEmpty","newTree","fillNewTreeWithOnlyLoadingSegments","subSegment","generateSegmentsFromPatch","scrollableSegmentPath","rest","newSegment","updatedParallelRoutes","FetchStrategy","NavigationResultTag","PrefetchPriority","cancelPrefetchTask","createCacheKey","getCurrentCacheVersion","isPrefetchTaskDirty","navigate","prefetch","reschedulePrefetchTask","revalidateEntireCache","schedulePrefetchTask","notEnabled","handleExternalUrl","navigateReducer","flightRouterPatch","childSegment","triggerLazyFetchForLeafSegments","appliedPatch","segmentPathsToFill","handleNavigationResult","MPA","newUrl","NoOp","newCanonicalUrl","oldUrl","Success","Async","asyncResult","isExternalUrl","navigateType","getElementById","navigateUsingSegmentCache","prefetchValues","canonicalUrlOverride","isFirstRead","urlWithCanonicalPathname","updatedCanonicalUrl","patchedRouterState","dynamicRequest","hardNavigate","serverPatchReducer","serverResponse","canonicalUrlOverrideHref","restoreReducer","treeToRestore","oldCache","__NEXT_PPR","handleSegmentMismatch","hasInterceptionRouteInCurrentTree","refreshReducer","log","hmrRefreshReducer","hmrRefreshReducerImpl","hmrRefreshReducerNoop","_action","assignLocation","urlBase","extractInfoFromServerReferenceId","omitUnusedArgs","infoByte","typeBit","argMask","restArgs","usedArgs","bitPosition","bit","hasRestArgs","info","filteredArgs","serverActionReducer","createFromFetch","createFromFetchBrowser","fetchServerAction","temporaryReferences","createTemporaryReferenceSet","encodeReply","Accept","unrecognizedActionHeader","UnrecognizedActionError","redirectHeader","_redirectType","isPrerender","revalidatedParts","revalidatedHeader","parse","paths","cookie","e","NO_REVALIDATED_PARTS","redirectLocation","isRscResponse","text","actionResult","actionFlightData","a","redirectHref","actionRevalidated","didRevalidate","getRedirectError","reducer","clientReducer","serverReducer","createMutableActionQueue","dispatchNavigateAction","getCurrentAppRouterState","runRemainingActions","pending","runAction","needsRefresh","prevState","payload","handleResult","nextState","discarded","dispatchAction","resolvers","deferredPromise","newAction","last","globalActionQueue","initialState","instrumentationHooks","onRouterTransitionStart","getAppRouterActionQueue","getProfilingHookForOnNavigationStart","linkInstanceRef","setLinkForCurrentNavigation","locationSearch","back","forward","fetchStrategy","PPR","Full","prefetchWithSegmentCache","onInvalidate","scroll","refresh","hmrRefresh","IDLE_LINK_STATUS","PENDING_LINK_STATUS","mountFormInstance","mountLinkInstance","onLinkVisibilityChanged","onNavigationIntent","unmountLinkForCurrentNavigation","unmountPrefetchableInstance","linkForMostRecentNavigation","setOptimisticLinkStatus","prefetchable","WeakMap","prefetchableAndVisible","observer","IntersectionObserver","handleIntersect","rootMargin","observeVisibility","element","instance","existingInstance","observe","coercePrefetchableUrl","reportErrorFn","reportError","prefetchEnabled","prefetchURL","isVisible","prefetchTask","prefetchHref","unobserve","entry","intersectionRatio","rescheduleLinkPrefetch","Default","unstable_upgradeToDynamicPrefetch","__NEXT_DYNAMIC_ON_HOVER","Intent","existingPrefetchTask","prefetchWithOldCacheImplementation","scheduleSegmentPrefetchTask","doPrefetch","PPRRuntime","InvariantError","catch","isLocalURL","locationOrigin","resolved","LinkComponent","useLinkStatus","isModifiedEvent","eventTarget","currentTarget","getAttribute","metaKey","ctrlKey","shiftKey","altKey","nativeEvent","which","linkClicked","as","onNavigate","hasAttribute","isDefaultPrevented","formatStringOrUrl","urlObjOrString","linkStatus","useOptimistic","hrefProp","asProp","prefetchProp","shallow","onClick","onMouseEnter","onMouseEnterProp","onTouchStart","onTouchStartProp","forwardedRef","unstable_dynamicOnHover","restProps","getFetchStrategyFromPrefetchProp","createPropError","expected","actual","requiredPropsGuard","requiredProps","optionalPropsGuard","optionalProps","valType","locale","warnOnce","hasDynamicSegment","resolvedHref","observeLinkVisibilityOnMount","useCallback","mergedRef","useMergedRef","anchorProps","defaultPrevented","upgradeToDynamicPrefetch","__NEXT_LINK_NO_TOUCH_START","LinkStatusContext","createContext","__NEXT_CACHE_COMPONENTS"],"mappings":"6CAEO,SAASC,EACdE,CAA6B,EAE7B,IAAMC,EAAwB,CAAC,EAC/B,IAAK,GAAM,CAACC,EAAKC,EAAM,GAAIH,EAAaI,OAAO,GAAI,CACjD,IAAMC,EAAWJ,CAAK,CAACC,EAAI,AACvB,MAAoB,IAAbG,EACTJ,CAAK,CAACC,EAAI,CAAGC,EADsB,AAE1BG,MAAMC,OAAO,CAACF,GACvBA,EAASG,IAAI,CAACL,CADoB,EAGlCF,CAAK,CAACC,EAAI,CAAG,CAACG,EAAUF,EAAM,AAElC,CACA,OAAOF,CACT,CAEA,SAASQ,EAAuBC,CAAc,QAC5C,AAAqB,UAAU,AAA3B,OAAOA,EACFA,GAIW,UAAjB,EAA6B,KAAtBA,GAAuBC,MAAMD,EAAAA,GACpB,WAAjB,AACA,OADOA,EAIA,GAFAE,OAAOF,EAIlB,CAEO,SAASX,EAAuBE,CAAqB,EAC1D,IAAMD,EAAe,IAAIa,gBACzB,IAAK,GAAM,CAACX,EAAKC,EAAM,GAAIW,OAAOV,OAAO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AA,EAAA,GAAA,EAAC,EAAA,OAAI,CAAA,CAAC,KAAK,QAAQ,UAAU,iDAAwC,qBASnF","ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78]}
|
|
1
|
+
{"version":3,"sources":["turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/querystring.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/format-url.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/utils.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/parse-path.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/add-path-prefix.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/remove-trailing-slash.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/normalize-trailing-slash.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/add-base-path.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/router-reducer-types.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/app-router-headers.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/is-thenable.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/use-action-queue.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/app-call-server.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/app-find-source-map-url.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/flight-data-helpers.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/app-build-id.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/hash.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/cache-busting-search-param.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/set-cache-busting-search-param.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/segment-cache/segment-value-encoding.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/route-params.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/fetch-server-response.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/create-href-from-url.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/create-router-cache-key.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/invalidate-cache-below-flight-segmentpath.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/match-segments.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/fill-lazy-items-till-leaf-with-head.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/invalidate-cache-by-router-state.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/fill-cache-with-new-subtree-data.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/apply-flight-data.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/refetch-inactive-parallel-segments.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/apply-router-state-patch-to-tree.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/should-hard-navigate.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/is-navigating-to-new-root-layout.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/page-path/ensure-leading-slash.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/app-paths.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/interception-routes.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/compute-changed-path.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/handle-mutable.ts","turbopack:///[project]/node_modules/.pnpm/@swc+helpers@0.5.15/node_modules/@swc/helpers/cjs/_class_private_field_loose_base.cjs","turbopack:///[project]/node_modules/.pnpm/@swc+helpers@0.5.15/node_modules/@swc/helpers/cjs/_class_private_field_loose_key.cjs","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/promise-queue.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/prefetch-cache-utils.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/reducers/prefetch-reducer.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/html-bots.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/is-bot.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/app-router-announcer.tsx","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/redirect-boundary.tsx","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/reducers/find-head-in-cache.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/unresolved-thenable.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/path-has-prefix.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/has-base-path.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/remove-base-path.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/nav-failure-handler.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/errors/graceful-degrade-boundary.tsx","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/navigation-untracked.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/error-boundary.tsx","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/errors/root-error-boundary.tsx","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/lib/framework/boundary-components.tsx","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/app-router.tsx","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/ppr-navigations.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/clear-cache-node-data-for-segment-path.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/aliased-prefetch-navigations.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/segment-cache.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/reducers/navigate-reducer.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/reducers/server-patch-reducer.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/reducers/restore-reducer.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/handle-segment-mismatch.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/reducers/has-interception-route-in-current-tree.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/reducers/refresh-reducer.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/reducers/hmr-refresh-reducer.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/assign-location.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/server-reference-info.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/reducers/server-action-reducer.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/router-reducer/router-reducer.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/app-router-instance.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/components/links.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/shared/lib/router/utils/is-local-url.ts","turbopack:///[project]/node_modules/.pnpm/next@15.5.1-canary.30_babel-plugin-react-compiler@19.1.0-rc.3_react-dom@19.2.0-canary-d_5eea965284f26eb4e30482e6426df099/node_modules/next/src/client/app-dir/link.tsx","turbopack:///[project]/app/page.tsx"],"sourcesContent":["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 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 runtimeConfig?: { [key: string]: any }\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","import type { CacheNode } from '../../../shared/lib/app-router-types'\nimport type {\n FlightRouterState,\n FlightSegmentPath,\n} from '../../../shared/lib/app-router-types'\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_PREFETCH = 'prefetch'\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 canonicalUrl?: string\n scrollableSegments?: FlightSegmentPath[]\n pendingPush?: boolean\n cache?: CacheNode\n prefetchCache?: AppRouterState['prefetchCache']\n hashFragment?: string\n shouldScroll?: boolean\n preserveCustomHistoryState?: boolean\n onlyHashChange?: boolean\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 origin: Location['origin']\n}\n\nexport interface HmrRefreshAction {\n type: typeof ACTION_HMR_REFRESH\n origin: Location['origin']\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 allowAliasing: 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 tree: FlightRouterState | undefined\n}\n\n/**\n * Server-patch applies the provided Flight data to the cache and router tree.\n * - Only triggered in layout-router.\n * - Creates a new cache and router state with the Flight data applied.\n */\nexport interface ServerPatchAction {\n type: typeof ACTION_SERVER_PATCH\n navigatedAt: number\n serverResponse: FetchServerResponseResult\n previousTree: FlightRouterState\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 * - `temporary` - a temporary prefetch entry is added to the cache, this is used when prefetch={false} is used in next/link or when you push a route programmatically.\n */\n\nexport enum PrefetchKind {\n AUTO = 'auto',\n FULL = 'full',\n TEMPORARY = 'temporary',\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 */\nexport interface PrefetchAction {\n type: typeof ACTION_PREFETCH\n url: URL\n kind: PrefetchKind\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\nexport type PrefetchCacheEntry = {\n treeAtTimeOfPrefetch: FlightRouterState\n data: Promise<FetchServerResponseResult>\n kind: PrefetchKind\n prefetchTime: number\n staleTime: number\n lastUsedTime: number | null\n key: string\n status: PrefetchCacheEntryStatus\n url: URL\n}\n\nexport enum PrefetchCacheEntryStatus {\n fresh = 'fresh',\n reusable = 'reusable',\n expired = 'expired',\n stale = 'stale',\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 * Prefetched data is stored separately in `prefetchCache`, that is applied during ACTION_NAVIGATE.\n */\n cache: CacheNode\n /**\n * Cache that holds prefetched Flight responses keyed by url.\n */\n prefetchCache: Map<string, PrefetchCacheEntry>\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 /**\n * The underlying \"url\" representing the UI state, which is used for intercepting routes.\n */\n nextUrl: string | null\n}\n\nexport type ReadonlyReducerState = Readonly<AppRouterState>\nexport type ReducerState = Promise<AppRouterState> | AppRouterState\nexport type ReducerActions = Readonly<\n | RefreshAction\n | NavigateAction\n | RestoreAction\n | ServerPatchAction\n | PrefetchAction\n | HmrRefreshAction\n | ServerActionAction\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 * 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 } 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\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 return isThenable(state) ? use(state) : state\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 {\n CacheNodeSeedData,\n FlightData,\n FlightDataPath,\n FlightRouterState,\n FlightSegmentPath,\n Segment,\n HeadData,\n} from '../shared/lib/app-router-types'\nimport { PAGE_SEGMENT_KEY } from '../shared/lib/segment'\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 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","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>\nexport type SegmentCacheKeyPart = Opaque<'SegmentCacheKeyPart', string>\nexport type SegmentCacheKey = Opaque<'SegmentCacheKey', string>\n\nexport const ROOT_SEGMENT_REQUEST_KEY = '' as SegmentRequestKey\nexport const ROOT_SEGMENT_CACHE_KEY = '' as SegmentCacheKey\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\nexport function createSegmentCacheKeyPart(\n requestKeyPart: SegmentRequestKeyPart,\n segment: FlightRouterStateSegment\n): SegmentCacheKeyPart {\n if (typeof segment === 'string') {\n return requestKeyPart as any as SegmentCacheKeyPart\n }\n const paramValue = segment[1]\n const safeValue = encodeToFilesystemAndURLSafeString(paramValue)\n return (requestKeyPart + '$' + safeValue) as SegmentCacheKeyPart\n}\n\nexport function appendSegmentCacheKeyPart(\n parentSegmentKey: SegmentCacheKey,\n parallelRouteKey: string,\n childCacheKeyPart: SegmentCacheKeyPart\n): SegmentCacheKey {\n const slotKey =\n parallelRouteKey === 'children'\n ? childCacheKeyPart\n : `@${encodeToFilesystemAndURLSafeString(parallelRouteKey)}/${childCacheKeyPart}`\n return (parentSegmentKey + '/' + slotKey) as SegmentCacheKey\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 { NormalizedSearch } from './components/segment-cache'\nimport type { RSCResponse } from './components/router-reducer/fetch-server-response'\n\nexport type RouteParamValue = string | Array<string> | null\n\nexport type RouteParam = {\n name: string\n value: RouteParamValue\n type: DynamicParamTypesShort\n}\n\nexport function getRenderedSearch(response: RSCResponse): 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(response: RSCResponse): string {\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 (\n rewrittenPath ?? urlToUrlWithoutFlightMarker(new URL(response.url)).pathname\n )\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 case 'ci': {\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 // 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 case 'di': {\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 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","'use client'\n\n// TODO: Explicitly import from client.browser\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { createFromReadableStream as createFromReadableStreamBrowser } from 'react-server-dom-webpack/client'\n\nimport type {\n FlightRouterState,\n NavigationFlightResponse,\n} from '../../../shared/lib/app-router-types'\n\nimport type { NEXT_ROUTER_SEGMENT_PREFETCH_HEADER } from '../app-router-headers'\nimport {\n NEXT_ROUTER_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} from '../app-router-headers'\nimport { callServer } from '../../app-call-server'\nimport { findSourceMapURL } from '../../app-find-source-map-url'\nimport { PrefetchKind } from './router-reducer-types'\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 { urlToUrlWithoutFlightMarker } from '../../route-params'\n\nconst createFromReadableStream =\n createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream']\n\nlet createDebugChannel:\n | typeof import('../../dev/debug-channel').createDebugChannel\n | undefined\n\nif (process.env.NODE_ENV !== 'production') {\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 prefetchKind?: PrefetchKind\n readonly isHmrRefresh?: boolean\n}\n\nexport type FetchServerResponseResult = {\n flightData: NormalizedFlightData[] | string\n canonicalUrl: URL | undefined\n couldBeIntercepted: boolean\n prerendered: boolean\n postponed: boolean\n staleTime: number\n}\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}\n\nfunction doMpaNavigation(url: string): FetchServerResponseResult {\n return {\n flightData: urlToUrlWithoutFlightMarker(\n new URL(url, location.origin)\n ).toString(),\n canonicalUrl: undefined,\n couldBeIntercepted: false,\n prerendered: false,\n postponed: false,\n staleTime: -1,\n }\n}\n\nlet abortController = new AbortController()\n\nif (typeof window !== 'undefined') {\n // Abort any in-flight requests when the page is unloaded, e.g. due to\n // reloading the page or performing hard navigations. This allows us to ignore\n // what would otherwise be a thrown TypeError when the browser cancels the\n // requests.\n window.addEventListener('pagehide', () => {\n abortController.abort()\n })\n\n // Use a fresh AbortController instance on pageshow, e.g. when navigating back\n // and the JavaScript execution context is restored by the browser.\n window.addEventListener('pageshow', () => {\n abortController = new AbortController()\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, prefetchKind } = 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 /**\n * Three cases:\n * - `prefetchKind` is `undefined`, it means it's a normal navigation, so we want to prefetch the page data fully\n * - `prefetchKind` is `full` - we want to prefetch the whole page so same as above\n * - `prefetchKind` is `auto` - if the page is dynamic, prefetch the page data partially, if static prefetch the page data fully\n */\n if (prefetchKind === PrefetchKind.AUTO) {\n headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'\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 try {\n // When creating a \"temporary\" prefetch (the \"on-demand\" prefetch that gets created on navigation, if one doesn't exist)\n // we send the request with a \"high\" priority as it's in response to a user interaction that could be blocking a transition.\n // Otherwise, all other prefetches are sent with a \"low\" priority.\n // We use \"auto\" for in all other cases to match the existing default, as this function is shared outside of prefetching.\n const fetchPriority = prefetchKind\n ? prefetchKind === PrefetchKind.TEMPORARY\n ? 'high'\n : 'low'\n : 'auto'\n\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 const res = await createFetch(\n url,\n headers,\n fetchPriority,\n abortController.signal\n )\n\n const responseUrl = urlToUrlWithoutFlightMarker(new URL(res.url))\n const canonicalUrl = res.redirected ? responseUrl : undefined\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 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 // Handle the `fetch` readable stream that can be unwrapped by `React.use`.\n const flightStream = postponed\n ? createUnclosingPrefetchStream(res.body)\n : res.body\n const response = await (createFromNextReadableStream(\n flightStream,\n res.headers\n ) as Promise<NavigationFlightResponse>)\n\n if (getAppBuildId() !== response.b) {\n return doMpaNavigation(res.url)\n }\n\n return {\n flightData: normalizeFlightData(response.f),\n canonicalUrl: canonicalUrl,\n couldBeIntercepted: interception,\n prerendered: response.S,\n postponed,\n staleTime,\n }\n } catch (err) {\n if (!abortController.signal.aborted) {\n console.error(\n `Failed to fetch RSC payload for ${url}. 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 {\n flightData: url.toString(),\n canonicalUrl: undefined,\n couldBeIntercepted: false,\n prerendered: false,\n postponed: false,\n staleTime: -1,\n }\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 = {\n ok: boolean\n redirected: boolean\n headers: Headers\n body: ReadableStream<Uint8Array> | null\n status: number\n url: string\n}\n\nexport async function createFetch(\n url: URL,\n headers: RequestHeaders,\n fetchPriority: 'auto' | 'high' | 'low' | null,\n signal?: AbortSignal\n): Promise<RSCResponse> {\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 if (process.env.NEXT_DEPLOYMENT_ID) {\n headers['x-deployment-id'] = process.env.NEXT_DEPLOYMENT_ID\n }\n\n if (process.env.NODE_ENV !== 'production' && self.__next_r) {\n headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r\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 browserResponse = await fetch(fetchUrl, fetchOptions)\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 fetchUrl = new URL(responseUrl)\n setCacheBustingSearchParam(fetchUrl, headers)\n browserResponse = await fetch(fetchUrl, fetchOptions)\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 = {\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\n return rscResponse\n}\n\nexport function createFromNextReadableStream(\n flightStream: ReadableStream<Uint8Array>,\n responseHeaders: Headers\n): Promise<unknown> {\n return createFromReadableStream(flightStream, {\n callServer,\n findSourceMapURL,\n debugChannel: createDebugChannel && createDebugChannel(responseHeaders),\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","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 { 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 {\n CacheNode,\n FlightSegmentPath,\n} from '../../../shared/lib/app-router-types'\nimport { createRouterCacheKey } from './create-router-cache-key'\nimport { getNextFlightSegmentPath } from '../../flight-data-helpers'\n\n/**\n * Fill cache up to the end of the flightSegmentPath, invalidating anything below it.\n */\nexport function invalidateCacheBelowFlightSegmentPath(\n newCache: CacheNode,\n existingCache: CacheNode,\n flightSegmentPath: FlightSegmentPath\n): void {\n const isLastEntry = flightSegmentPath.length <= 2\n const [parallelRouteKey, segment] = flightSegmentPath\n\n const cacheKey = createRouterCacheKey(segment)\n\n const existingChildSegmentMap =\n existingCache.parallelRoutes.get(parallelRouteKey)\n\n if (!existingChildSegmentMap) {\n // Bailout because the existing cache does not have the path to the leaf node\n // Will trigger lazy fetch in layout-router because of missing segment\n return\n }\n\n let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey)\n if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {\n childSegmentMap = new Map(existingChildSegmentMap)\n newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap)\n }\n\n // In case of last entry don't copy further down.\n if (isLastEntry) {\n childSegmentMap.delete(cacheKey)\n return\n }\n\n const existingChildCacheNode = existingChildSegmentMap.get(cacheKey)\n let childCacheNode = childSegmentMap.get(cacheKey)\n\n if (!childCacheNode || !existingChildCacheNode) {\n // Bailout because the existing cache does not have the path to the leaf node\n // Will trigger lazy fetch in layout-router because of missing segment\n return\n }\n\n if (childCacheNode === existingChildCacheNode) {\n childCacheNode = {\n lazyData: childCacheNode.lazyData,\n rsc: childCacheNode.rsc,\n prefetchRsc: childCacheNode.prefetchRsc,\n head: childCacheNode.head,\n prefetchHead: childCacheNode.prefetchHead,\n parallelRoutes: new Map(childCacheNode.parallelRoutes),\n } as CacheNode\n childSegmentMap.set(cacheKey, childCacheNode)\n }\n\n invalidateCacheBelowFlightSegmentPath(\n childCacheNode,\n existingChildCacheNode,\n getNextFlightSegmentPath(flightSegmentPath)\n )\n}\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","import type { CacheNode } from '../../../shared/lib/app-router-types'\nimport type {\n FlightRouterState,\n CacheNodeSeedData,\n} from '../../../shared/lib/app-router-types'\nimport { createRouterCacheKey } from './create-router-cache-key'\nimport {\n PrefetchCacheEntryStatus,\n type PrefetchCacheEntry,\n} from './router-reducer-types'\n\nexport function fillLazyItemsTillLeafWithHead(\n navigatedAt: number,\n newCache: CacheNode,\n existingCache: CacheNode | undefined,\n routerState: FlightRouterState,\n cacheNodeSeedData: CacheNodeSeedData | null,\n head: React.ReactNode,\n prefetchEntry: PrefetchCacheEntry | undefined\n): void {\n const isLastSegment = Object.keys(routerState[1]).length === 0\n if (isLastSegment) {\n newCache.head = head\n return\n }\n // Remove segment that we got data for so that it is filled in during rendering of rsc.\n for (const key in routerState[1]) {\n const parallelRouteState = routerState[1][key]\n const segmentForParallelRoute = parallelRouteState[0]\n const cacheKey = createRouterCacheKey(segmentForParallelRoute)\n\n // TODO: We should traverse the cacheNodeSeedData tree instead of the router\n // state tree. Ideally, they would always be the same shape, but because of\n // the loading.js pattern, cacheNodeSeedData sometimes only represents a\n // partial tree. That's why this node is sometimes null. Once PPR lands,\n // loading.js will no longer have special behavior and we can traverse the\n // data tree instead.\n //\n // We should also consider merging the router state tree and the data tree\n // in the response format, so that we don't have to send the keys twice.\n // Then the client can convert them into separate representations.\n const parallelSeedData =\n cacheNodeSeedData !== null && cacheNodeSeedData[2][key] !== undefined\n ? cacheNodeSeedData[2][key]\n : null\n if (existingCache) {\n const existingParallelRoutesCacheNode =\n existingCache.parallelRoutes.get(key)\n if (existingParallelRoutesCacheNode) {\n const hasReusablePrefetch =\n prefetchEntry?.kind === 'auto' &&\n prefetchEntry.status === PrefetchCacheEntryStatus.reusable\n\n let parallelRouteCacheNode = new Map(existingParallelRoutesCacheNode)\n const existingCacheNode = parallelRouteCacheNode.get(cacheKey)\n let newCacheNode: CacheNode\n if (parallelSeedData !== null) {\n // New data was sent from the server.\n const seedNode = parallelSeedData[1]\n const loading = parallelSeedData[3]\n newCacheNode = {\n lazyData: null,\n rsc: seedNode,\n // This is a PPR-only field. When PPR is enabled, we shouldn't hit\n // this path during a navigation, but until PPR is fully implemented\n // yet it's possible the existing node does have a non-null\n // `prefetchRsc`. As an incremental step, we'll just de-opt to the\n // old behavior — no PPR value.\n prefetchRsc: null,\n head: null,\n prefetchHead: null,\n loading,\n parallelRoutes: new Map(existingCacheNode?.parallelRoutes),\n navigatedAt,\n }\n } else if (hasReusablePrefetch && existingCacheNode) {\n // No new data was sent from the server, but the existing cache node\n // was prefetched, so we should reuse that.\n newCacheNode = {\n lazyData: existingCacheNode.lazyData,\n rsc: existingCacheNode.rsc,\n // This is a PPR-only field. Unlike the previous branch, since we're\n // just cloning the existing cache node, we might as well keep the\n // PPR value, if it exists.\n prefetchRsc: existingCacheNode.prefetchRsc,\n head: existingCacheNode.head,\n prefetchHead: existingCacheNode.prefetchHead,\n parallelRoutes: new Map(existingCacheNode.parallelRoutes),\n loading: existingCacheNode.loading,\n } as CacheNode\n } else {\n // No data available for this node. This will trigger a lazy fetch\n // during render.\n newCacheNode = {\n lazyData: null,\n rsc: null,\n prefetchRsc: null,\n head: null,\n prefetchHead: null,\n parallelRoutes: new Map(existingCacheNode?.parallelRoutes),\n loading: null,\n navigatedAt,\n }\n }\n\n // Overrides the cache key with the new cache node.\n parallelRouteCacheNode.set(cacheKey, newCacheNode)\n // Traverse deeper to apply the head / fill lazy items till the head.\n fillLazyItemsTillLeafWithHead(\n navigatedAt,\n newCacheNode,\n existingCacheNode,\n parallelRouteState,\n parallelSeedData ? parallelSeedData : null,\n head,\n prefetchEntry\n )\n\n newCache.parallelRoutes.set(key, parallelRouteCacheNode)\n continue\n }\n }\n\n let newCacheNode: CacheNode\n if (parallelSeedData !== null) {\n // New data was sent from the server.\n const seedNode = parallelSeedData[1]\n const loading = parallelSeedData[3]\n newCacheNode = {\n lazyData: null,\n rsc: seedNode,\n prefetchRsc: null,\n head: null,\n prefetchHead: null,\n parallelRoutes: new Map(),\n loading,\n navigatedAt,\n }\n } else {\n // No data available for this node. This will trigger a lazy fetch\n // during render.\n newCacheNode = {\n lazyData: null,\n rsc: null,\n prefetchRsc: null,\n head: null,\n prefetchHead: null,\n parallelRoutes: new Map(),\n loading: null,\n navigatedAt,\n }\n }\n\n const existingParallelRoutes = newCache.parallelRoutes.get(key)\n if (existingParallelRoutes) {\n existingParallelRoutes.set(cacheKey, newCacheNode)\n } else {\n newCache.parallelRoutes.set(key, new Map([[cacheKey, newCacheNode]]))\n }\n\n fillLazyItemsTillLeafWithHead(\n navigatedAt,\n newCacheNode,\n undefined,\n parallelRouteState,\n parallelSeedData,\n head,\n prefetchEntry\n )\n }\n}\n","import type {\n CacheNode,\n FlightRouterState,\n} from '../../../shared/lib/app-router-types'\nimport { createRouterCacheKey } from './create-router-cache-key'\n\n/**\n * Invalidate cache one level down from the router state.\n */\nexport function invalidateCacheByRouterState(\n newCache: CacheNode,\n existingCache: CacheNode,\n routerState: FlightRouterState\n): void {\n // Remove segment that we got data for so that it is filled in during rendering of rsc.\n for (const key in routerState[1]) {\n const segmentForParallelRoute = routerState[1][key][0]\n const cacheKey = createRouterCacheKey(segmentForParallelRoute)\n const existingParallelRoutesCacheNode =\n existingCache.parallelRoutes.get(key)\n if (existingParallelRoutesCacheNode) {\n let parallelRouteCacheNode = new Map(existingParallelRoutesCacheNode)\n parallelRouteCacheNode.delete(cacheKey)\n newCache.parallelRoutes.set(key, parallelRouteCacheNode)\n }\n }\n}\n","import type { CacheNode, Segment } from '../../../shared/lib/app-router-types'\nimport { invalidateCacheByRouterState } from './invalidate-cache-by-router-state'\nimport { fillLazyItemsTillLeafWithHead } from './fill-lazy-items-till-leaf-with-head'\nimport { createRouterCacheKey } from './create-router-cache-key'\nimport type { PrefetchCacheEntry } from './router-reducer-types'\nimport { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'\nimport type { NormalizedFlightData } from '../../flight-data-helpers'\n\n/**\n * Common logic for filling cache with new sub tree data.\n */\nfunction fillCacheHelper(\n navigatedAt: number,\n newCache: CacheNode,\n existingCache: CacheNode,\n flightData: NormalizedFlightData,\n prefetchEntry: PrefetchCacheEntry | undefined,\n fillLazyItems: boolean\n): void {\n const {\n segmentPath,\n seedData: cacheNodeSeedData,\n tree: treePatch,\n head,\n } = flightData\n let newCacheNode = newCache\n let existingCacheNode = existingCache\n\n for (let i = 0; i < segmentPath.length; i += 2) {\n const parallelRouteKey: string = segmentPath[i]\n const segment: Segment = segmentPath[i + 1]\n\n // segmentPath is a repeating tuple of parallelRouteKey and segment\n // we know we've hit the last entry we've reached our final pair\n const isLastEntry = i === segmentPath.length - 2\n const cacheKey = createRouterCacheKey(segment)\n\n const existingChildSegmentMap =\n existingCacheNode.parallelRoutes.get(parallelRouteKey)\n\n if (!existingChildSegmentMap) {\n // Bailout because the existing cache does not have the path to the leaf node\n // Will trigger lazy fetch in layout-router because of missing segment\n continue\n }\n\n let childSegmentMap = newCacheNode.parallelRoutes.get(parallelRouteKey)\n if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {\n childSegmentMap = new Map(existingChildSegmentMap)\n newCacheNode.parallelRoutes.set(parallelRouteKey, childSegmentMap)\n }\n\n const existingChildCacheNode = existingChildSegmentMap.get(cacheKey)\n let childCacheNode = childSegmentMap.get(cacheKey)\n\n if (isLastEntry) {\n if (\n cacheNodeSeedData &&\n (!childCacheNode ||\n !childCacheNode.lazyData ||\n childCacheNode === existingChildCacheNode)\n ) {\n const incomingSegment = cacheNodeSeedData[0]\n const rsc = cacheNodeSeedData[1]\n const loading = cacheNodeSeedData[3]\n\n childCacheNode = {\n lazyData: null,\n // When `fillLazyItems` is false, we only want to fill the RSC data for the layout,\n // not the page segment.\n rsc:\n fillLazyItems || incomingSegment !== PAGE_SEGMENT_KEY ? rsc : null,\n prefetchRsc: null,\n head: null,\n prefetchHead: null,\n loading,\n parallelRoutes:\n fillLazyItems && existingChildCacheNode\n ? new Map(existingChildCacheNode.parallelRoutes)\n : new Map(),\n navigatedAt,\n }\n\n if (existingChildCacheNode && fillLazyItems) {\n invalidateCacheByRouterState(\n childCacheNode,\n existingChildCacheNode,\n treePatch\n )\n }\n if (fillLazyItems) {\n fillLazyItemsTillLeafWithHead(\n navigatedAt,\n childCacheNode,\n existingChildCacheNode,\n treePatch,\n cacheNodeSeedData,\n head,\n prefetchEntry\n )\n }\n\n childSegmentMap.set(cacheKey, childCacheNode)\n }\n continue\n }\n\n if (!childCacheNode || !existingChildCacheNode) {\n // Bailout because the existing cache does not have the path to the leaf node\n // Will trigger lazy fetch in layout-router because of missing segment\n continue\n }\n\n if (childCacheNode === existingChildCacheNode) {\n childCacheNode = {\n lazyData: childCacheNode.lazyData,\n rsc: childCacheNode.rsc,\n prefetchRsc: childCacheNode.prefetchRsc,\n head: childCacheNode.head,\n prefetchHead: childCacheNode.prefetchHead,\n parallelRoutes: new Map(childCacheNode.parallelRoutes),\n loading: childCacheNode.loading,\n } as CacheNode\n childSegmentMap.set(cacheKey, childCacheNode)\n }\n\n // Move deeper into the cache nodes\n newCacheNode = childCacheNode\n existingCacheNode = existingChildCacheNode\n }\n}\n\n/**\n * Fill cache with rsc based on flightDataPath\n */\nexport function fillCacheWithNewSubTreeData(\n navigatedAt: number,\n newCache: CacheNode,\n existingCache: CacheNode,\n flightData: NormalizedFlightData,\n prefetchEntry?: PrefetchCacheEntry\n): void {\n fillCacheHelper(\n navigatedAt,\n newCache,\n existingCache,\n flightData,\n prefetchEntry,\n true\n )\n}\n\nexport function fillCacheWithNewSubTreeDataButOnlyLoading(\n navigatedAt: number,\n newCache: CacheNode,\n existingCache: CacheNode,\n flightData: NormalizedFlightData,\n prefetchEntry?: PrefetchCacheEntry\n): void {\n fillCacheHelper(\n navigatedAt,\n newCache,\n existingCache,\n flightData,\n prefetchEntry,\n false\n )\n}\n","import type { CacheNode } from '../../../shared/lib/app-router-types'\nimport { fillLazyItemsTillLeafWithHead } from './fill-lazy-items-till-leaf-with-head'\nimport { fillCacheWithNewSubTreeData } from './fill-cache-with-new-subtree-data'\nimport type { PrefetchCacheEntry } from './router-reducer-types'\nimport type { NormalizedFlightData } from '../../flight-data-helpers'\n\nexport function applyFlightData(\n navigatedAt: number,\n existingCache: CacheNode,\n cache: CacheNode,\n flightData: NormalizedFlightData,\n prefetchEntry?: PrefetchCacheEntry\n): boolean {\n // The one before last item is the router state tree patch\n const { tree: treePatch, seedData, head, isRootRender } = flightData\n\n // Handles case where prefetch only returns the router tree patch without rendered components.\n if (seedData === null) {\n return false\n }\n\n if (isRootRender) {\n const rsc = seedData[1]\n const loading = seedData[3]\n cache.loading = loading\n cache.rsc = rsc\n // This is a PPR-only field. When PPR is enabled, we shouldn't hit\n // this path during a navigation, but until PPR is fully implemented\n // yet it's possible the existing node does have a non-null\n // `prefetchRsc`. As an incremental step, we'll just de-opt to the\n // old behavior — no PPR value.\n cache.prefetchRsc = null\n fillLazyItemsTillLeafWithHead(\n navigatedAt,\n cache,\n existingCache,\n treePatch,\n seedData,\n head,\n prefetchEntry\n )\n } else {\n // Copy rsc for the root node of the cache.\n cache.rsc = existingCache.rsc\n // This is a PPR-only field. Unlike the previous branch, since we're\n // just cloning the existing cache node, we might as well keep the\n // PPR value, if it exists.\n cache.prefetchRsc = existingCache.prefetchRsc\n cache.parallelRoutes = new Map(existingCache.parallelRoutes)\n cache.loading = existingCache.loading\n // Create a copy of the existing cache with the rsc applied.\n fillCacheWithNewSubTreeData(\n navigatedAt,\n cache,\n existingCache,\n flightData,\n prefetchEntry\n )\n }\n\n return true\n}\n","import type {\n FlightRouterState,\n CacheNode,\n} from '../../../shared/lib/app-router-types'\nimport type { AppRouterState } from './router-reducer-types'\nimport { applyFlightData } from './apply-flight-data'\nimport { fetchServerResponse } from './fetch-server-response'\nimport { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'\n\ninterface RefreshInactiveParallelSegments {\n navigatedAt: number\n state: AppRouterState\n updatedTree: FlightRouterState\n updatedCache: CacheNode\n includeNextUrl: boolean\n canonicalUrl: string\n}\n\n/**\n * Refreshes inactive segments that are still in the current FlightRouterState.\n * A segment is considered \"inactive\" when the server response indicates it didn't match to a page component.\n * This happens during a soft-navigation, where the server will want to patch in the segment\n * with the \"default\" component, but we explicitly ignore the server in this case\n * and keep the existing state for that segment. New data for inactive segments are inherently\n * not part of the server response when we patch the tree, because they were associated with a response\n * from an earlier navigation/request. For each segment, once it becomes \"active\", we encode the URL that provided\n * the data for it. This function traverses parallel routes looking for these markers so that it can re-fetch\n * and patch the new data into the tree.\n */\nexport async function refreshInactiveParallelSegments(\n options: RefreshInactiveParallelSegments\n) {\n const fetchedSegments = new Set<string>()\n await refreshInactiveParallelSegmentsImpl({\n ...options,\n rootTree: options.updatedTree,\n fetchedSegments,\n })\n}\n\nasync function refreshInactiveParallelSegmentsImpl({\n navigatedAt,\n state,\n updatedTree,\n updatedCache,\n includeNextUrl,\n fetchedSegments,\n rootTree = updatedTree,\n canonicalUrl,\n}: RefreshInactiveParallelSegments & {\n fetchedSegments: Set<string>\n rootTree: FlightRouterState\n}) {\n const [, parallelRoutes, refetchPath, refetchMarker] = updatedTree\n const fetchPromises = []\n\n if (\n refetchPath &&\n refetchPath !== canonicalUrl &&\n refetchMarker === 'refresh' &&\n // it's possible for the tree to contain multiple segments that contain data at the same URL\n // we keep track of them so we can dedupe the requests\n !fetchedSegments.has(refetchPath)\n ) {\n fetchedSegments.add(refetchPath) // Mark this URL as fetched\n\n // Eagerly kick off the fetch for the refetch path & the parallel routes. This should be fine to do as they each operate\n // independently on their own cache nodes, and `applyFlightData` will copy anything it doesn't care about from the existing cache.\n const fetchPromise = fetchServerResponse(\n new URL(refetchPath, location.origin),\n {\n // refetch from the root of the updated tree, otherwise it will be scoped to the current segment\n // and might not contain the data we need to patch in interception route data (such as dynamic params from a previous segment)\n flightRouterState: [rootTree[0], rootTree[1], rootTree[2], 'refetch'],\n nextUrl: includeNextUrl ? state.nextUrl : null,\n }\n ).then(({ flightData }) => {\n if (typeof flightData !== 'string') {\n for (const flightDataPath of flightData) {\n // we only pass the new cache as this function is called after clearing the router cache\n // and filling in the new page data from the server. Meaning the existing cache is actually the cache that's\n // just been created & has been written to, but hasn't been \"committed\" yet.\n applyFlightData(\n navigatedAt,\n updatedCache,\n updatedCache,\n flightDataPath\n )\n }\n } else {\n // When flightData is a string, it suggests that the server response should have triggered an MPA navigation\n // I'm not 100% sure of this decision, but it seems unlikely that we'd want to introduce a redirect side effect\n // when refreshing on-screen data, so handling this has been ommitted.\n }\n })\n\n fetchPromises.push(fetchPromise)\n }\n\n for (const key in parallelRoutes) {\n const parallelFetchPromise = refreshInactiveParallelSegmentsImpl({\n navigatedAt,\n state,\n updatedTree: parallelRoutes[key],\n updatedCache,\n includeNextUrl,\n fetchedSegments,\n rootTree,\n canonicalUrl,\n })\n\n fetchPromises.push(parallelFetchPromise)\n }\n\n await Promise.all(fetchPromises)\n}\n\n/**\n * Walks the current parallel segments to determine if they are \"active\".\n * An active parallel route will have a `__PAGE__` segment in the FlightRouterState.\n * As opposed to a `__DEFAULT__` segment, which means there was no match for that parallel route.\n * We add a special marker here so that we know how to refresh its data when the router is revalidated.\n */\nexport function addRefreshMarkerToActiveParallelSegments(\n tree: FlightRouterState,\n path: string\n) {\n const [segment, parallelRoutes, , refetchMarker] = tree\n // a page segment might also contain concatenated search params, so we do a partial match on the key\n if (segment.includes(PAGE_SEGMENT_KEY) && refetchMarker !== 'refresh') {\n tree[2] = path\n tree[3] = 'refresh'\n }\n\n for (const key in parallelRoutes) {\n addRefreshMarkerToActiveParallelSegments(parallelRoutes[key], path)\n }\n}\n","import type {\n FlightRouterState,\n FlightSegmentPath,\n} from '../../../shared/lib/app-router-types'\nimport { DEFAULT_SEGMENT_KEY } from '../../../shared/lib/segment'\nimport { getNextFlightSegmentPath } from '../../flight-data-helpers'\nimport { matchSegment } from '../match-segments'\nimport { addRefreshMarkerToActiveParallelSegments } from './refetch-inactive-parallel-segments'\n\n/**\n * Deep merge of the two router states. Parallel route keys are preserved if the patch doesn't have them.\n */\nfunction applyPatch(\n initialTree: FlightRouterState,\n patchTree: FlightRouterState\n): FlightRouterState {\n const [initialSegment, initialParallelRoutes] = initialTree\n const [patchSegment, patchParallelRoutes] = patchTree\n\n // if the applied patch segment is __DEFAULT__ then it can be ignored in favor of the initial tree\n // this is because the __DEFAULT__ segment is used as a placeholder on navigation\n if (\n patchSegment === DEFAULT_SEGMENT_KEY &&\n initialSegment !== DEFAULT_SEGMENT_KEY\n ) {\n return initialTree\n }\n\n if (matchSegment(initialSegment, patchSegment)) {\n const newParallelRoutes: FlightRouterState[1] = {}\n for (const key in initialParallelRoutes) {\n const isInPatchTreeParallelRoutes =\n typeof patchParallelRoutes[key] !== 'undefined'\n if (isInPatchTreeParallelRoutes) {\n newParallelRoutes[key] = applyPatch(\n initialParallelRoutes[key],\n patchParallelRoutes[key]\n )\n } else {\n newParallelRoutes[key] = initialParallelRoutes[key]\n }\n }\n\n for (const key in patchParallelRoutes) {\n if (newParallelRoutes[key]) {\n continue\n }\n\n newParallelRoutes[key] = patchParallelRoutes[key]\n }\n\n const tree: FlightRouterState = [initialSegment, newParallelRoutes]\n\n // Copy over the existing tree\n if (initialTree[2]) {\n tree[2] = initialTree[2]\n }\n\n if (initialTree[3]) {\n tree[3] = initialTree[3]\n }\n\n if (initialTree[4]) {\n tree[4] = initialTree[4]\n }\n\n return tree\n }\n\n return patchTree\n}\n\n/**\n * Apply the router state from the Flight response, but skip patching default segments.\n * Useful for patching the router cache when navigating, where we persist the existing default segment if there isn't a new one.\n * Creates a new router state tree.\n */\nexport function applyRouterStatePatchToTree(\n flightSegmentPath: FlightSegmentPath,\n flightRouterState: FlightRouterState,\n treePatch: FlightRouterState,\n path: string\n): FlightRouterState | null {\n const [segment, parallelRoutes, url, refetch, isRootLayout] =\n flightRouterState\n\n // Root refresh\n if (flightSegmentPath.length === 1) {\n const tree: FlightRouterState = applyPatch(flightRouterState, treePatch)\n\n addRefreshMarkerToActiveParallelSegments(tree, path)\n\n return tree\n }\n\n const [currentSegment, parallelRouteKey] = flightSegmentPath\n\n // Tree path returned from the server should always match up with the current tree in the browser\n if (!matchSegment(currentSegment, segment)) {\n return null\n }\n\n const lastSegment = flightSegmentPath.length === 2\n\n let parallelRoutePatch\n if (lastSegment) {\n parallelRoutePatch = applyPatch(parallelRoutes[parallelRouteKey], treePatch)\n } else {\n parallelRoutePatch = applyRouterStatePatchToTree(\n getNextFlightSegmentPath(flightSegmentPath),\n parallelRoutes[parallelRouteKey],\n treePatch,\n path\n )\n\n if (parallelRoutePatch === null) {\n return null\n }\n }\n\n const tree: FlightRouterState = [\n flightSegmentPath[0],\n {\n ...parallelRoutes,\n [parallelRouteKey]: parallelRoutePatch,\n },\n url,\n refetch,\n ]\n\n // Current segment is the root layout\n if (isRootLayout) {\n tree[4] = true\n }\n\n addRefreshMarkerToActiveParallelSegments(tree, path)\n\n return tree\n}\n","import type {\n FlightRouterState,\n FlightDataPath,\n Segment,\n} from '../../../shared/lib/app-router-types'\nimport { getNextFlightSegmentPath } from '../../flight-data-helpers'\nimport { matchSegment } from '../match-segments'\n\n// TODO-APP: flightSegmentPath will be empty in case of static response, needs to be handled.\nexport function shouldHardNavigate(\n flightSegmentPath: FlightDataPath,\n flightRouterState: FlightRouterState\n): boolean {\n const [segment, parallelRoutes] = flightRouterState\n // TODO-APP: Check if `as` can be replaced.\n const [currentSegment, parallelRouteKey] = flightSegmentPath as [\n Segment,\n string,\n ]\n\n // Check if current segment matches the existing segment.\n if (!matchSegment(currentSegment, segment)) {\n // If dynamic parameter in tree doesn't match up with segment path a hard navigation is triggered.\n if (Array.isArray(currentSegment)) {\n return true\n }\n\n // If the existing segment did not match soft navigation is triggered.\n return false\n }\n const lastSegment = flightSegmentPath.length <= 2\n\n if (lastSegment) {\n return false\n }\n\n return shouldHardNavigate(\n getNextFlightSegmentPath(flightSegmentPath),\n parallelRoutes[parallelRouteKey]\n )\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","/**\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 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\nexport function extractInterceptionRouteInformation(path: string) {\n let interceptingRoute: string | undefined,\n marker: (typeof INTERCEPTION_ROUTE_MARKERS)[number] | undefined,\n 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 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 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: isNotUndefined(mutable.canonicalUrl)\n ? mutable.canonicalUrl === state.canonicalUrl\n ? state.canonicalUrl\n : mutable.canonicalUrl\n : state.canonicalUrl,\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 prefetchCache: mutable.prefetchCache\n ? mutable.prefetchCache\n : state.prefetchCache,\n // Apply patched router state.\n tree: isNotUndefined(mutable.patchedTree)\n ? mutable.patchedTree\n : state.tree,\n nextUrl,\n }\n}\n","\"use strict\";\n\nfunction _class_private_field_loose_base(receiver, privateKey) {\n if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {\n throw new TypeError(\"attempted to use private field on non-instance\");\n }\n\n return receiver;\n}\nexports._ = _class_private_field_loose_base;\n","\"use strict\";\n\nvar id = 0;\n\nfunction _class_private_field_loose_key(name) {\n return \"__private_\" + id++ + \"_\" + name;\n}\nexports._ = _class_private_field_loose_key;\n","/*\n This is a simple promise queue that allows you to limit the number of concurrent promises\n that are running at any given time. It's used to limit the number of concurrent\n prefetch requests that are being made to the server but could be used for other\n things as well.\n*/\nexport class PromiseQueue {\n #maxConcurrency: number\n #runningCount: number\n #queue: Array<{\n promiseFn: Promise<any>\n task: () => void\n }>\n\n constructor(maxConcurrency = 5) {\n this.#maxConcurrency = maxConcurrency\n this.#runningCount = 0\n this.#queue = []\n }\n\n enqueue<T>(promiseFn: () => Promise<T>): Promise<T> {\n let taskResolve: (value: T | PromiseLike<T>) => void\n let taskReject: (reason?: any) => void\n\n const taskPromise = new Promise((resolve, reject) => {\n taskResolve = resolve\n taskReject = reject\n }) as Promise<T>\n\n const task = async () => {\n try {\n this.#runningCount++\n const result = await promiseFn()\n taskResolve(result)\n } catch (error) {\n taskReject(error)\n } finally {\n this.#runningCount--\n this.#processNext()\n }\n }\n\n const enqueueResult = { promiseFn: taskPromise, task }\n // wonder if we should take a LIFO approach here\n this.#queue.push(enqueueResult)\n this.#processNext()\n\n return taskPromise\n }\n\n bump(promiseFn: Promise<any>) {\n const index = this.#queue.findIndex((item) => item.promiseFn === promiseFn)\n\n if (index > -1) {\n const bumpedItem = this.#queue.splice(index, 1)[0]\n this.#queue.unshift(bumpedItem)\n this.#processNext(true)\n }\n }\n\n #processNext(forced = false) {\n if (\n (this.#runningCount < this.#maxConcurrency || forced) &&\n this.#queue.length > 0\n ) {\n this.#queue.shift()?.task()\n }\n }\n}\n","import {\n fetchServerResponse,\n type FetchServerResponseResult,\n} from './fetch-server-response'\nimport {\n PrefetchCacheEntryStatus,\n type PrefetchCacheEntry,\n PrefetchKind,\n type ReadonlyReducerState,\n} from './router-reducer-types'\nimport { prefetchQueue } from './reducers/prefetch-reducer'\n\nconst INTERCEPTION_CACHE_KEY_MARKER = '%'\n\nexport type AliasedPrefetchCacheEntry = PrefetchCacheEntry & {\n /** This is a special property that indicates a prefetch entry associated with a different URL\n * was returned rather than the requested URL. This signals to the router that it should only\n * apply the part that doesn't depend on searchParams (specifically the loading state).\n */\n aliased?: boolean\n}\n\n/**\n * Creates a cache key for the router prefetch cache\n *\n * @param url - The URL being navigated to\n * @param nextUrl - an internal URL, primarily used for handling rewrites. Defaults to '/'.\n * @return The generated prefetch cache key.\n */\nfunction createPrefetchCacheKeyImpl(\n url: URL,\n includeSearchParams: boolean,\n prefix?: string | null\n) {\n // Initially we only use the pathname as the cache key. We don't want to include\n // search params so that multiple URLs with the same search parameter can re-use\n // loading states.\n let pathnameFromUrl = url.pathname\n\n // RSC responses can differ based on search params, specifically in the case where we aren't\n // returning a partial response (ie with `PrefetchKind.AUTO`).\n // In the auto case, since loading.js & layout.js won't have access to search params,\n // we can safely re-use that cache entry. But for full prefetches, we should not\n // re-use the cache entry as the response may differ.\n if (includeSearchParams) {\n // if we have a full prefetch, we can include the search param in the key,\n // as we'll be getting back a full response. The server might have read the search\n // params when generating the full response.\n pathnameFromUrl += url.search\n }\n\n if (prefix) {\n return `${prefix}${INTERCEPTION_CACHE_KEY_MARKER}${pathnameFromUrl}`\n }\n\n return pathnameFromUrl\n}\n\nfunction createPrefetchCacheKey(\n url: URL,\n kind: PrefetchKind | undefined,\n nextUrl?: string | null\n) {\n return createPrefetchCacheKeyImpl(url, kind === PrefetchKind.FULL, nextUrl)\n}\n\nfunction getExistingCacheEntry(\n url: URL,\n kind: PrefetchKind = PrefetchKind.TEMPORARY,\n nextUrl: string | null,\n prefetchCache: Map<string, PrefetchCacheEntry>,\n allowAliasing: boolean\n): AliasedPrefetchCacheEntry | undefined {\n // We first check if there's a more specific interception route prefetch entry\n // This is because when we detect a prefetch that corresponds with an interception route, we prefix it with nextUrl (see `createPrefetchCacheKey`)\n // to avoid conflicts with other pages that may have the same URL but render different things depending on the `Next-URL` header.\n for (const maybeNextUrl of [nextUrl, null]) {\n const cacheKeyWithParams = createPrefetchCacheKeyImpl(\n url,\n true,\n maybeNextUrl\n )\n const cacheKeyWithoutParams = createPrefetchCacheKeyImpl(\n url,\n false,\n maybeNextUrl\n )\n\n // First, we check if we have a cache entry that exactly matches the URL\n const cacheKeyToUse = url.search\n ? cacheKeyWithParams\n : cacheKeyWithoutParams\n\n const existingEntry = prefetchCache.get(cacheKeyToUse)\n if (existingEntry && allowAliasing) {\n // We know we're returning an aliased entry when the pathname matches but the search params don't,\n const isAliased =\n existingEntry.url.pathname === url.pathname &&\n existingEntry.url.search !== url.search\n\n if (isAliased) {\n return {\n ...existingEntry,\n aliased: true,\n }\n }\n\n return existingEntry\n }\n\n // If the request contains search params, and we're not doing a full prefetch, we can return the\n // param-less entry if it exists.\n // This is technically covered by the check at the bottom of this function, which iterates over cache entries,\n // but lets us arrive there quicker in the param-full case.\n const entryWithoutParams = prefetchCache.get(cacheKeyWithoutParams)\n if (\n process.env.NODE_ENV !== 'development' &&\n allowAliasing &&\n url.search &&\n kind !== PrefetchKind.FULL &&\n entryWithoutParams &&\n // We shouldn't return the aliased entry if it was relocated to a new cache key.\n // Since it's rewritten, it could respond with a completely different loading state.\n !entryWithoutParams.key.includes(INTERCEPTION_CACHE_KEY_MARKER)\n ) {\n return { ...entryWithoutParams, aliased: true }\n }\n }\n\n // If we've gotten to this point, we didn't find a specific cache entry that matched\n // the request URL.\n // We attempt a partial match by checking if there's a cache entry with the same pathname.\n // Regardless of what we find, since it doesn't correspond with the requested URL, we'll mark it \"aliased\".\n // This will signal to the router that it should only apply the loading state on the prefetched data.\n if (\n process.env.NODE_ENV !== 'development' &&\n kind !== PrefetchKind.FULL &&\n allowAliasing\n ) {\n for (const cacheEntry of prefetchCache.values()) {\n if (\n cacheEntry.url.pathname === url.pathname &&\n // We shouldn't return the aliased entry if it was relocated to a new cache key.\n // Since it's rewritten, it could respond with a completely different loading state.\n !cacheEntry.key.includes(INTERCEPTION_CACHE_KEY_MARKER)\n ) {\n return { ...cacheEntry, aliased: true }\n }\n }\n }\n\n return undefined\n}\n\n/**\n * Returns a prefetch cache entry if one exists. Otherwise creates a new one and enqueues a fetch request\n * to retrieve the prefetch data from the server.\n */\nexport function getOrCreatePrefetchCacheEntry({\n url,\n nextUrl,\n tree,\n prefetchCache,\n kind,\n allowAliasing = true,\n}: Pick<ReadonlyReducerState, 'nextUrl' | 'prefetchCache' | 'tree'> & {\n url: URL\n kind?: PrefetchKind\n allowAliasing: boolean\n}): AliasedPrefetchCacheEntry {\n const existingCacheEntry = getExistingCacheEntry(\n url,\n kind,\n nextUrl,\n prefetchCache,\n allowAliasing\n )\n\n if (existingCacheEntry) {\n // Grab the latest status of the cache entry and update it\n existingCacheEntry.status = getPrefetchEntryCacheStatus(existingCacheEntry)\n\n // when `kind` is provided, an explicit prefetch was requested.\n // if the requested prefetch is \"full\" and the current cache entry wasn't, we want to re-prefetch with the new intent\n const switchedToFullPrefetch =\n existingCacheEntry.kind !== PrefetchKind.FULL &&\n kind === PrefetchKind.FULL\n\n if (switchedToFullPrefetch) {\n // If we switched to a full prefetch, validate that the existing cache entry contained partial data.\n // It's possible that the cache entry was seeded with full data but has a cache type of \"auto\" (ie when cache entries\n // are seeded but without a prefetch intent)\n existingCacheEntry.data.then((prefetchResponse) => {\n const isFullPrefetch =\n Array.isArray(prefetchResponse.flightData) &&\n prefetchResponse.flightData.some((flightData) => {\n // If we started rendering from the root and we returned RSC data (seedData), we already had a full prefetch.\n return flightData.isRootRender && flightData.seedData !== null\n })\n\n if (!isFullPrefetch) {\n return createLazyPrefetchEntry({\n tree,\n url,\n nextUrl,\n prefetchCache,\n // If we didn't get an explicit prefetch kind, we want to set a temporary kind\n // rather than assuming the same intent as the previous entry, to be consistent with how we\n // lazily create prefetch entries when intent is left unspecified.\n kind: kind ?? PrefetchKind.TEMPORARY,\n })\n }\n })\n }\n\n // If the existing cache entry was marked as temporary, it means it was lazily created when attempting to get an entry,\n // where we didn't have the prefetch intent. Now that we have the intent (in `kind`), we want to update the entry to the more accurate kind.\n if (kind && existingCacheEntry.kind === PrefetchKind.TEMPORARY) {\n existingCacheEntry.kind = kind\n }\n\n // We've determined that the existing entry we found is still valid, so we return it.\n return existingCacheEntry\n }\n\n // If we didn't return an entry, create a new one.\n return createLazyPrefetchEntry({\n tree,\n url,\n nextUrl,\n prefetchCache,\n kind: kind || PrefetchKind.TEMPORARY,\n })\n}\n\n/*\n * Used to take an existing cache entry and prefix it with the nextUrl, if it exists.\n * This ensures that we don't have conflicting cache entries for the same URL (as is the case with route interception).\n */\nfunction prefixExistingPrefetchCacheEntry({\n url,\n nextUrl,\n prefetchCache,\n existingCacheKey,\n}: Pick<ReadonlyReducerState, 'nextUrl' | 'prefetchCache'> & {\n url: URL\n existingCacheKey: string\n}) {\n const existingCacheEntry = prefetchCache.get(existingCacheKey)\n if (!existingCacheEntry) {\n // no-op -- there wasn't an entry to move\n return\n }\n\n const newCacheKey = createPrefetchCacheKey(\n url,\n existingCacheEntry.kind,\n nextUrl\n )\n prefetchCache.set(newCacheKey, { ...existingCacheEntry, key: newCacheKey })\n prefetchCache.delete(existingCacheKey)\n\n return newCacheKey\n}\n\n/**\n * Use to seed the prefetch cache with data that has already been fetched.\n */\nexport function createSeededPrefetchCacheEntry({\n nextUrl,\n tree,\n prefetchCache,\n url,\n data,\n kind,\n}: Pick<ReadonlyReducerState, 'nextUrl' | 'tree' | 'prefetchCache'> & {\n url: URL\n data: FetchServerResponseResult\n kind: PrefetchKind\n}) {\n // The initial cache entry technically includes full data, but it isn't explicitly prefetched -- we just seed the\n // prefetch cache so that we can skip an extra prefetch request later, since we already have the data.\n // if the prefetch corresponds with an interception route, we use the nextUrl to prefix the cache key\n const prefetchCacheKey = data.couldBeIntercepted\n ? createPrefetchCacheKey(url, kind, nextUrl)\n : createPrefetchCacheKey(url, kind)\n\n const prefetchEntry = {\n treeAtTimeOfPrefetch: tree,\n data: Promise.resolve(data),\n kind,\n prefetchTime: Date.now(),\n lastUsedTime: Date.now(),\n staleTime: data.staleTime,\n key: prefetchCacheKey,\n status: PrefetchCacheEntryStatus.fresh,\n url,\n } satisfies PrefetchCacheEntry\n\n prefetchCache.set(prefetchCacheKey, prefetchEntry)\n\n return prefetchEntry\n}\n\n/**\n * Creates a prefetch entry entry and enqueues a fetch request to retrieve the data.\n */\nfunction createLazyPrefetchEntry({\n url,\n kind,\n tree,\n nextUrl,\n prefetchCache,\n}: Pick<ReadonlyReducerState, 'nextUrl' | 'tree' | 'prefetchCache'> & {\n url: URL\n kind: PrefetchKind\n}): PrefetchCacheEntry {\n const prefetchCacheKey = createPrefetchCacheKey(url, kind)\n\n // initiates the fetch request for the prefetch and attaches a listener\n // to the promise to update the prefetch cache entry when the promise resolves (if necessary)\n const data = prefetchQueue.enqueue(() =>\n fetchServerResponse(url, {\n flightRouterState: tree,\n nextUrl,\n prefetchKind: kind,\n }).then((prefetchResponse) => {\n // TODO: `fetchServerResponse` should be more tighly coupled to these prefetch cache operations\n // to avoid drift between this cache key prefixing logic\n // (which is currently directly influenced by the server response)\n let newCacheKey\n\n if (prefetchResponse.couldBeIntercepted) {\n // Determine if we need to prefix the cache key with the nextUrl\n newCacheKey = prefixExistingPrefetchCacheEntry({\n url,\n existingCacheKey: prefetchCacheKey,\n nextUrl,\n prefetchCache,\n })\n }\n\n // If the prefetch was a cache hit, we want to update the existing cache entry to reflect that it was a full prefetch.\n // This is because we know that a static response will contain the full RSC payload, and can be updated to respect the `static`\n // staleTime.\n if (prefetchResponse.prerendered) {\n const existingCacheEntry = prefetchCache.get(\n // if we prefixed the cache key due to route interception, we want to use the new key. Otherwise we use the original key\n newCacheKey ?? prefetchCacheKey\n )\n if (existingCacheEntry) {\n existingCacheEntry.kind = PrefetchKind.FULL\n if (prefetchResponse.staleTime !== -1) {\n // This is the stale time that was collected by the server during\n // static generation. Use this in place of the default stale time.\n existingCacheEntry.staleTime = prefetchResponse.staleTime\n }\n }\n }\n\n return prefetchResponse\n })\n )\n\n const prefetchEntry = {\n treeAtTimeOfPrefetch: tree,\n data,\n kind,\n prefetchTime: Date.now(),\n lastUsedTime: null,\n staleTime: -1,\n key: prefetchCacheKey,\n status: PrefetchCacheEntryStatus.fresh,\n url,\n }\n\n prefetchCache.set(prefetchCacheKey, prefetchEntry)\n\n return prefetchEntry\n}\n\nexport function prunePrefetchCache(\n prefetchCache: ReadonlyReducerState['prefetchCache']\n) {\n for (const [href, prefetchCacheEntry] of prefetchCache) {\n if (\n getPrefetchEntryCacheStatus(prefetchCacheEntry) ===\n PrefetchCacheEntryStatus.expired\n ) {\n prefetchCache.delete(href)\n }\n }\n}\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 =\n Number(process.env.__NEXT_CLIENT_ROUTER_STATIC_STALETIME) * 1000\n\nfunction getPrefetchEntryCacheStatus({\n kind,\n prefetchTime,\n lastUsedTime,\n}: PrefetchCacheEntry): PrefetchCacheEntryStatus {\n // We will re-use the cache entry data for up to the `dynamic` staletime window.\n if (Date.now() < (lastUsedTime ?? prefetchTime) + DYNAMIC_STALETIME_MS) {\n return lastUsedTime\n ? PrefetchCacheEntryStatus.reusable\n : PrefetchCacheEntryStatus.fresh\n }\n\n // For \"auto\" prefetching, we'll re-use only the loading boundary for up to `static` staletime window.\n // A stale entry will only re-use the `loading` boundary, not the full data.\n // This will trigger a \"lazy fetch\" for the full data.\n if (kind === PrefetchKind.AUTO) {\n if (Date.now() < prefetchTime + STATIC_STALETIME_MS) {\n return PrefetchCacheEntryStatus.stale\n }\n }\n\n // for \"full\" prefetching, we'll re-use the cache entry data for up to `static` staletime window.\n if (kind === PrefetchKind.FULL) {\n if (Date.now() < prefetchTime + STATIC_STALETIME_MS) {\n return PrefetchCacheEntryStatus.reusable\n }\n }\n\n return PrefetchCacheEntryStatus.expired\n}\n","import type {\n PrefetchAction,\n ReducerState,\n ReadonlyReducerState,\n} from '../router-reducer-types'\nimport { PromiseQueue } from '../../promise-queue'\nimport {\n getOrCreatePrefetchCacheEntry,\n prunePrefetchCache,\n} from '../prefetch-cache-utils'\nexport const prefetchQueue = new PromiseQueue(5)\n\nexport const prefetchReducer = process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? identityReducerWhenSegmentCacheIsEnabled\n : prefetchReducerImpl\n\nfunction identityReducerWhenSegmentCacheIsEnabled<T>(state: T): T {\n // Unlike the old implementation, the Segment Cache doesn't store its data in\n // the router reducer state.\n //\n // This shouldn't be reachable because we wrap the prefetch API in a check,\n // too, which prevents the action from being dispatched. But it's here for\n // clarity + code elimination.\n return state\n}\n\nfunction prefetchReducerImpl(\n state: ReadonlyReducerState,\n action: PrefetchAction\n): ReducerState {\n // let's prune the prefetch cache before we do anything else\n prunePrefetchCache(state.prefetchCache)\n\n const { url } = action\n\n getOrCreatePrefetchCacheEntry({\n url,\n nextUrl: state.nextUrl,\n prefetchCache: state.prefetchCache,\n kind: action.kind,\n tree: state.tree,\n allowAliasing: true,\n })\n\n return state\n}\n","// This regex contains the bots that we need to do a blocking render for and can't safely stream the response\n// due to how they parse the DOM. For example, they might explicitly check for metadata in the `head` tag, so we can't stream metadata tags after the `head` was sent.\n// Note: The pattern [\\w-]+-Google captures all Google crawlers with \"-Google\" suffix (e.g., Mediapartners-Google, AdsBot-Google, Storebot-Google)\n// as well as crawlers starting with \"Google-\" (e.g., Google-PageRenderer, Google-InspectionTool)\nexport const HTML_LIMITED_BOT_UA_RE =\n /[\\w-]+-Google|Google-[\\w-]+|Chrome-Lighthouse|Slurp|DuckDuckBot|baiduspider|yandex|sogou|bitlybot|tumblr|vkShare|quora link preview|redditbot|ia_archiver|Bingbot|BingPreview|applebot|facebookexternalhit|facebookcatalog|Twitterbot|LinkedInBot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|Yeti|googleweblight/i\n","import { HTML_LIMITED_BOT_UA_RE } from './html-bots'\n\n// Bot crawler that will spin up a headless browser and execute JS.\n// Only the main Googlebot search crawler executes JavaScript, not other Google crawlers.\n// x-ref: https://developers.google.com/search/docs/crawling-indexing/google-common-crawlers\n// This regex specifically matches \"Googlebot\" but NOT \"Mediapartners-Google\", \"AdsBot-Google\", etc.\nconst HEADLESS_BROWSER_BOT_UA_RE = /Googlebot(?!-)|Googlebot$/i\n\nexport const HTML_LIMITED_BOT_UA_RE_STRING = HTML_LIMITED_BOT_UA_RE.source\n\nexport { HTML_LIMITED_BOT_UA_RE }\n\nfunction isDomBotUA(userAgent: string) {\n return HEADLESS_BROWSER_BOT_UA_RE.test(userAgent)\n}\n\nfunction isHtmlLimitedBotUA(userAgent: string) {\n return HTML_LIMITED_BOT_UA_RE.test(userAgent)\n}\n\nexport function isBot(userAgent: string): boolean {\n return isDomBotUA(userAgent) || isHtmlLimitedBotUA(userAgent)\n}\n\nexport function getBotType(userAgent: string): 'dom' | 'html' | undefined {\n if (isDomBotUA(userAgent)) {\n return 'dom'\n }\n if (isHtmlLimitedBotUA(userAgent)) {\n return 'html'\n }\n return undefined\n}\n","import { useEffect, useRef, useState } from 'react'\nimport { createPortal } from 'react-dom'\nimport type { FlightRouterState } from '../../shared/lib/app-router-types'\n\nconst ANNOUNCER_TYPE = 'next-route-announcer'\nconst ANNOUNCER_ID = '__next-route-announcer__'\n\nfunction getAnnouncerNode() {\n const existingAnnouncer = document.getElementsByName(ANNOUNCER_TYPE)[0]\n if (existingAnnouncer?.shadowRoot?.childNodes[0]) {\n return existingAnnouncer.shadowRoot.childNodes[0] as HTMLElement\n } else {\n const container = document.createElement(ANNOUNCER_TYPE)\n container.style.cssText = 'position:absolute'\n const announcer = document.createElement('div')\n announcer.ariaLive = 'assertive'\n announcer.id = ANNOUNCER_ID\n announcer.role = 'alert'\n announcer.style.cssText =\n 'position:absolute;border:0;height:1px;margin:-1px;padding:0;width:1px;clip:rect(0 0 0 0);overflow:hidden;white-space:nowrap;word-wrap:normal'\n\n // Use shadow DOM here to avoid any potential CSS bleed\n const shadow = container.attachShadow({ mode: 'open' })\n shadow.appendChild(announcer)\n document.body.appendChild(container)\n return announcer\n }\n}\n\nexport function AppRouterAnnouncer({ tree }: { tree: FlightRouterState }) {\n const [portalNode, setPortalNode] = useState<HTMLElement | null>(null)\n\n useEffect(() => {\n const announcer = getAnnouncerNode()\n setPortalNode(announcer)\n return () => {\n const container = document.getElementsByTagName(ANNOUNCER_TYPE)[0]\n if (container?.isConnected) {\n document.body.removeChild(container)\n }\n }\n }, [])\n\n const [routeAnnouncement, setRouteAnnouncement] = useState('')\n const previousTitle = useRef<string | undefined>(undefined)\n\n useEffect(() => {\n let currentTitle = ''\n if (document.title) {\n currentTitle = document.title\n } else {\n const pageHeader = document.querySelector('h1')\n if (pageHeader) {\n currentTitle = pageHeader.innerText || pageHeader.textContent || ''\n }\n }\n\n // Only announce the title change, but not for the first load because screen\n // readers do that automatically.\n if (\n previousTitle.current !== undefined &&\n previousTitle.current !== currentTitle\n ) {\n setRouteAnnouncement(currentTitle)\n }\n previousTitle.current = currentTitle\n }, [tree])\n\n return portalNode ? createPortal(routeAnnouncement, portalNode) : null\n}\n","'use client'\nimport React, { useEffect } from 'react'\nimport type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime'\nimport { useRouter } from './navigation'\nimport { getRedirectTypeFromError, getURLFromRedirectError } from './redirect'\nimport { RedirectType, isRedirectError } from './redirect-error'\n\ninterface RedirectBoundaryProps {\n router: AppRouterInstance\n children: React.ReactNode\n}\n\nfunction HandleRedirect({\n redirect,\n reset,\n redirectType,\n}: {\n redirect: string\n redirectType: RedirectType\n reset: () => void\n}) {\n const router = useRouter()\n\n useEffect(() => {\n React.startTransition(() => {\n if (redirectType === RedirectType.push) {\n router.push(redirect, {})\n } else {\n router.replace(redirect, {})\n }\n reset()\n })\n }, [redirect, redirectType, reset, router])\n\n return null\n}\n\nexport class RedirectErrorBoundary extends React.Component<\n RedirectBoundaryProps,\n { redirect: string | null; redirectType: RedirectType | null }\n> {\n constructor(props: RedirectBoundaryProps) {\n super(props)\n this.state = { redirect: null, redirectType: null }\n }\n\n static getDerivedStateFromError(error: any) {\n if (isRedirectError(error)) {\n const url = getURLFromRedirectError(error)\n const redirectType = getRedirectTypeFromError(error)\n return { redirect: url, redirectType }\n }\n // Re-throw if error is not for redirect\n throw error\n }\n\n // Explicit type is needed to avoid the generated `.d.ts` having a wide return type that could be specific to the `@types/react` version.\n render(): React.ReactNode {\n const { redirect, redirectType } = this.state\n if (redirect !== null && redirectType !== null) {\n return (\n <HandleRedirect\n redirect={redirect}\n redirectType={redirectType}\n reset={() => this.setState({ redirect: null })}\n />\n )\n }\n\n return this.props.children\n }\n}\n\nexport function RedirectBoundary({ children }: { children: React.ReactNode }) {\n const router = useRouter()\n return (\n <RedirectErrorBoundary router={router}>{children}</RedirectErrorBoundary>\n )\n}\n","import type {\n FlightRouterState,\n CacheNode,\n} from '../../../../shared/lib/app-router-types'\nimport { DEFAULT_SEGMENT_KEY } from '../../../../shared/lib/segment'\nimport { createRouterCacheKey } from '../create-router-cache-key'\n\nexport function findHeadInCache(\n cache: CacheNode,\n parallelRoutes: FlightRouterState[1]\n): [CacheNode, string, string] | null {\n return findHeadInCacheImpl(cache, parallelRoutes, '', '')\n}\n\nfunction findHeadInCacheImpl(\n cache: CacheNode,\n parallelRoutes: FlightRouterState[1],\n keyPrefix: string,\n keyPrefixWithoutSearchParams: string\n): [CacheNode, string, string] | null {\n const isLastItem = Object.keys(parallelRoutes).length === 0\n if (isLastItem) {\n // Returns the entire Cache Node of the segment whose head we will render.\n return [cache, keyPrefix, keyPrefixWithoutSearchParams]\n }\n\n // First try the 'children' parallel route if it exists\n // when starting from the \"root\", this corresponds with the main page component\n const parallelRoutesKeys = Object.keys(parallelRoutes).filter(\n (key) => key !== 'children'\n )\n\n // if we are at the root, we need to check the children slot first\n if ('children' in parallelRoutes) {\n parallelRoutesKeys.unshift('children')\n }\n\n for (const key of parallelRoutesKeys) {\n const [segment, childParallelRoutes] = parallelRoutes[key]\n // If the parallel is not matched and using the default segment,\n // skip searching the head from it.\n if (segment === DEFAULT_SEGMENT_KEY) {\n continue\n }\n const childSegmentMap = cache.parallelRoutes.get(key)\n if (!childSegmentMap) {\n continue\n }\n\n const cacheKey = createRouterCacheKey(segment)\n const cacheKeyWithoutSearchParams = createRouterCacheKey(segment, true)\n\n const cacheNode = childSegmentMap.get(cacheKey)\n if (!cacheNode) {\n continue\n }\n\n const item = findHeadInCacheImpl(\n cacheNode,\n childParallelRoutes,\n keyPrefix + '/' + cacheKey,\n keyPrefix + '/' + cacheKeyWithoutSearchParams\n )\n\n if (item) {\n return item\n }\n }\n\n return null\n}\n","/**\n * Create a \"Thenable\" that does not resolve. This is used to suspend indefinitely when data is not available yet.\n */\nexport const unresolvedThenable = {\n then: () => {},\n} as PromiseLike<void>\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 { hasBasePath } from './has-base-path'\n\nconst basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''\n\nexport function removeBasePath(path: string): string {\n if (process.env.__NEXT_MANUAL_CLIENT_BASE_PATH) {\n if (!hasBasePath(path)) {\n return path\n }\n }\n\n // Can't trim the basePath if it has zero length!\n if (basePath.length === 0) return path\n\n path = path.slice(basePath.length)\n if (!path.startsWith('/')) path = `/${path}`\n return path\n}\n","import { useEffect } from 'react'\nimport { createHrefFromUrl } from './router-reducer/create-href-from-url'\n\nexport function handleHardNavError(error: unknown): boolean {\n if (\n error &&\n typeof window !== 'undefined' &&\n window.next.__pendingUrl &&\n createHrefFromUrl(new URL(window.location.href)) !==\n createHrefFromUrl(window.next.__pendingUrl)\n ) {\n console.error(\n `Error occurred during navigation, falling back to hard navigation`,\n error\n )\n window.location.href = window.next.__pendingUrl.toString()\n return true\n }\n return false\n}\n\nexport function useNavFailureHandler() {\n if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {\n // this if is only for DCE of the feature flag not conditional\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useEffect(() => {\n const uncaughtExceptionHandler = (\n evt: ErrorEvent | PromiseRejectionEvent\n ) => {\n const error = 'reason' in evt ? evt.reason : evt.error\n // if we have an unhandled exception/rejection during\n // a navigation we fall back to a hard navigation to\n // attempt recovering to a good state\n handleHardNavError(error)\n }\n window.addEventListener('unhandledrejection', uncaughtExceptionHandler)\n window.addEventListener('error', uncaughtExceptionHandler)\n return () => {\n window.removeEventListener('error', uncaughtExceptionHandler)\n window.removeEventListener(\n 'unhandledrejection',\n uncaughtExceptionHandler\n )\n }\n }, [])\n }\n}\n","'use client'\n\nimport { Component, createRef, type ReactNode } from 'react'\n\ninterface ErrorBoundaryProps {\n children: ReactNode\n}\n\ninterface ErrorBoundaryState {\n hasError: boolean\n}\n\nfunction getDomNodeAttributes(node: HTMLElement): Record<string, string> {\n const result: Record<string, string> = {}\n for (let i = 0; i < node.attributes.length; i++) {\n const attr = node.attributes[i]\n result[attr.name] = attr.value\n }\n return result\n}\n\nexport class GracefulDegradeBoundary extends Component<\n ErrorBoundaryProps,\n ErrorBoundaryState\n> {\n private rootHtml: string\n private htmlAttributes: Record<string, string>\n private htmlRef: React.RefObject<HTMLHtmlElement | null>\n\n constructor(props: ErrorBoundaryProps) {\n super(props)\n this.state = { hasError: false }\n this.rootHtml = ''\n this.htmlAttributes = {}\n this.htmlRef = createRef<HTMLHtmlElement>()\n }\n\n static getDerivedStateFromError(_: unknown): ErrorBoundaryState {\n return { hasError: true }\n }\n\n componentDidMount() {\n const htmlNode = this.htmlRef.current\n if (this.state.hasError && htmlNode) {\n // Reapply the cached HTML attributes to the root element\n Object.entries(this.htmlAttributes).forEach(([key, value]) => {\n htmlNode.setAttribute(key, value)\n })\n }\n }\n\n render() {\n const { hasError } = this.state\n // Cache the root HTML content on the first render\n if (typeof window !== 'undefined' && !this.rootHtml) {\n this.rootHtml = document.documentElement.innerHTML\n this.htmlAttributes = getDomNodeAttributes(document.documentElement)\n }\n\n if (hasError) {\n // Render the current HTML content without hydration\n return (\n <html\n ref={this.htmlRef}\n suppressHydrationWarning\n dangerouslySetInnerHTML={{\n __html: this.rootHtml,\n }}\n />\n )\n }\n\n return this.props.children\n }\n}\n\nexport default GracefulDegradeBoundary\n","import { useContext } from 'react'\nimport { PathnameContext } from '../../shared/lib/hooks-client-context.shared-runtime'\n\n/**\n * This checks to see if the current render has any unknown route parameters that\n * would cause the pathname to be dynamic. It's used to trigger a different\n * render path in the error boundary.\n *\n * @returns true if there are any unknown route parameters, false otherwise\n */\nfunction hasFallbackRouteParams(): boolean {\n if (typeof window === 'undefined') {\n // AsyncLocalStorage should not be included in the client bundle.\n const { workUnitAsyncStorage } =\n require('../../server/app-render/work-unit-async-storage.external') as typeof import('../../server/app-render/work-unit-async-storage.external')\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!workUnitStore) return false\n\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n const fallbackParams = workUnitStore.fallbackRouteParams\n return fallbackParams ? fallbackParams.size > 0 : false\n case 'prerender-legacy':\n case 'request':\n case 'prerender-runtime':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n break\n default:\n workUnitStore satisfies never\n }\n\n return false\n }\n\n return false\n}\n\n/**\n * This returns a `null` value if there are any unknown route parameters, and\n * otherwise returns the pathname from the context. This is an alternative to\n * `usePathname` that is used in the error boundary to avoid rendering the\n * error boundary when there are unknown route parameters. This doesn't throw\n * when accessed with unknown route parameters.\n *\n * @returns\n *\n * @internal\n */\nexport function useUntrackedPathname(): string | null {\n // If there are any unknown route parameters we would typically throw\n // an error, but this internal method allows us to return a null value instead\n // for components that do not propagate the pathname to the static shell (like\n // the error boundary).\n if (hasFallbackRouteParams()) {\n return null\n }\n\n // This shouldn't cause any issues related to conditional rendering because\n // the environment will be consistent for the render.\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return useContext(PathnameContext)\n}\n","'use client'\n\nimport React, { type JSX } from 'react'\nimport { useUntrackedPathname } from './navigation-untracked'\nimport { isNextRouterError } from './is-next-router-error'\nimport { handleHardNavError } from './nav-failure-handler'\nimport { HandleISRError } from './handle-isr-error'\nimport { isBot } from '../../shared/lib/router/utils/is-bot'\n\nconst isBotUserAgent =\n typeof window !== 'undefined' && isBot(window.navigator.userAgent)\n\nexport type ErrorComponent = React.ComponentType<{\n error: Error\n // global-error, there's no `reset` function;\n // regular error boundary, there's a `reset` function.\n reset?: () => void\n}>\n\nexport interface ErrorBoundaryProps {\n children?: React.ReactNode\n errorComponent: ErrorComponent | undefined\n errorStyles?: React.ReactNode | undefined\n errorScripts?: React.ReactNode | undefined\n}\n\ninterface ErrorBoundaryHandlerProps extends ErrorBoundaryProps {\n pathname: string | null\n errorComponent: ErrorComponent\n}\n\ninterface ErrorBoundaryHandlerState {\n error: Error | null\n previousPathname: string | null\n}\n\nexport class ErrorBoundaryHandler extends React.Component<\n ErrorBoundaryHandlerProps,\n ErrorBoundaryHandlerState\n> {\n constructor(props: ErrorBoundaryHandlerProps) {\n super(props)\n this.state = { error: null, previousPathname: this.props.pathname }\n }\n\n static getDerivedStateFromError(error: Error) {\n if (isNextRouterError(error)) {\n // Re-throw if an expected internal Next.js router error occurs\n // this means it should be handled by a different boundary (such as a NotFound boundary in a parent segment)\n throw error\n }\n\n return { error }\n }\n\n static getDerivedStateFromProps(\n props: ErrorBoundaryHandlerProps,\n state: ErrorBoundaryHandlerState\n ): ErrorBoundaryHandlerState | null {\n const { error } = state\n\n // if we encounter an error while\n // a navigation is pending we shouldn't render\n // the error boundary and instead should fallback\n // to a hard navigation to attempt recovering\n if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {\n if (error && handleHardNavError(error)) {\n // clear error so we don't render anything\n return {\n error: null,\n previousPathname: props.pathname,\n }\n }\n }\n\n /**\n * Handles reset of the error boundary when a navigation happens.\n * Ensures the error boundary does not stay enabled when navigating to a new page.\n * Approach of setState in render is safe as it checks the previous pathname and then overrides\n * it as outlined in https://react.dev/reference/react/useState#storing-information-from-previous-renders\n */\n if (props.pathname !== state.previousPathname && state.error) {\n return {\n error: null,\n previousPathname: props.pathname,\n }\n }\n return {\n error: state.error,\n previousPathname: props.pathname,\n }\n }\n\n reset = () => {\n this.setState({ error: null })\n }\n\n // Explicit type is needed to avoid the generated `.d.ts` having a wide return type that could be specific to the `@types/react` version.\n render(): React.ReactNode {\n //When it's bot request, segment level error boundary will keep rendering the children,\n // the final error will be caught by the root error boundary and determine wether need to apply graceful degrade.\n if (this.state.error && !isBotUserAgent) {\n return (\n <>\n <HandleISRError error={this.state.error} />\n {this.props.errorStyles}\n {this.props.errorScripts}\n <this.props.errorComponent\n error={this.state.error}\n reset={this.reset}\n />\n </>\n )\n }\n\n return this.props.children\n }\n}\n\n/**\n * Handles errors through `getDerivedStateFromError`.\n * Renders the provided error component and provides a way to `reset` the error boundary state.\n */\n\n/**\n * Renders error boundary with the provided \"errorComponent\" property as the fallback.\n * If no \"errorComponent\" property is provided it renders the children without an error boundary.\n */\nexport function ErrorBoundary({\n errorComponent,\n errorStyles,\n errorScripts,\n children,\n}: ErrorBoundaryProps & {\n children: React.ReactNode\n}): JSX.Element {\n // When we're rendering the missing params shell, this will return null. This\n // is because we won't be rendering any not found boundaries or error\n // boundaries for the missing params shell. When this runs on the client\n // (where these errors can occur), we will get the correct pathname.\n const pathname = useUntrackedPathname()\n if (errorComponent) {\n return (\n <ErrorBoundaryHandler\n pathname={pathname}\n errorComponent={errorComponent}\n errorStyles={errorStyles}\n errorScripts={errorScripts}\n >\n {children}\n </ErrorBoundaryHandler>\n )\n }\n\n return <>{children}</>\n}\n","'use client'\n\nimport React, { type JSX } from 'react'\nimport GracefulDegradeBoundary from './graceful-degrade-boundary'\nimport { ErrorBoundary, type ErrorBoundaryProps } from '../error-boundary'\nimport { isBot } from '../../../shared/lib/router/utils/is-bot'\n\nconst isBotUserAgent =\n typeof window !== 'undefined' && isBot(window.navigator.userAgent)\n\nexport default function RootErrorBoundary({\n children,\n errorComponent,\n errorStyles,\n errorScripts,\n}: ErrorBoundaryProps & { children: React.ReactNode }): JSX.Element {\n if (isBotUserAgent) {\n // Preserve existing DOM/HTML for bots to avoid replacing content with an error UI\n // and to keep the original SSR output intact.\n return <GracefulDegradeBoundary>{children}</GracefulDegradeBoundary>\n }\n\n return (\n <ErrorBoundary\n errorComponent={errorComponent}\n errorStyles={errorStyles}\n errorScripts={errorScripts}\n >\n {children}\n </ErrorBoundary>\n )\n}\n","'use client'\n\nimport type { ReactNode } from 'react'\nimport {\n METADATA_BOUNDARY_NAME,\n VIEWPORT_BOUNDARY_NAME,\n OUTLET_BOUNDARY_NAME,\n ROOT_LAYOUT_BOUNDARY_NAME,\n} from './boundary-constants'\n\n// We use a namespace object to allow us to recover the name of the function\n// at runtime even when production bundling/minification is used.\nconst NameSpace = {\n [METADATA_BOUNDARY_NAME]: function ({ children }: { children: ReactNode }) {\n return children\n },\n [VIEWPORT_BOUNDARY_NAME]: function ({ children }: { children: ReactNode }) {\n return children\n },\n [OUTLET_BOUNDARY_NAME]: function ({ children }: { children: ReactNode }) {\n return children\n },\n [ROOT_LAYOUT_BOUNDARY_NAME]: function ({\n children,\n }: {\n children: ReactNode\n }) {\n return children\n },\n}\n\nexport const MetadataBoundary =\n // We use slice(0) to trick the bundler into not inlining/minifying the function\n // so it retains the name inferred from the namespace object\n NameSpace[METADATA_BOUNDARY_NAME.slice(0) as typeof METADATA_BOUNDARY_NAME]\n\nexport const ViewportBoundary =\n // We use slice(0) to trick the bundler into not inlining/minifying the function\n // so it retains the name inferred from the namespace object\n NameSpace[VIEWPORT_BOUNDARY_NAME.slice(0) as typeof VIEWPORT_BOUNDARY_NAME]\n\nexport const OutletBoundary =\n // We use slice(0) to trick the bundler into not inlining/minifying the function\n // so it retains the name inferred from the namespace object\n NameSpace[OUTLET_BOUNDARY_NAME.slice(0) as typeof OUTLET_BOUNDARY_NAME]\n\nexport const RootLayoutBoundary =\n // We use slice(0) to trick the bundler into not inlining/minifying the function\n // so it retains the name inferred from the namespace object\n NameSpace[\n ROOT_LAYOUT_BOUNDARY_NAME.slice(0) as typeof ROOT_LAYOUT_BOUNDARY_NAME\n ]\n","'use client'\n\nimport React, {\n useEffect,\n useMemo,\n startTransition,\n useInsertionEffect,\n useDeferredValue,\n} from 'react'\nimport {\n AppRouterContext,\n LayoutRouterContext,\n GlobalLayoutRouterContext,\n} from '../../shared/lib/app-router-context.shared-runtime'\nimport type {\n CacheNode,\n FlightRouterState,\n} from '../../shared/lib/app-router-types'\nimport { ACTION_RESTORE } from './router-reducer/router-reducer-types'\nimport type { AppRouterState } from './router-reducer/router-reducer-types'\nimport { createHrefFromUrl } from './router-reducer/create-href-from-url'\nimport {\n SearchParamsContext,\n PathnameContext,\n PathParamsContext,\n} from '../../shared/lib/hooks-client-context.shared-runtime'\nimport { dispatchAppRouterAction, useActionQueue } from './use-action-queue'\nimport { isBot } from '../../shared/lib/router/utils/is-bot'\nimport { addBasePath } from '../add-base-path'\nimport { AppRouterAnnouncer } from './app-router-announcer'\nimport { RedirectBoundary } from './redirect-boundary'\nimport { findHeadInCache } from './router-reducer/reducers/find-head-in-cache'\nimport { unresolvedThenable } from './unresolved-thenable'\nimport { removeBasePath } from '../remove-base-path'\nimport { hasBasePath } from '../has-base-path'\nimport { getSelectedParams } from './router-reducer/compute-changed-path'\nimport { useNavFailureHandler } from './nav-failure-handler'\nimport {\n dispatchTraverseAction,\n publicAppRouterInstance,\n type AppRouterActionQueue,\n type GlobalErrorState,\n} from './app-router-instance'\nimport { getRedirectTypeFromError, getURLFromRedirectError } from './redirect'\nimport { isRedirectError, RedirectType } from './redirect-error'\nimport { pingVisibleLinks } from './links'\nimport RootErrorBoundary from './errors/root-error-boundary'\nimport DefaultGlobalError from './builtin/global-error'\nimport { RootLayoutBoundary } from '../../lib/framework/boundary-components'\nimport type { StaticIndicatorState } from '../dev/hot-reloader/app/hot-reloader-app'\n\nconst globalMutable: {\n pendingMpaPath?: string\n} = {}\n\nexport function isExternalURL(url: URL) {\n return url.origin !== window.location.origin\n}\n\n/**\n * Given a link href, constructs the URL that should be prefetched. Returns null\n * in cases where prefetching should be disabled, like external URLs, or\n * during development.\n * @param href The href passed to <Link>, router.prefetch(), or similar\n * @returns A URL object to prefetch, or null if prefetching should be disabled\n */\nexport function createPrefetchURL(href: string): URL | null {\n // Don't prefetch for bots as they don't navigate.\n if (isBot(window.navigator.userAgent)) {\n return null\n }\n\n let url: URL\n try {\n url = new URL(addBasePath(href), window.location.href)\n } catch (_) {\n // TODO: Does this need to throw or can we just console.error instead? Does\n // anyone rely on this throwing? (Seems unlikely.)\n throw new Error(\n `Cannot prefetch '${href}' because it cannot be converted to a URL.`\n )\n }\n\n // Don't prefetch during development (improves compilation performance)\n if (process.env.NODE_ENV === 'development') {\n return null\n }\n\n // External urls can't be prefetched in the same way.\n if (isExternalURL(url)) {\n return null\n }\n\n return url\n}\n\nfunction HistoryUpdater({\n appRouterState,\n}: {\n appRouterState: AppRouterState\n}) {\n useInsertionEffect(() => {\n if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {\n // clear pending URL as navigation is no longer\n // in flight\n window.next.__pendingUrl = undefined\n }\n\n const { tree, pushRef, canonicalUrl } = appRouterState\n const historyState = {\n ...(pushRef.preserveCustomHistoryState ? window.history.state : {}),\n // Identifier is shortened intentionally.\n // __NA is used to identify if the history entry can be handled by the app-router.\n // __N is used to identify if the history entry can be handled by the old router.\n __NA: true,\n __PRIVATE_NEXTJS_INTERNALS_TREE: tree,\n }\n if (\n pushRef.pendingPush &&\n // Skip pushing an additional history entry if the canonicalUrl is the same as the current url.\n // This mirrors the browser behavior for normal navigation.\n createHrefFromUrl(new URL(window.location.href)) !== canonicalUrl\n ) {\n // This intentionally mutates React state, pushRef is overwritten to ensure additional push/replace calls do not trigger an additional history entry.\n pushRef.pendingPush = false\n window.history.pushState(historyState, '', canonicalUrl)\n } else {\n window.history.replaceState(historyState, '', canonicalUrl)\n }\n }, [appRouterState])\n\n useEffect(() => {\n // The Next-Url and the base tree may affect the result of a prefetch\n // task. Re-prefetch all visible links with the updated values. In most\n // cases, this will not result in any new network requests, only if\n // the prefetch result actually varies on one of these inputs.\n if (process.env.__NEXT_CLIENT_SEGMENT_CACHE) {\n pingVisibleLinks(appRouterState.nextUrl, appRouterState.tree)\n }\n }, [appRouterState.nextUrl, appRouterState.tree])\n\n return null\n}\n\nexport function createEmptyCacheNode(): CacheNode {\n return {\n lazyData: null,\n rsc: null,\n prefetchRsc: null,\n head: null,\n prefetchHead: null,\n parallelRoutes: new Map(),\n loading: null,\n navigatedAt: -1,\n }\n}\n\nfunction copyNextJsInternalHistoryState(data: any) {\n if (data == null) data = {}\n const currentState = window.history.state\n const __NA = currentState?.__NA\n if (__NA) {\n data.__NA = __NA\n }\n const __PRIVATE_NEXTJS_INTERNALS_TREE =\n currentState?.__PRIVATE_NEXTJS_INTERNALS_TREE\n if (__PRIVATE_NEXTJS_INTERNALS_TREE) {\n data.__PRIVATE_NEXTJS_INTERNALS_TREE = __PRIVATE_NEXTJS_INTERNALS_TREE\n }\n\n return data\n}\n\nfunction Head({\n headCacheNode,\n}: {\n headCacheNode: CacheNode | null\n}): React.ReactNode {\n // If this segment has a `prefetchHead`, it's the statically prefetched data.\n // We should use that on initial render instead of `head`. Then we'll switch\n // to `head` when the dynamic response streams in.\n const head = headCacheNode !== null ? headCacheNode.head : null\n const prefetchHead =\n headCacheNode !== null ? headCacheNode.prefetchHead : null\n\n // If no prefetch data is available, then we go straight to rendering `head`.\n const resolvedPrefetchRsc = prefetchHead !== null ? prefetchHead : head\n\n // We use `useDeferredValue` to handle switching between the prefetched and\n // final values. The second argument is returned on initial render, then it\n // re-renders with the first argument.\n return useDeferredValue(head, resolvedPrefetchRsc)\n}\n\n/**\n * The global router that wraps the application components.\n */\nfunction Router({\n actionQueue,\n globalError,\n webSocket,\n staticIndicatorState,\n}: {\n actionQueue: AppRouterActionQueue\n globalError: GlobalErrorState\n webSocket: WebSocket | undefined\n staticIndicatorState: StaticIndicatorState | undefined\n}) {\n const state = useActionQueue(actionQueue)\n const { canonicalUrl } = state\n // Add memoized pathname/query for useSearchParams and usePathname.\n const { searchParams, pathname } = useMemo(() => {\n const url = new URL(\n canonicalUrl,\n typeof window === 'undefined' ? 'http://n' : window.location.href\n )\n\n return {\n // This is turned into a readonly class in `useSearchParams`\n searchParams: url.searchParams,\n pathname: hasBasePath(url.pathname)\n ? removeBasePath(url.pathname)\n : url.pathname,\n }\n }, [canonicalUrl])\n\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const { cache, prefetchCache, tree } = state\n\n // This hook is in a conditional but that is ok because `process.env.NODE_ENV` never changes\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useEffect(() => {\n // Add `window.nd` for debugging purposes.\n // This is not meant for use in applications as concurrent rendering will affect the cache/tree/router.\n // @ts-ignore this is for debugging\n window.nd = {\n router: publicAppRouterInstance,\n cache,\n prefetchCache,\n tree,\n }\n }, [cache, prefetchCache, tree])\n }\n\n useEffect(() => {\n // If the app is restored from bfcache, it's possible that\n // pushRef.mpaNavigation is true, which would mean that any re-render of this component\n // would trigger the mpa navigation logic again from the lines below.\n // This will restore the router to the initial state in the event that the app is restored from bfcache.\n function handlePageShow(event: PageTransitionEvent) {\n if (\n !event.persisted ||\n !window.history.state?.__PRIVATE_NEXTJS_INTERNALS_TREE\n ) {\n return\n }\n\n // Clear the pendingMpaPath value so that a subsequent MPA navigation to the same URL can be triggered.\n // This is necessary because if the browser restored from bfcache, the pendingMpaPath would still be set to the value\n // of the last MPA navigation.\n globalMutable.pendingMpaPath = undefined\n\n dispatchAppRouterAction({\n type: ACTION_RESTORE,\n url: new URL(window.location.href),\n tree: window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE,\n })\n }\n\n window.addEventListener('pageshow', handlePageShow)\n\n return () => {\n window.removeEventListener('pageshow', handlePageShow)\n }\n }, [])\n\n useEffect(() => {\n // Ensure that any redirect errors that bubble up outside of the RedirectBoundary\n // are caught and handled by the router.\n function handleUnhandledRedirect(\n event: ErrorEvent | PromiseRejectionEvent\n ) {\n const error = 'reason' in event ? event.reason : event.error\n if (isRedirectError(error)) {\n event.preventDefault()\n const url = getURLFromRedirectError(error)\n const redirectType = getRedirectTypeFromError(error)\n // TODO: This should access the router methods directly, rather than\n // go through the public interface.\n if (redirectType === RedirectType.push) {\n publicAppRouterInstance.push(url, {})\n } else {\n publicAppRouterInstance.replace(url, {})\n }\n }\n }\n window.addEventListener('error', handleUnhandledRedirect)\n window.addEventListener('unhandledrejection', handleUnhandledRedirect)\n\n return () => {\n window.removeEventListener('error', handleUnhandledRedirect)\n window.removeEventListener('unhandledrejection', handleUnhandledRedirect)\n }\n }, [])\n\n // When mpaNavigation flag is set do a hard navigation to the new url.\n // Infinitely suspend because we don't actually want to rerender any child\n // components with the new URL and any entangled state updates shouldn't\n // commit either (eg: useTransition isPending should stay true until the page\n // unloads).\n //\n // This is a side effect in render. Don't try this at home, kids. It's\n // probably safe because we know this is a singleton component and it's never\n // in <Offscreen>. At least I hope so. (It will run twice in dev strict mode,\n // but that's... fine?)\n const { pushRef } = state\n if (pushRef.mpaNavigation) {\n // if there's a re-render, we don't want to trigger another redirect if one is already in flight to the same URL\n if (globalMutable.pendingMpaPath !== canonicalUrl) {\n const location = window.location\n if (pushRef.pendingPush) {\n location.assign(canonicalUrl)\n } else {\n location.replace(canonicalUrl)\n }\n\n globalMutable.pendingMpaPath = canonicalUrl\n }\n // TODO-APP: Should we listen to navigateerror here to catch failed\n // navigations somehow? And should we call window.stop() if a SPA navigation\n // should interrupt an MPA one?\n // NOTE: This is intentionally using `throw` instead of `use` because we're\n // inside an externally mutable condition (pushRef.mpaNavigation), which\n // violates the rules of hooks.\n throw unresolvedThenable\n }\n\n useEffect(() => {\n const originalPushState = window.history.pushState.bind(window.history)\n const originalReplaceState = window.history.replaceState.bind(\n window.history\n )\n\n // Ensure the canonical URL in the Next.js Router is updated when the URL is changed so that `usePathname` and `useSearchParams` hold the pushed values.\n const applyUrlFromHistoryPushReplace = (\n url: string | URL | null | undefined\n ) => {\n const href = window.location.href\n const tree: FlightRouterState | undefined =\n window.history.state?.__PRIVATE_NEXTJS_INTERNALS_TREE\n\n startTransition(() => {\n dispatchAppRouterAction({\n type: ACTION_RESTORE,\n url: new URL(url ?? href, href),\n tree,\n })\n })\n }\n\n /**\n * Patch pushState to ensure external changes to the history are reflected in the Next.js Router.\n * Ensures Next.js internal history state is copied to the new history entry.\n * Ensures usePathname and useSearchParams hold the newly provided url.\n */\n window.history.pushState = function pushState(\n data: any,\n _unused: string,\n url?: string | URL | null\n ): void {\n // Avoid a loop when Next.js internals trigger pushState/replaceState\n if (data?.__NA || data?._N) {\n return originalPushState(data, _unused, url)\n }\n\n data = copyNextJsInternalHistoryState(data)\n\n if (url) {\n applyUrlFromHistoryPushReplace(url)\n }\n\n return originalPushState(data, _unused, url)\n }\n\n /**\n * Patch replaceState to ensure external changes to the history are reflected in the Next.js Router.\n * Ensures Next.js internal history state is copied to the new history entry.\n * Ensures usePathname and useSearchParams hold the newly provided url.\n */\n window.history.replaceState = function replaceState(\n data: any,\n _unused: string,\n url?: string | URL | null\n ): void {\n // Avoid a loop when Next.js internals trigger pushState/replaceState\n if (data?.__NA || data?._N) {\n return originalReplaceState(data, _unused, url)\n }\n data = copyNextJsInternalHistoryState(data)\n\n if (url) {\n applyUrlFromHistoryPushReplace(url)\n }\n return originalReplaceState(data, _unused, url)\n }\n\n /**\n * Handle popstate event, this is used to handle back/forward in the browser.\n * By default dispatches ACTION_RESTORE, however if the history entry was not pushed/replaced by app-router it will reload the page.\n * That case can happen when the old router injected the history entry.\n */\n const onPopState = (event: PopStateEvent) => {\n if (!event.state) {\n // TODO-APP: this case only happens when pushState/replaceState was called outside of Next.js. It should probably reload the page in this case.\n return\n }\n\n // This case happens when the history entry was pushed by the `pages` router.\n if (!event.state.__NA) {\n window.location.reload()\n return\n }\n\n // TODO-APP: Ideally the back button should not use startTransition as it should apply the updates synchronously\n // Without startTransition works if the cache is there for this path\n startTransition(() => {\n dispatchTraverseAction(\n window.location.href,\n event.state.__PRIVATE_NEXTJS_INTERNALS_TREE\n )\n })\n }\n\n // Register popstate event to call onPopstate.\n window.addEventListener('popstate', onPopState)\n return () => {\n window.history.pushState = originalPushState\n window.history.replaceState = originalReplaceState\n window.removeEventListener('popstate', onPopState)\n }\n }, [])\n\n const { cache, tree, nextUrl, focusAndScrollRef } = state\n\n const matchingHead = useMemo(() => {\n return findHeadInCache(cache, tree[1])\n }, [cache, tree])\n\n // Add memoized pathParams for useParams.\n const pathParams = useMemo(() => {\n return getSelectedParams(tree)\n }, [tree])\n\n const layoutRouterContext = useMemo(() => {\n return {\n parentTree: tree,\n parentCacheNode: cache,\n parentSegmentPath: null,\n // Root node always has `url`\n // Provided in AppTreeContext to ensure it can be overwritten in layout-router\n url: canonicalUrl,\n }\n }, [tree, cache, canonicalUrl])\n\n const globalLayoutRouterContext = useMemo(() => {\n return {\n tree,\n focusAndScrollRef,\n nextUrl,\n }\n }, [tree, focusAndScrollRef, nextUrl])\n\n let head\n if (matchingHead !== null) {\n // The head is wrapped in an extra component so we can use\n // `useDeferredValue` to swap between the prefetched and final versions of\n // the head. (This is what LayoutRouter does for segment data, too.)\n //\n // The `key` is used to remount the component whenever the head moves to\n // a different segment.\n const [headCacheNode, headKey, headKeyWithoutSearchParams] = matchingHead\n\n head = (\n <Head\n key={\n // Necessary for PPR: omit search params from the key to match prerendered keys\n typeof window === 'undefined' ? headKeyWithoutSearchParams : headKey\n }\n headCacheNode={headCacheNode}\n />\n )\n } else {\n head = null\n }\n\n let content = (\n <RedirectBoundary>\n {head}\n {/* RootLayoutBoundary enables detection of Suspense boundaries around the root layout.\n When users wrap their layout in <Suspense>, this creates the component stack pattern\n \"Suspense -> RootLayoutBoundary\" which dynamic-rendering.ts uses to allow dynamic rendering. */}\n <RootLayoutBoundary>{cache.rsc}</RootLayoutBoundary>\n <AppRouterAnnouncer tree={tree} />\n </RedirectBoundary>\n )\n\n if (process.env.NODE_ENV !== 'production') {\n // In development, we apply few error boundaries and hot-reloader:\n // - DevRootHTTPAccessFallbackBoundary: avoid using navigation API like notFound() in root layout\n // - HotReloader:\n // - hot-reload the app when the code changes\n // - render dev overlay\n // - catch runtime errors and display global-error when necessary\n if (typeof window !== 'undefined') {\n const { DevRootHTTPAccessFallbackBoundary } =\n require('./dev-root-http-access-fallback-boundary') as typeof import('./dev-root-http-access-fallback-boundary')\n content = (\n <DevRootHTTPAccessFallbackBoundary>\n {content}\n </DevRootHTTPAccessFallbackBoundary>\n )\n }\n const HotReloader: typeof import('../dev/hot-reloader/app/hot-reloader-app').default =\n (\n require('../dev/hot-reloader/app/hot-reloader-app') as typeof import('../dev/hot-reloader/app/hot-reloader-app')\n ).default\n\n content = (\n <HotReloader\n globalError={globalError}\n webSocket={webSocket}\n staticIndicatorState={staticIndicatorState}\n >\n {content}\n </HotReloader>\n )\n } else {\n content = (\n <RootErrorBoundary\n errorComponent={globalError[0]}\n errorStyles={globalError[1]}\n >\n {content}\n </RootErrorBoundary>\n )\n }\n\n return (\n <>\n <HistoryUpdater appRouterState={state} />\n <RuntimeStyles />\n <PathParamsContext.Provider value={pathParams}>\n <PathnameContext.Provider value={pathname}>\n <SearchParamsContext.Provider value={searchParams}>\n <GlobalLayoutRouterContext.Provider\n value={globalLayoutRouterContext}\n >\n {/* TODO: We should be able to remove this context. useRouter\n should import from app-router-instance instead. It's only\n necessary because useRouter is shared between Pages and\n App Router. We should fork that module, then remove this\n context provider. */}\n <AppRouterContext.Provider value={publicAppRouterInstance}>\n <LayoutRouterContext.Provider value={layoutRouterContext}>\n {content}\n </LayoutRouterContext.Provider>\n </AppRouterContext.Provider>\n </GlobalLayoutRouterContext.Provider>\n </SearchParamsContext.Provider>\n </PathnameContext.Provider>\n </PathParamsContext.Provider>\n </>\n )\n}\n\nexport default function AppRouter({\n actionQueue,\n globalErrorState,\n webSocket,\n staticIndicatorState,\n}: {\n actionQueue: AppRouterActionQueue\n globalErrorState: GlobalErrorState\n webSocket?: WebSocket\n staticIndicatorState?: StaticIndicatorState\n}) {\n useNavFailureHandler()\n\n const router = (\n <Router\n actionQueue={actionQueue}\n globalError={globalErrorState}\n webSocket={webSocket}\n staticIndicatorState={staticIndicatorState}\n />\n )\n\n // At the very top level, use the default GlobalError component as the final fallback.\n // When the app router itself fails, which means the framework itself fails, we show the default error.\n return (\n <RootErrorBoundary errorComponent={DefaultGlobalError}>\n {router}\n </RootErrorBoundary>\n )\n}\n\nconst runtimeStyles = new Set<string>()\nlet runtimeStyleChanged = new Set<() => void>()\n\nglobalThis._N_E_STYLE_LOAD = function (href: string) {\n let len = runtimeStyles.size\n runtimeStyles.add(href)\n if (runtimeStyles.size !== len) {\n runtimeStyleChanged.forEach((cb) => cb())\n }\n // TODO figure out how to get a promise here\n // But maybe it's not necessary as react would block rendering until it's loaded\n return Promise.resolve()\n}\n\nfunction RuntimeStyles() {\n const [, forceUpdate] = React.useState(0)\n const renderedStylesSize = runtimeStyles.size\n useEffect(() => {\n const changed = () => forceUpdate((c) => c + 1)\n runtimeStyleChanged.add(changed)\n if (renderedStylesSize !== runtimeStyles.size) {\n changed()\n }\n return () => {\n runtimeStyleChanged.delete(changed)\n }\n }, [renderedStylesSize, forceUpdate])\n\n const dplId = process.env.NEXT_DEPLOYMENT_ID\n ? `?dpl=${process.env.NEXT_DEPLOYMENT_ID}`\n : ''\n return [...runtimeStyles].map((href, i) => (\n <link\n key={i}\n rel=\"stylesheet\"\n href={`${href}${dplId}`}\n // @ts-ignore\n precedence=\"next\"\n // TODO figure out crossOrigin and nonce\n // crossOrigin={TODO}\n // nonce={TODO}\n />\n ))\n}\n","import type {\n CacheNodeSeedData,\n FlightRouterState,\n FlightSegmentPath,\n Segment,\n} from '../../../shared/lib/app-router-types'\nimport type {\n CacheNode,\n ChildSegmentMap,\n ReadyCacheNode,\n} from '../../../shared/lib/app-router-types'\nimport type {\n HeadData,\n LoadingModuleData,\n} from '../../../shared/lib/app-router-types'\nimport { DEFAULT_SEGMENT_KEY } from '../../../shared/lib/segment'\nimport { matchSegment } from '../match-segments'\nimport { createRouterCacheKey } from './create-router-cache-key'\nimport type { FetchServerResponseResult } from './fetch-server-response'\nimport { isNavigatingToNewRootLayout } from './is-navigating-to-new-root-layout'\nimport { DYNAMIC_STALETIME_MS } from './prefetch-cache-utils'\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.\ntype SPANavigationTask = {\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. If\n // `children` is null (i.e. if this is a terminal task node), then `node`\n // represents a brand new Cache Node tree, which way or may not need to be\n // filled with dynamic data from the server.\n node: CacheNode | null\n // The tree sent to the server during the dynamic request. This is the\n // same as `route`, except with the `refetch` marker set on dynamic segments.\n // If all the segments are static, then this will be null, and no server\n // request is required.\n dynamicRequestTree: FlightRouterState | null\n children: Map<string, SPANavigationTask> | null\n}\n\n// A special type used to bail out and trigger a full-page navigation.\ntype MPANavigationTask = {\n // MPA tasks are distinguised from SPA tasks by having a null `route`.\n route: null\n node: null\n dynamicRequestTree: null\n children: null\n}\n\nconst MPA_NAVIGATION_TASK: MPANavigationTask = {\n route: null,\n node: null,\n dynamicRequestTree: null,\n children: null,\n}\n\nexport type Task = SPANavigationTask | MPANavigationTask\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 oldCacheNode: CacheNode,\n oldRouterState: FlightRouterState,\n newRouterState: FlightRouterState,\n prefetchData: CacheNodeSeedData | null,\n prefetchHead: HeadData | null,\n isPrefetchHeadPartial: boolean,\n isSamePageNavigation: boolean,\n scrollableSegmentsResult: Array<FlightSegmentPath>\n): Task | null {\n const segmentPath: Array<FlightSegmentPath> = []\n return updateCacheNodeOnNavigation(\n navigatedAt,\n oldCacheNode,\n oldRouterState,\n newRouterState,\n false,\n prefetchData,\n prefetchHead,\n isPrefetchHeadPartial,\n isSamePageNavigation,\n segmentPath,\n scrollableSegmentsResult\n )\n}\n\nfunction updateCacheNodeOnNavigation(\n navigatedAt: number,\n oldCacheNode: CacheNode,\n oldRouterState: FlightRouterState,\n newRouterState: FlightRouterState,\n didFindRootLayout: boolean,\n prefetchData: CacheNodeSeedData | null,\n prefetchHead: HeadData | null,\n isPrefetchHeadPartial: boolean,\n isSamePageNavigation: boolean,\n segmentPath: FlightSegmentPath,\n scrollableSegmentsResult: Array<FlightSegmentPath>\n): Task | null {\n // Diff the old and new trees to reuse the shared layouts.\n const oldRouterStateChildren = oldRouterState[1]\n const newRouterStateChildren = newRouterState[1]\n const prefetchDataChildren = prefetchData !== null ? prefetchData[2] : null\n\n if (!didFindRootLayout) {\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. See beginRenderingNewRouteTree for context.\n const isRootLayout = newRouterState[4] === true\n if (isRootLayout) {\n // Found a matching root layout.\n didFindRootLayout = true\n }\n }\n\n const oldParallelRoutes = oldCacheNode.parallelRoutes\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 const prefetchParallelRoutes = new Map(oldParallelRoutes)\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 needsDynamicRequest = 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. needsDynamicRequest is false at the\n // 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 const newRouterStateChild: FlightRouterState =\n newRouterStateChildren[parallelRouteKey]\n const oldRouterStateChild: FlightRouterState | void =\n oldRouterStateChildren[parallelRouteKey]\n const oldSegmentMapChild = oldParallelRoutes.get(parallelRouteKey)\n const prefetchDataChild: CacheNodeSeedData | void | null =\n prefetchDataChildren !== null\n ? prefetchDataChildren[parallelRouteKey]\n : null\n\n const newSegmentChild = newRouterStateChild[0]\n const newSegmentPathChild = segmentPath.concat([\n parallelRouteKey,\n newSegmentChild,\n ])\n const newSegmentKeyChild = createRouterCacheKey(newSegmentChild)\n\n const oldSegmentChild =\n oldRouterStateChild !== undefined ? oldRouterStateChild[0] : undefined\n\n const oldCacheNodeChild =\n oldSegmentMapChild !== undefined\n ? oldSegmentMapChild.get(newSegmentKeyChild)\n : undefined\n\n let taskChild: Task | null\n if (newSegmentChild === DEFAULT_SEGMENT_KEY) {\n // This is another kind of leaf segment — a default route.\n //\n // Default routes have special behavior. When there's no matching segment\n // for a parallel route, Next.js preserves the currently active segment\n // during a client navigation — but not for initial render. The server\n // leaves it to the client to account for this. So we need to handle\n // it here.\n if (oldRouterStateChild !== undefined) {\n // Reuse the existing Router State for this segment. We spawn a \"task\"\n // just to keep track of the updated router state; unlike most, it's\n // already fulfilled and won't be affected by the dynamic response.\n taskChild = spawnReusedTask(oldRouterStateChild)\n } else {\n // There's no currently active segment. Switch to the \"create\" path.\n taskChild = beginRenderingNewRouteTree(\n navigatedAt,\n oldRouterStateChild,\n newRouterStateChild,\n oldCacheNodeChild,\n didFindRootLayout,\n prefetchDataChild !== undefined ? prefetchDataChild : null,\n prefetchHead,\n isPrefetchHeadPartial,\n newSegmentPathChild,\n scrollableSegmentsResult\n )\n }\n } else if (\n isSamePageNavigation &&\n // Check if this is a page segment.\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 Object.keys(newRouterStateChild[1]).length === 0\n ) {\n // We special case navigations to the exact same URL as the current\n // location. It's a common UI pattern for apps to refresh when you click a\n // link to the current page. So when this happens, we refresh the dynamic\n // data in the page segments.\n //\n // Note that this does not apply if the any part of the hash or search\n // query has changed. This might feel a bit weird but it makes more sense\n // when you consider that the way to trigger this behavior is to click\n // the same link multiple times.\n //\n // TODO: We should probably refresh the *entire* route when this case\n // occurs, not just the page segments. Essentially treating it the same as\n // a refresh() triggered by an action, which is the more explicit way of\n // modeling the UI pattern described above.\n //\n // Also note that this only refreshes the dynamic data, not static/\n // cached data. If the page segment is fully static and prefetched, the\n // request is skipped. (This is also how refresh() works.)\n taskChild = beginRenderingNewRouteTree(\n navigatedAt,\n oldRouterStateChild,\n newRouterStateChild,\n oldCacheNodeChild,\n didFindRootLayout,\n prefetchDataChild !== undefined ? prefetchDataChild : null,\n prefetchHead,\n isPrefetchHeadPartial,\n newSegmentPathChild,\n scrollableSegmentsResult\n )\n } else if (\n oldRouterStateChild !== undefined &&\n oldSegmentChild !== undefined &&\n matchSegment(newSegmentChild, oldSegmentChild)\n ) {\n if (\n oldCacheNodeChild !== undefined &&\n oldRouterStateChild !== undefined\n ) {\n // This segment exists in both the old and new trees. Recursively update\n // the children.\n taskChild = updateCacheNodeOnNavigation(\n navigatedAt,\n oldCacheNodeChild,\n oldRouterStateChild,\n newRouterStateChild,\n didFindRootLayout,\n prefetchDataChild,\n prefetchHead,\n isPrefetchHeadPartial,\n isSamePageNavigation,\n newSegmentPathChild,\n scrollableSegmentsResult\n )\n } else {\n // There's no existing Cache Node for this segment. Switch to the\n // \"create\" path.\n taskChild = beginRenderingNewRouteTree(\n navigatedAt,\n oldRouterStateChild,\n newRouterStateChild,\n oldCacheNodeChild,\n didFindRootLayout,\n prefetchDataChild !== undefined ? prefetchDataChild : null,\n prefetchHead,\n isPrefetchHeadPartial,\n newSegmentPathChild,\n scrollableSegmentsResult\n )\n }\n } else {\n // This is a new tree. Switch to the \"create\" path.\n taskChild = beginRenderingNewRouteTree(\n navigatedAt,\n oldRouterStateChild,\n newRouterStateChild,\n oldCacheNodeChild,\n didFindRootLayout,\n prefetchDataChild !== undefined ? prefetchDataChild : null,\n prefetchHead,\n isPrefetchHeadPartial,\n newSegmentPathChild,\n scrollableSegmentsResult\n )\n }\n\n if (taskChild !== null) {\n // Recursively propagate up the child tasks.\n\n if (taskChild.route === null) {\n // One of the child tasks discovered a change to the root layout.\n // Immediately unwind from this recursive traversal.\n return MPA_NAVIGATION_TASK\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(oldSegmentMapChild)\n newSegmentMapChild.set(newSegmentKeyChild, newCacheNodeChild)\n prefetchParallelRoutes.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 needsDynamicRequest = true\n dynamicRequestTreeChildren[parallelRouteKey] = dynamicRequestTreeChild\n } else {\n dynamicRequestTreeChildren[parallelRouteKey] = taskChildRoute\n }\n } else {\n // The child didn't change. We can use the prefetched router state.\n patchedRouterStateChildren[parallelRouteKey] = newRouterStateChild\n dynamicRequestTreeChildren[parallelRouteKey] = newRouterStateChild\n }\n }\n\n if (taskChildren === null) {\n // No new tasks were spawned.\n return null\n }\n\n const newCacheNode: ReadyCacheNode = {\n lazyData: null,\n rsc: oldCacheNode.rsc,\n // We intentionally aren't updating the prefetchRsc field, since this node\n // is already part of the current tree, because it would be weird for\n // prefetch data to be newer than the final data. It probably won't ever be\n // observable anyway, but it could happen if the segment is unmounted then\n // mounted again, because LayoutRouter will momentarily switch to rendering\n // prefetchRsc, via useDeferredValue.\n prefetchRsc: oldCacheNode.prefetchRsc,\n head: oldCacheNode.head,\n prefetchHead: oldCacheNode.prefetchHead,\n loading: oldCacheNode.loading,\n\n // Everything is cloned except for the children, which we computed above.\n parallelRoutes: prefetchParallelRoutes,\n\n navigatedAt,\n }\n\n return {\n // Return a cloned copy of the router state with updated children.\n route: patchRouterStateWithNewChildren(\n newRouterState,\n patchedRouterStateChildren\n ),\n node: newCacheNode,\n dynamicRequestTree: needsDynamicRequest\n ? patchRouterStateWithNewChildren(\n newRouterState,\n dynamicRequestTreeChildren\n )\n : null,\n children: taskChildren,\n }\n}\n\nfunction beginRenderingNewRouteTree(\n navigatedAt: number,\n oldRouterState: FlightRouterState | void,\n newRouterState: FlightRouterState,\n existingCacheNode: CacheNode | void,\n didFindRootLayout: boolean,\n prefetchData: CacheNodeSeedData | null,\n possiblyPartialPrefetchHead: HeadData | null,\n isPrefetchHeadPartial: boolean,\n segmentPath: FlightSegmentPath,\n scrollableSegmentsResult: Array<FlightSegmentPath>\n): Task {\n if (!didFindRootLayout) {\n // The route tree changed before we reached a layout. (The highest-level\n // layout in a route tree is referred to as the \"root\" layout.) This could\n // mean that we're navigating between two different root layouts. When this\n // happens, we perform a full-page (MPA-style) 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 because\n // we're re-rendering a segment outside of the root layout does not mean we\n // should trigger a full-page navigation.\n //\n // Specifically, we handle dynamic parameters differently: two segments are\n // 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 unchanged.\n // In the common case, this branch is skipped completely.\n if (\n oldRouterState === undefined ||\n isNavigatingToNewRootLayout(oldRouterState, newRouterState)\n ) {\n // The root layout changed. Perform a full-page navigation.\n return MPA_NAVIGATION_TASK\n }\n }\n return createCacheNodeOnNavigation(\n navigatedAt,\n newRouterState,\n existingCacheNode,\n prefetchData,\n possiblyPartialPrefetchHead,\n isPrefetchHeadPartial,\n segmentPath,\n scrollableSegmentsResult\n )\n}\n\nfunction createCacheNodeOnNavigation(\n navigatedAt: number,\n routerState: FlightRouterState,\n existingCacheNode: CacheNode | void,\n prefetchData: CacheNodeSeedData | null,\n possiblyPartialPrefetchHead: HeadData | null,\n isPrefetchHeadPartial: boolean,\n segmentPath: FlightSegmentPath,\n scrollableSegmentsResult: Array<FlightSegmentPath>\n): SPANavigationTask {\n // Same traversal as updateCacheNodeNavigation, but we switch to this path\n // once we reach the part of the tree that was not in the previous route. We\n // don't need to diff against the old tree, we just need to create a new one.\n\n // The head is assigned to every leaf segment delivered by the server. Based\n // on corresponding logic in fill-lazy-items-till-leaf-with-head.ts\n const routerStateChildren = routerState[1]\n const isLeafSegment = Object.keys(routerStateChildren).length === 0\n\n // Even we're rendering inside the \"new\" part of the target tree, we may have\n // a locally cached segment that we can reuse. This may come from either 1)\n // the CacheNode tree, which lives in React state and is populated by previous\n // navigations; or 2) the prefetch cache, which is a separate cache that is\n // populated by prefetches.\n let rsc: React.ReactNode\n let loading: LoadingModuleData | Promise<LoadingModuleData>\n let head: HeadData | null\n let cacheNodeNavigatedAt: number\n if (\n existingCacheNode !== undefined &&\n // DYNAMIC_STALETIME_MS defaults to 0, but it can be increased using\n // the experimental.staleTimes.dynamic config. When set, we'll avoid\n // refetching dynamic data if it was fetched within the given threshold.\n existingCacheNode.navigatedAt + DYNAMIC_STALETIME_MS > navigatedAt\n ) {\n // We have an existing CacheNode for this segment, and it's not stale. We\n // should reuse it rather than request a new one.\n rsc = existingCacheNode.rsc\n loading = existingCacheNode.loading\n head = existingCacheNode.head\n\n // Don't update the navigatedAt timestamp, since we're reusing stale data.\n cacheNodeNavigatedAt = existingCacheNode.navigatedAt\n } else if (prefetchData !== null) {\n // There's no existing CacheNode for this segment, but we do have prefetch\n // data. If the prefetch data is fully static (i.e. does not contain any\n // dynamic holes), we don't need to request it from the server.\n rsc = prefetchData[1]\n loading = prefetchData[3]\n head = isLeafSegment ? possiblyPartialPrefetchHead : null\n // Even though we're accessing the data from the prefetch cache, this is\n // conceptually a new segment, not a reused one. So we should update the\n // navigatedAt timestamp.\n cacheNodeNavigatedAt = navigatedAt\n const isPrefetchRscPartial = prefetchData[4]\n if (\n // Check if the segment data is partial\n isPrefetchRscPartial ||\n // Check if the head is partial (only relevant if this is a leaf segment)\n (isPrefetchHeadPartial && isLeafSegment)\n ) {\n // We only have partial data from this segment. Like missing segments, we\n // must request the full data from the server.\n return spawnPendingTask(\n navigatedAt,\n routerState,\n prefetchData,\n possiblyPartialPrefetchHead,\n isPrefetchHeadPartial,\n segmentPath,\n scrollableSegmentsResult\n )\n } else {\n // The prefetch data is fully static, so we can omit it from the\n // navigation request.\n }\n } else {\n // There's no prefetch for this segment. Everything from this point will be\n // requested from the server, even if there are static children below it.\n // Create a terminal task node that will later be fulfilled by\n // server response.\n return spawnPendingTask(\n navigatedAt,\n routerState,\n null,\n possiblyPartialPrefetchHead,\n isPrefetchHeadPartial,\n segmentPath,\n scrollableSegmentsResult\n )\n }\n\n // We already have a full segment we can render, so we don't need to request a\n // new one from the server. Keep traversing down the tree until we reach\n // something that requires a dynamic request.\n const prefetchDataChildren = prefetchData !== null ? prefetchData[2] : null\n const taskChildren = new Map()\n const existingCacheNodeChildren =\n existingCacheNode !== undefined ? existingCacheNode.parallelRoutes : null\n const cacheNodeChildren = new Map(existingCacheNodeChildren)\n let dynamicRequestTreeChildren: {\n [parallelRouteKey: string]: FlightRouterState\n } = {}\n let needsDynamicRequest = false\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 // 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 scrollableSegmentsResult.push(segmentPath)\n } else {\n for (let parallelRouteKey in routerStateChildren) {\n const routerStateChild: FlightRouterState =\n routerStateChildren[parallelRouteKey]\n const prefetchDataChild: CacheNodeSeedData | void | null =\n prefetchDataChildren !== null\n ? prefetchDataChildren[parallelRouteKey]\n : null\n const existingSegmentMapChild =\n existingCacheNodeChildren !== null\n ? existingCacheNodeChildren.get(parallelRouteKey)\n : undefined\n const segmentChild = routerStateChild[0]\n const segmentPathChild = segmentPath.concat([\n parallelRouteKey,\n segmentChild,\n ])\n const segmentKeyChild = createRouterCacheKey(segmentChild)\n\n const existingCacheNodeChild =\n existingSegmentMapChild !== undefined\n ? existingSegmentMapChild.get(segmentKeyChild)\n : undefined\n\n const taskChild = createCacheNodeOnNavigation(\n navigatedAt,\n routerStateChild,\n existingCacheNodeChild,\n prefetchDataChild,\n possiblyPartialPrefetchHead,\n isPrefetchHeadPartial,\n segmentPathChild,\n scrollableSegmentsResult\n )\n taskChildren.set(parallelRouteKey, taskChild)\n const dynamicRequestTreeChild = taskChild.dynamicRequestTree\n if (dynamicRequestTreeChild !== null) {\n // Something in the child tree is dynamic.\n needsDynamicRequest = true\n dynamicRequestTreeChildren[parallelRouteKey] = dynamicRequestTreeChild\n } else {\n dynamicRequestTreeChildren[parallelRouteKey] = routerStateChild\n }\n const newCacheNodeChild = taskChild.node\n if (newCacheNodeChild !== null) {\n const newSegmentMapChild: ChildSegmentMap = new Map()\n newSegmentMapChild.set(segmentKeyChild, newCacheNodeChild)\n cacheNodeChildren.set(parallelRouteKey, newSegmentMapChild)\n }\n }\n }\n\n return {\n // Since we're inside a new route tree, unlike the\n // `updateCacheNodeOnNavigation` path, the router state on the children\n // tasks is always the same as the router state we pass in. So we don't need\n // to clone/modify it.\n route: routerState,\n node: {\n lazyData: null,\n // Since this segment is already full, we don't need to use the\n // `prefetchRsc` field.\n rsc,\n prefetchRsc: null,\n head,\n prefetchHead: null,\n loading,\n parallelRoutes: cacheNodeChildren,\n navigatedAt: cacheNodeNavigatedAt,\n },\n dynamicRequestTree: needsDynamicRequest\n ? patchRouterStateWithNewChildren(routerState, dynamicRequestTreeChildren)\n : 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 spawnPendingTask(\n navigatedAt: number,\n routerState: FlightRouterState,\n prefetchData: CacheNodeSeedData | null,\n prefetchHead: HeadData | null,\n isPrefetchHeadPartial: boolean,\n segmentPath: FlightSegmentPath,\n scrollableSegmentsResult: Array<FlightSegmentPath>\n): SPANavigationTask {\n // Create a task that will later be fulfilled by data from the server.\n\n // Clone the prefetched route tree and the `refetch` marker to it. We'll send\n // this to the server so it knows where to start rendering.\n const dynamicRequestTree = patchRouterStateWithNewChildren(\n routerState,\n routerState[1]\n )\n dynamicRequestTree[3] = 'refetch'\n\n const newTask: Task = {\n route: routerState,\n\n // Corresponds to the part of the route that will be rendered on the server.\n node: createPendingCacheNode(\n navigatedAt,\n routerState,\n prefetchData,\n prefetchHead,\n isPrefetchHeadPartial,\n segmentPath,\n scrollableSegmentsResult\n ),\n // Because this is non-null, and it gets propagated up through the parent\n // tasks, the root task will know that it needs to perform a server request.\n dynamicRequestTree,\n children: null,\n }\n return newTask\n}\n\nfunction spawnReusedTask(reusedRouterState: FlightRouterState): Task {\n // Create a task that reuses an existing segment, e.g. when reusing\n // the current active segment in place of a default route.\n return {\n route: reusedRouterState,\n node: null,\n dynamicRequestTree: null,\n children: null,\n }\n}\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 listenForDynamicRequest(\n task: SPANavigationTask,\n responsePromise: Promise<FetchServerResponseResult>\n) {\n responsePromise.then(\n ({ flightData }: FetchServerResponseResult) => {\n if (typeof flightData === 'string') {\n // Happens when navigating to page in `pages` from `app`. We shouldn't\n // get here because should have already handled this during\n // the prefetch.\n return\n }\n for (const normalizedFlightData of flightData) {\n const {\n segmentPath,\n tree: serverRouterState,\n seedData: dynamicData,\n head: dynamicHead,\n } = normalizedFlightData\n\n if (!dynamicData) {\n // This shouldn't happen. PPR should always send back a response.\n // However, `FlightDataPath` is a shared type and the pre-PPR handling of\n // this might return null.\n continue\n }\n\n writeDynamicDataIntoPendingTask(\n task,\n segmentPath,\n serverRouterState,\n dynamicData,\n dynamicHead\n )\n }\n\n // Now that we've exhausted all the data we received from the server, if\n // there are any remaining pending tasks in the tree, abort them now.\n // If there's any missing data, it will trigger a lazy fetch.\n abortTask(task, null)\n },\n (error: any) => {\n // This will trigger an error during render\n abortTask(task, error)\n }\n )\n}\n\nfunction writeDynamicDataIntoPendingTask(\n rootTask: SPANavigationTask,\n segmentPath: FlightSegmentPath,\n serverRouterState: FlightRouterState,\n dynamicData: CacheNodeSeedData,\n dynamicHead: HeadData\n) {\n // The data sent by the server represents only a subtree of the app. We need\n // to find the part of the task tree that matches the server response, and\n // fulfill it using the dynamic data.\n //\n // segmentPath represents the parent path of subtree. It's a repeating pattern\n // of parallel route key and segment:\n //\n // [string, Segment, string, Segment, string, Segment, ...]\n //\n // Iterate through the path and finish any tasks that match this payload.\n let task = rootTask\n for (let i = 0; i < segmentPath.length; i += 2) {\n const parallelRouteKey: string = segmentPath[i]\n const segment: Segment = segmentPath[i + 1]\n const taskChildren = task.children\n if (taskChildren !== null) {\n const taskChild = taskChildren.get(parallelRouteKey)\n if (taskChild !== undefined) {\n const taskSegment = taskChild.route[0]\n if (matchSegment(segment, taskSegment)) {\n // Found a match for this task. Keep traversing down the task tree.\n task = taskChild\n continue\n }\n }\n }\n // We didn't find a child task that matches the server data. Exit. We won't\n // abort the task, though, because a different FlightDataPath may be able to\n // fulfill it (see loop in listenForDynamicRequest). We only abort tasks\n // once we've run out of data.\n return\n }\n\n finishTaskUsingDynamicDataPayload(\n task,\n serverRouterState,\n dynamicData,\n dynamicHead\n )\n}\n\nfunction finishTaskUsingDynamicDataPayload(\n task: SPANavigationTask,\n serverRouterState: FlightRouterState,\n dynamicData: CacheNodeSeedData,\n dynamicHead: HeadData\n) {\n if (task.dynamicRequestTree === null) {\n // Everything in this subtree is already complete. Bail out.\n return\n }\n\n // dynamicData may represent a larger subtree than the task. Before we can\n // finish the task, we need to line them up.\n const taskChildren = task.children\n const taskNode = task.node\n if (taskChildren === null) {\n // We've reached the leaf node of the pending task. The server data tree\n // lines up the pending Cache Node tree. We can now switch to the\n // normal algorithm.\n if (taskNode !== null) {\n finishPendingCacheNode(\n taskNode,\n task.route,\n serverRouterState,\n dynamicData,\n dynamicHead\n )\n // Set this to null to indicate that this task is now complete.\n task.dynamicRequestTree = null\n }\n return\n }\n // The server returned more data than we need to finish the task. Skip over\n // the extra segments until we reach the leaf task node.\n const serverChildren = serverRouterState[1]\n const dynamicDataChildren = dynamicData[2]\n\n for (const parallelRouteKey in serverRouterState) {\n const serverRouterStateChild: FlightRouterState =\n serverChildren[parallelRouteKey]\n const dynamicDataChild: CacheNodeSeedData | null | void =\n dynamicDataChildren[parallelRouteKey]\n\n const taskChild = taskChildren.get(parallelRouteKey)\n if (taskChild !== undefined) {\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 return finishTaskUsingDynamicDataPayload(\n taskChild,\n serverRouterStateChild,\n dynamicDataChild,\n dynamicHead\n )\n }\n }\n // We didn't find a child task that matches the server data. We won't abort\n // the task, though, because a different FlightDataPath may be able to\n // fulfill it (see loop in listenForDynamicRequest). We only abort tasks\n // once we've run out of data.\n }\n}\n\nfunction createPendingCacheNode(\n navigatedAt: number,\n routerState: FlightRouterState,\n prefetchData: CacheNodeSeedData | null,\n prefetchHead: HeadData | null,\n isPrefetchHeadPartial: boolean,\n segmentPath: FlightSegmentPath,\n scrollableSegmentsResult: Array<FlightSegmentPath>\n): ReadyCacheNode {\n const routerStateChildren = routerState[1]\n const prefetchDataChildren = prefetchData !== null ? prefetchData[2] : null\n\n const parallelRoutes = new Map()\n for (let parallelRouteKey in routerStateChildren) {\n const routerStateChild: FlightRouterState =\n routerStateChildren[parallelRouteKey]\n const prefetchDataChild: CacheNodeSeedData | null | void =\n prefetchDataChildren !== null\n ? prefetchDataChildren[parallelRouteKey]\n : null\n\n const segmentChild = routerStateChild[0]\n const segmentPathChild = segmentPath.concat([\n parallelRouteKey,\n segmentChild,\n ])\n const segmentKeyChild = createRouterCacheKey(segmentChild)\n\n const newCacheNodeChild = createPendingCacheNode(\n navigatedAt,\n routerStateChild,\n prefetchDataChild === undefined ? null : prefetchDataChild,\n prefetchHead,\n isPrefetchHeadPartial,\n segmentPathChild,\n scrollableSegmentsResult\n )\n\n const newSegmentMapChild: ChildSegmentMap = new Map()\n newSegmentMapChild.set(segmentKeyChild, newCacheNodeChild)\n parallelRoutes.set(parallelRouteKey, newSegmentMapChild)\n }\n\n // The head is assigned to every leaf segment delivered by the server. Based\n // on corresponding logic in fill-lazy-items-till-leaf-with-head.ts\n const isLeafSegment = parallelRoutes.size === 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 // 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 scrollableSegmentsResult.push(segmentPath)\n }\n\n const maybePrefetchRsc = prefetchData !== null ? prefetchData[1] : null\n return {\n lazyData: null,\n parallelRoutes: parallelRoutes,\n\n prefetchRsc: maybePrefetchRsc !== undefined ? maybePrefetchRsc : null,\n prefetchHead: isLeafSegment ? prefetchHead : [null, null],\n\n // Create a deferred promise. This will be fulfilled once the dynamic\n // response is received from the server.\n rsc: createDeferredRsc() as React.ReactNode,\n head: isLeafSegment ? (createDeferredRsc() as React.ReactNode) : null,\n\n // TODO: Technically, a loading boundary could contain dynamic data. We must\n // have separate `loading` and `prefetchLoading` fields to handle this, like\n // we do for the segment data and head.\n loading:\n prefetchData !== null\n ? (prefetchData[3] ?? null)\n : // If we don't have a prefetch, then we don't know if there's a loading component.\n // We'll fulfill it based on the dynamic response, just like `rsc` and `head`.\n createDeferredRsc<LoadingModuleData>(),\n\n navigatedAt,\n }\n}\n\nfunction finishPendingCacheNode(\n cacheNode: CacheNode,\n taskState: FlightRouterState,\n serverState: FlightRouterState,\n dynamicData: CacheNodeSeedData,\n dynamicHead: HeadData\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 const taskStateChildren = taskState[1]\n const serverStateChildren = serverState[1]\n const dataChildren = dynamicData[2]\n\n // The router state that we traverse the tree with (taskState) is the same one\n // that we used to construct the pending Cache Node tree. That way we're sure\n // to resolve all the pending promises.\n const parallelRoutes = cacheNode.parallelRoutes\n for (let parallelRouteKey in taskStateChildren) {\n const taskStateChild: FlightRouterState =\n taskStateChildren[parallelRouteKey]\n const serverStateChild: FlightRouterState | void =\n serverStateChildren[parallelRouteKey]\n const dataChild: CacheNodeSeedData | null | void =\n dataChildren[parallelRouteKey]\n\n const segmentMapChild = parallelRoutes.get(parallelRouteKey)\n const taskSegmentChild = taskStateChild[0]\n const taskSegmentKeyChild = createRouterCacheKey(taskSegmentChild)\n\n const cacheNodeChild =\n segmentMapChild !== undefined\n ? segmentMapChild.get(taskSegmentKeyChild)\n : undefined\n\n if (cacheNodeChild !== undefined) {\n if (\n serverStateChild !== undefined &&\n matchSegment(taskSegmentChild, serverStateChild[0])\n ) {\n if (dataChild !== undefined && dataChild !== null) {\n // This is the happy path. Recursively update all the children.\n finishPendingCacheNode(\n cacheNodeChild,\n taskStateChild,\n serverStateChild,\n dataChild,\n dynamicHead\n )\n } else {\n // The server never returned data for this segment. Trigger a lazy\n // fetch during render. This shouldn't happen because the Route Tree\n // and the Seed Data tree sent by the server should always be the same\n // shape when part of the same server response.\n abortPendingCacheNode(taskStateChild, cacheNodeChild, null)\n }\n } else {\n // The server never returned data for this segment. Trigger a lazy\n // fetch during render.\n abortPendingCacheNode(taskStateChild, cacheNodeChild, null)\n }\n } else {\n // The server response matches what was expected to receive, but there's\n // no matching Cache Node in the task tree. This is a bug in the\n // implementation because we should have created a node for every\n // segment in the tree that's associated with this task.\n }\n }\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[1]\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)\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[3]\n loading.resolve(dynamicLoading)\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)\n }\n}\n\nexport function abortTask(task: SPANavigationTask, error: any): void {\n const cacheNode = task.node\n if (cacheNode === null) {\n // This indicates the task is already complete.\n return\n }\n\n const taskChildren = task.children\n if (taskChildren === null) {\n // Reached the leaf task node. This is the root of a pending cache\n // node tree.\n abortPendingCacheNode(task.route, cacheNode, error)\n } else {\n // This is an intermediate task node. Keep traversing until we reach a\n // task node with no children. That will be the root of the cache node tree\n // that needs to be resolved.\n for (const taskChild of taskChildren.values()) {\n abortTask(taskChild, error)\n }\n }\n\n // Set this to null to indicate that this task is now complete.\n task.dynamicRequestTree = null\n}\n\nfunction abortPendingCacheNode(\n routerState: FlightRouterState,\n cacheNode: CacheNode,\n error: any\n): void {\n // For every pending segment in the tree, resolve its `rsc` promise to `null`\n // to trigger a lazy fetch during render.\n //\n // Or, if an error object is provided, it will error instead.\n const routerStateChildren = routerState[1]\n const parallelRoutes = cacheNode.parallelRoutes\n for (let parallelRouteKey in routerStateChildren) {\n const routerStateChild: FlightRouterState =\n routerStateChildren[parallelRouteKey]\n const segmentMapChild = parallelRoutes.get(parallelRouteKey)\n if (segmentMapChild === undefined) {\n // This shouldn't happen because we're traversing the same tree that was\n // used to construct the cache nodes in the first place.\n continue\n }\n const segmentChild = routerStateChild[0]\n const segmentKeyChild = createRouterCacheKey(segmentChild)\n const cacheNodeChild = segmentMapChild.get(segmentKeyChild)\n if (cacheNodeChild !== undefined) {\n abortPendingCacheNode(routerStateChild, cacheNodeChild, error)\n } else {\n // This shouldn't happen because we're traversing the same tree that was\n // used to construct the cache nodes in the first place.\n }\n }\n\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)\n } else {\n // This will trigger an error during rendering.\n rsc.reject(error)\n }\n }\n\n const loading = cacheNode.loading\n if (isDeferredRsc(loading)) {\n loading.resolve(null)\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)\n }\n}\n\nexport function updateCacheNodeOnPopstateRestoration(\n oldCacheNode: CacheNode,\n routerState: FlightRouterState\n): ReadyCacheNode {\n // A popstate navigation reads data from the local cache. It does not issue\n // new network requests (unless the cache entries have been evicted). So, we\n // update the cache to drop the prefetch data for any segment whose dynamic\n // data was already received. This prevents an unnecessary flash back to PPR\n // state during a back/forward navigation.\n //\n // This function clones the entire cache node tree and sets the `prefetchRsc`\n // field to `null` to prevent it from being rendered. We can't mutate the node\n // in place because this is a concurrent data structure.\n\n const routerStateChildren = routerState[1]\n const oldParallelRoutes = oldCacheNode.parallelRoutes\n const newParallelRoutes = new Map(oldParallelRoutes)\n for (let parallelRouteKey in routerStateChildren) {\n const routerStateChild: FlightRouterState =\n routerStateChildren[parallelRouteKey]\n const segmentChild = routerStateChild[0]\n const segmentKeyChild = createRouterCacheKey(segmentChild)\n const oldSegmentMapChild = oldParallelRoutes.get(parallelRouteKey)\n if (oldSegmentMapChild !== undefined) {\n const oldCacheNodeChild = oldSegmentMapChild.get(segmentKeyChild)\n if (oldCacheNodeChild !== undefined) {\n const newCacheNodeChild = updateCacheNodeOnPopstateRestoration(\n oldCacheNodeChild,\n routerStateChild\n )\n const newSegmentMapChild = new Map(oldSegmentMapChild)\n newSegmentMapChild.set(segmentKeyChild, newCacheNodeChild)\n newParallelRoutes.set(parallelRouteKey, newSegmentMapChild)\n }\n }\n }\n\n // Only show prefetched data if the dynamic data is still pending.\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 not\n // mean that all the dynamic data has fully streamed in. It just means that\n // _some_ of the dynamic data was received. But as a heuristic, we assume that\n // the rest dynamic data will stream in quickly, so it's still better to skip\n // the prefetch state.\n const rsc = oldCacheNode.rsc\n const shouldUsePrefetch = isDeferredRsc(rsc) && rsc.status === 'pending'\n\n return {\n lazyData: null,\n rsc,\n head: oldCacheNode.head,\n\n prefetchHead: shouldUsePrefetch ? oldCacheNode.prefetchHead : [null, null],\n prefetchRsc: shouldUsePrefetch ? oldCacheNode.prefetchRsc : null,\n loading: oldCacheNode.loading,\n\n // These are the cloned children we computed above\n parallelRoutes: newParallelRoutes,\n\n navigatedAt: oldCacheNode.navigatedAt,\n }\n}\n\nconst DEFERRED = Symbol()\n\ntype PendingDeferredRsc<T> = Promise<T> & {\n status: 'pending'\n resolve: (value: T) => void\n reject: (error: any) => void\n tag: Symbol\n}\n\ntype FulfilledDeferredRsc<T> = Promise<T> & {\n status: 'fulfilled'\n value: T\n resolve: (value: T) => void\n reject: (error: any) => void\n tag: Symbol\n}\n\ntype RejectedDeferredRsc<T> = Promise<T> & {\n status: 'rejected'\n reason: any\n resolve: (value: T) => void\n reject: (error: any) => void\n tag: Symbol\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.\nfunction 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 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) => {\n if (pendingRsc.status === 'pending') {\n const fulfilledRsc: FulfilledDeferredRsc<T> = pendingRsc as any\n fulfilledRsc.status = 'fulfilled'\n fulfilledRsc.value = value\n resolve(value)\n }\n }\n pendingRsc.reject = (error: any) => {\n if (pendingRsc.status === 'pending') {\n const rejectedRsc: RejectedDeferredRsc<T> = pendingRsc as any\n rejectedRsc.status = 'rejected'\n rejectedRsc.reason = error\n reject(error)\n }\n }\n pendingRsc.tag = DEFERRED\n return pendingRsc\n}\n","import type {\n FlightSegmentPath,\n CacheNode,\n} from '../../../shared/lib/app-router-types'\nimport { getNextFlightSegmentPath } from '../../flight-data-helpers'\nimport { createRouterCacheKey } from './create-router-cache-key'\n\n/**\n * This will clear the CacheNode data for a particular segment path. This will cause a lazy-fetch in layout router to fill in new data.\n */\nexport function clearCacheNodeDataForSegmentPath(\n newCache: CacheNode,\n existingCache: CacheNode,\n flightSegmentPath: FlightSegmentPath\n): void {\n const isLastEntry = flightSegmentPath.length <= 2\n\n const [parallelRouteKey, segment] = flightSegmentPath\n const cacheKey = createRouterCacheKey(segment)\n\n const existingChildSegmentMap =\n existingCache.parallelRoutes.get(parallelRouteKey)\n\n let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey)\n\n if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {\n childSegmentMap = new Map(existingChildSegmentMap)\n newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap)\n }\n\n const existingChildCacheNode = existingChildSegmentMap?.get(cacheKey)\n let childCacheNode = childSegmentMap.get(cacheKey)\n\n // In case of last segment start off the fetch at this level and don't copy further down.\n if (isLastEntry) {\n if (\n !childCacheNode ||\n !childCacheNode.lazyData ||\n childCacheNode === existingChildCacheNode\n ) {\n childSegmentMap.set(cacheKey, {\n lazyData: null,\n rsc: null,\n prefetchRsc: null,\n head: null,\n prefetchHead: null,\n parallelRoutes: new Map(),\n loading: null,\n navigatedAt: -1,\n })\n }\n return\n }\n\n if (!childCacheNode || !existingChildCacheNode) {\n // Start fetch in the place where the existing cache doesn't have the data yet.\n if (!childCacheNode) {\n childSegmentMap.set(cacheKey, {\n lazyData: null,\n rsc: null,\n prefetchRsc: null,\n head: null,\n prefetchHead: null,\n parallelRoutes: new Map(),\n loading: null,\n navigatedAt: -1,\n })\n }\n return\n }\n\n if (childCacheNode === existingChildCacheNode) {\n childCacheNode = {\n lazyData: childCacheNode.lazyData,\n rsc: childCacheNode.rsc,\n prefetchRsc: childCacheNode.prefetchRsc,\n head: childCacheNode.head,\n prefetchHead: childCacheNode.prefetchHead,\n parallelRoutes: new Map(childCacheNode.parallelRoutes),\n loading: childCacheNode.loading,\n } as CacheNode\n childSegmentMap.set(cacheKey, childCacheNode)\n }\n\n return clearCacheNodeDataForSegmentPath(\n childCacheNode,\n existingChildCacheNode,\n getNextFlightSegmentPath(flightSegmentPath)\n )\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 {\n addSearchParamsIfPageSegment,\n DEFAULT_SEGMENT_KEY,\n PAGE_SEGMENT_KEY,\n} from '../../../shared/lib/segment'\nimport type { NormalizedFlightData } from '../../flight-data-helpers'\nimport { createEmptyCacheNode } from '../app-router'\nimport { applyRouterStatePatchToTree } from './apply-router-state-patch-to-tree'\nimport { createHrefFromUrl } from './create-href-from-url'\nimport { createRouterCacheKey } from './create-router-cache-key'\nimport { fillCacheWithNewSubTreeDataButOnlyLoading } from './fill-cache-with-new-subtree-data'\nimport { handleMutable } from './handle-mutable'\nimport { generateSegmentsFromPatch } from './reducers/navigate-reducer'\nimport type { Mutable, ReadonlyReducerState } from './router-reducer-types'\n\n/**\n * This is a stop-gap until per-segment caching is implemented. It leverages the `aliased` flag that is added\n * to prefetch entries when it's determined that the loading state from that entry should be used for this navigation.\n * This function takes the aliased entry and only applies the loading state to the updated cache node.\n * We should remove this once per-segment fetching is implemented as ideally the prefetch cache will contain a\n * more granular segment map and so the router will be able to simply re-use the loading segment for the new navigation.\n */\nexport function handleAliasedPrefetchEntry(\n navigatedAt: number,\n state: ReadonlyReducerState,\n flightData: string | NormalizedFlightData[],\n url: URL,\n mutable: Mutable\n) {\n let currentTree = state.tree\n let currentCache = state.cache\n const href = createHrefFromUrl(url)\n let applied\n let scrollableSegments: FlightSegmentPath[] = []\n\n if (typeof flightData === 'string') {\n return false\n }\n\n for (const normalizedFlightData of flightData) {\n // If the segment doesn't have a loading component, we don't need to do anything.\n if (!hasLoadingComponentInSeedData(normalizedFlightData.seedData)) {\n continue\n }\n\n let treePatch = normalizedFlightData.tree\n // Segments are keyed by searchParams (e.g. __PAGE__?{\"foo\":\"bar\"}). We might return a less specific, param-less entry,\n // so we ensure that the final tree contains the correct searchParams (reflected in the URL) are provided in the updated FlightRouterState tree.\n // We only do this on the first read, as otherwise we'd be overwriting the searchParams that may have already been set\n treePatch = addSearchParamsToPageSegments(\n treePatch,\n Object.fromEntries(url.searchParams)\n )\n\n const { seedData, isRootRender, pathToSegment } = normalizedFlightData\n // TODO-APP: remove ''\n const flightSegmentPathWithLeadingEmpty = ['', ...pathToSegment]\n\n // Segments are keyed by searchParams (e.g. __PAGE__?{\"foo\":\"bar\"}). We might return a less specific, param-less entry,\n // so we ensure that the final tree contains the correct searchParams (reflected in the URL) are provided in the updated FlightRouterState tree.\n // We only do this on the first read, as otherwise we'd be overwriting the searchParams that may have already been set\n treePatch = addSearchParamsToPageSegments(\n treePatch,\n Object.fromEntries(url.searchParams)\n )\n\n let newTree = applyRouterStatePatchToTree(\n flightSegmentPathWithLeadingEmpty,\n currentTree,\n treePatch,\n href\n )\n\n const newCache = createEmptyCacheNode()\n\n // The prefetch cache entry was aliased -- this signals that we only fill in the cache with the\n // loading state and not the actual parallel route seed data.\n if (isRootRender && seedData) {\n // Fill in the cache with the new loading / rsc data\n const rsc = seedData[1]\n const loading = seedData[3]\n newCache.loading = loading\n newCache.rsc = rsc\n\n // Construct a new tree and apply the aliased loading state for each parallel route\n fillNewTreeWithOnlyLoadingSegments(\n navigatedAt,\n newCache,\n currentCache,\n treePatch,\n seedData\n )\n } else {\n // Copy rsc for the root node of the cache.\n newCache.rsc = currentCache.rsc\n newCache.prefetchRsc = currentCache.prefetchRsc\n newCache.loading = currentCache.loading\n newCache.parallelRoutes = new Map(currentCache.parallelRoutes)\n\n // copy the loading state only into the leaf node (the part that changed)\n fillCacheWithNewSubTreeDataButOnlyLoading(\n navigatedAt,\n newCache,\n currentCache,\n normalizedFlightData\n )\n }\n\n // If we don't have an updated tree, there's no reason to update the cache, as the tree\n // dictates what cache nodes to render.\n if (newTree) {\n currentTree = newTree\n currentCache = newCache\n applied = true\n }\n\n for (const subSegment of generateSegmentsFromPatch(treePatch)) {\n const scrollableSegmentPath = [\n ...normalizedFlightData.pathToSegment,\n ...subSegment,\n ]\n // Filter out the __DEFAULT__ paths as they shouldn't be scrolled to in this case.\n if (\n scrollableSegmentPath[scrollableSegmentPath.length - 1] !==\n DEFAULT_SEGMENT_KEY\n ) {\n scrollableSegments.push(scrollableSegmentPath)\n }\n }\n }\n\n if (!applied) {\n return false\n }\n\n mutable.patchedTree = currentTree\n mutable.cache = currentCache\n mutable.canonicalUrl = href\n mutable.hashFragment = url.hash\n mutable.scrollableSegments = scrollableSegments\n\n return handleMutable(state, mutable)\n}\n\nfunction hasLoadingComponentInSeedData(seedData: CacheNodeSeedData | null) {\n if (!seedData) return false\n\n const parallelRoutes = seedData[2]\n const loading = seedData[3]\n\n if (loading) {\n return true\n }\n\n for (const key in parallelRoutes) {\n if (hasLoadingComponentInSeedData(parallelRoutes[key])) {\n return true\n }\n }\n\n return false\n}\n\nfunction fillNewTreeWithOnlyLoadingSegments(\n navigatedAt: number,\n newCache: CacheNode,\n existingCache: CacheNode,\n routerState: FlightRouterState,\n cacheNodeSeedData: CacheNodeSeedData | null\n) {\n const isLastSegment = Object.keys(routerState[1]).length === 0\n if (isLastSegment) {\n return\n }\n\n for (const key in routerState[1]) {\n const parallelRouteState = routerState[1][key]\n const segmentForParallelRoute = parallelRouteState[0]\n const cacheKey = createRouterCacheKey(segmentForParallelRoute)\n\n const parallelSeedData =\n cacheNodeSeedData !== null && cacheNodeSeedData[2][key] !== undefined\n ? cacheNodeSeedData[2][key]\n : null\n\n let newCacheNode: CacheNode\n if (parallelSeedData !== null) {\n // New data was sent from the server.\n const rsc = parallelSeedData[1]\n const loading = parallelSeedData[3]\n newCacheNode = {\n lazyData: null,\n // copy the layout but null the page segment as that's not meant to be used\n rsc: segmentForParallelRoute.includes(PAGE_SEGMENT_KEY) ? null : rsc,\n prefetchRsc: null,\n head: null,\n prefetchHead: null,\n parallelRoutes: new Map(),\n loading,\n navigatedAt,\n }\n } else {\n // No data available for this node. This will trigger a lazy fetch\n // during render.\n newCacheNode = {\n lazyData: null,\n rsc: null,\n prefetchRsc: null,\n head: null,\n prefetchHead: null,\n parallelRoutes: new Map(),\n loading: null,\n navigatedAt: -1,\n }\n }\n\n const existingParallelRoutes = newCache.parallelRoutes.get(key)\n if (existingParallelRoutes) {\n existingParallelRoutes.set(cacheKey, newCacheNode)\n } else {\n newCache.parallelRoutes.set(key, new Map([[cacheKey, newCacheNode]]))\n }\n\n fillNewTreeWithOnlyLoadingSegments(\n navigatedAt,\n newCacheNode,\n existingCache,\n parallelRouteState,\n parallelSeedData\n )\n }\n}\n\n/**\n * Add search params to the page segments in the flight router state\n * Page segments that are associated with search params have a page segment key\n * followed by a query string. This function will add those params to the page segment.\n * This is useful if we return an aliased prefetch entry (ie, won't have search params)\n * but the canonical router URL has search params.\n */\nexport function addSearchParamsToPageSegments(\n flightRouterState: FlightRouterState,\n searchParams: Record<string, string | string[] | undefined>\n): FlightRouterState {\n const [segment, parallelRoutes, ...rest] = flightRouterState\n\n // If it's a page segment, modify the segment by adding search params\n if (segment.includes(PAGE_SEGMENT_KEY)) {\n const newSegment = addSearchParamsIfPageSegment(segment, searchParams)\n return [newSegment, parallelRoutes, ...rest]\n }\n\n // Otherwise, recurse through the parallel routes and return a new tree\n const updatedParallelRoutes: { [key: string]: FlightRouterState } = {}\n\n for (const [key, parallelRoute] of Object.entries(parallelRoutes)) {\n updatedParallelRoutes[key] = addSearchParamsToPageSegments(\n parallelRoute,\n searchParams\n )\n }\n\n return [segment, updatedParallelRoutes, ...rest]\n}\n","/**\n * Entry point to the Segment Cache implementation.\n *\n * All code related to the Segment Cache lives `segment-cache-impl` directory.\n * Callers access it through this indirection.\n *\n * This is to ensure the code is dead code eliminated from the bundle if the\n * flag is disabled.\n *\n * TODO: This is super tedious. Since experimental flags are an essential part\n * of our workflow, we should establish a better pattern for dead code\n * elimination. Ideally it would be done at the bundler level, like how React's\n * build process works. In the React repo, you don't even need to add any extra\n * configuration per experiment — if the code is not reachable, it gets stripped\n * from the build automatically by Rollup. Or, shorter term, we could stub out\n * experimental modules at build time by updating the build config, i.e. a more\n * automated version of what I'm doing manually in this file.\n */\n\nexport type { NavigationResult } from './segment-cache-impl/navigation'\nexport type { PrefetchTask } from './segment-cache-impl/scheduler'\nexport type { NormalizedSearch } from './segment-cache-impl/cache-key'\n\nconst notEnabled: any = () => {\n throw new Error(\n 'Segment Cache experiment is not enabled. This is a bug in Next.js.'\n )\n}\n\nexport const prefetch: typeof import('./segment-cache-impl/prefetch').prefetch =\n process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? function (...args) {\n return (\n require('./segment-cache-impl/prefetch') as typeof import('./segment-cache-impl/prefetch')\n ).prefetch(...args)\n }\n : notEnabled\n\nexport const navigate: typeof import('./segment-cache-impl/navigation').navigate =\n process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? function (...args) {\n return (\n require('./segment-cache-impl/navigation') as typeof import('./segment-cache-impl/navigation')\n ).navigate(...args)\n }\n : notEnabled\n\nexport const revalidateEntireCache: typeof import('./segment-cache-impl/cache').revalidateEntireCache =\n process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? function (...args) {\n return (\n require('./segment-cache-impl/cache') as typeof import('./segment-cache-impl/cache')\n ).revalidateEntireCache(...args)\n }\n : notEnabled\n\nexport const getCurrentCacheVersion: typeof import('./segment-cache-impl/cache').getCurrentCacheVersion =\n process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? function (...args) {\n return (\n require('./segment-cache-impl/cache') as typeof import('./segment-cache-impl/cache')\n ).getCurrentCacheVersion(...args)\n }\n : notEnabled\n\nexport const schedulePrefetchTask: typeof import('./segment-cache-impl/scheduler').schedulePrefetchTask =\n process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? function (...args) {\n return (\n require('./segment-cache-impl/scheduler') as typeof import('./segment-cache-impl/scheduler')\n ).schedulePrefetchTask(...args)\n }\n : notEnabled\n\nexport const cancelPrefetchTask: typeof import('./segment-cache-impl/scheduler').cancelPrefetchTask =\n process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? function (...args) {\n return (\n require('./segment-cache-impl/scheduler') as typeof import('./segment-cache-impl/scheduler')\n ).cancelPrefetchTask(...args)\n }\n : notEnabled\n\nexport const reschedulePrefetchTask: typeof import('./segment-cache-impl/scheduler').reschedulePrefetchTask =\n process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? function (...args) {\n return (\n require('./segment-cache-impl/scheduler') as typeof import('./segment-cache-impl/scheduler')\n ).reschedulePrefetchTask(...args)\n }\n : notEnabled\n\nexport const isPrefetchTaskDirty: typeof import('./segment-cache-impl/scheduler').isPrefetchTaskDirty =\n process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? function (...args) {\n return (\n require('./segment-cache-impl/scheduler') as typeof import('./segment-cache-impl/scheduler')\n ).isPrefetchTaskDirty(...args)\n }\n : notEnabled\n\nexport const createCacheKey: typeof import('./segment-cache-impl/cache-key').createCacheKey =\n process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? function (...args) {\n return (\n require('./segment-cache-impl/cache-key') as typeof import('./segment-cache-impl/cache-key')\n ).createCacheKey(...args)\n }\n : notEnabled\n\n/**\n * Below are public constants. They're small enough that we don't need to\n * DCE them.\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","import type { CacheNode } from '../../../../shared/lib/app-router-types'\nimport type {\n FlightRouterState,\n FlightSegmentPath,\n} from '../../../../shared/lib/app-router-types'\nimport { fetchServerResponse } from '../fetch-server-response'\nimport { createHrefFromUrl } from '../create-href-from-url'\nimport { invalidateCacheBelowFlightSegmentPath } from '../invalidate-cache-below-flight-segmentpath'\nimport { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'\nimport { shouldHardNavigate } from '../should-hard-navigate'\nimport { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'\nimport {\n PrefetchCacheEntryStatus,\n type Mutable,\n type NavigateAction,\n type ReadonlyReducerState,\n type ReducerState,\n} from '../router-reducer-types'\nimport { handleMutable } from '../handle-mutable'\nimport { applyFlightData } from '../apply-flight-data'\nimport { prefetchQueue } from './prefetch-reducer'\nimport { createEmptyCacheNode } from '../../app-router'\nimport { DEFAULT_SEGMENT_KEY } from '../../../../shared/lib/segment'\nimport { listenForDynamicRequest, startPPRNavigation } from '../ppr-navigations'\nimport {\n getOrCreatePrefetchCacheEntry,\n prunePrefetchCache,\n} from '../prefetch-cache-utils'\nimport { clearCacheNodeDataForSegmentPath } from '../clear-cache-node-data-for-segment-path'\nimport { handleAliasedPrefetchEntry } from '../aliased-prefetch-navigations'\nimport {\n navigate as navigateUsingSegmentCache,\n NavigationResultTag,\n type NavigationResult,\n} from '../../segment-cache'\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\nfunction triggerLazyFetchForLeafSegments(\n newCache: CacheNode,\n currentCache: CacheNode,\n flightSegmentPath: FlightSegmentPath,\n treePatch: FlightRouterState\n) {\n let appliedPatch = false\n\n newCache.rsc = currentCache.rsc\n newCache.prefetchRsc = currentCache.prefetchRsc\n newCache.loading = currentCache.loading\n newCache.parallelRoutes = new Map(currentCache.parallelRoutes)\n\n const segmentPathsToFill = generateSegmentsFromPatch(treePatch).map(\n (segment) => [...flightSegmentPath, ...segment]\n )\n\n for (const segmentPaths of segmentPathsToFill) {\n clearCacheNodeDataForSegmentPath(newCache, currentCache, segmentPaths)\n\n appliedPatch = true\n }\n\n return appliedPatch\n}\n\nfunction 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.NoOp: {\n // The server responded with no change to the current page. However, if\n // the URL changed, we still need to update that.\n const newCanonicalUrl = result.data.canonicalUrl\n mutable.canonicalUrl = newCanonicalUrl\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.Success: {\n // Received a new result.\n mutable.cache = result.data.cacheNode\n mutable.patchedTree = result.data.flightRouterState\n mutable.canonicalUrl = result.data.canonicalUrl\n mutable.scrollableSegments = result.data.scrollableSegments\n mutable.shouldScroll = result.data.shouldScroll\n mutable.hashFragment = result.data.hash\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, allowAliasing } =\n action\n const mutable: Mutable = {}\n const { hash } = url\n const href = createHrefFromUrl(url)\n const pendingPush = navigateType === 'push'\n // we want to prune the prefetch cache on every navigation to avoid it growing too large\n prunePrefetchCache(state.prefetchCache)\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 if (process.env.__NEXT_CLIENT_SEGMENT_CACHE) {\n // (Very Early Experimental Feature) Segment Cache\n //\n // Bypass the normal prefetch cache and use the new per-segment cache\n // implementation instead. This is only supported if PPR is enabled, too.\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 result = navigateUsingSegmentCache(\n url,\n state.cache,\n state.tree,\n state.nextUrl,\n shouldScroll\n )\n return handleNavigationResult(url, state, mutable, pendingPush, result)\n }\n\n const prefetchValues = getOrCreatePrefetchCacheEntry({\n url,\n nextUrl: state.nextUrl,\n tree: state.tree,\n prefetchCache: state.prefetchCache,\n allowAliasing,\n })\n const { treeAtTimeOfPrefetch, data } = prefetchValues\n\n prefetchQueue.bump(data)\n\n return data.then(\n ({ flightData, canonicalUrl: canonicalUrlOverride, postponed }) => {\n const navigatedAt = Date.now()\n\n let isFirstRead = false\n // we only want to mark this once\n if (!prefetchValues.lastUsedTime) {\n // important: we should only mark the cache node as dirty after we unsuspend from the call above\n prefetchValues.lastUsedTime = navigatedAt\n isFirstRead = true\n }\n\n if (prefetchValues.aliased) {\n // When alias is enabled, search param may not be included in the canonicalUrl.\n // But we want to set url to canonicalUrl so that we use redirected path for fetching dynamic data.\n const urlWithCanonicalPathname = new URL(url.href)\n if (canonicalUrlOverride) {\n urlWithCanonicalPathname.pathname = canonicalUrlOverride.pathname\n }\n\n const result = handleAliasedPrefetchEntry(\n navigatedAt,\n state,\n flightData,\n urlWithCanonicalPathname,\n mutable\n )\n\n // We didn't return new router state because we didn't apply the aliased entry for some reason.\n // We'll re-invoke the navigation handler but ensure that we don't attempt to use the aliased entry. This\n // will create an on-demand prefetch entry.\n if (result === false) {\n return navigateReducer(state, { ...action, allowAliasing: false })\n }\n\n return result\n }\n\n // Handle case when navigating to page in `pages` from `app`\n if (typeof flightData === 'string') {\n return handleExternalUrl(state, mutable, flightData, pendingPush)\n }\n\n const updatedCanonicalUrl = canonicalUrlOverride\n ? createHrefFromUrl(canonicalUrlOverride)\n : href\n\n const onlyHashChange =\n !!hash &&\n state.canonicalUrl.split('#', 1)[0] ===\n updatedCanonicalUrl.split('#', 1)[0]\n\n // If only the hash has changed, the server hasn't sent us any new data. We can just update\n // the mutable properties responsible for URL and scroll handling and return early.\n if (onlyHashChange) {\n mutable.onlyHashChange = true\n mutable.canonicalUrl = updatedCanonicalUrl\n mutable.shouldScroll = shouldScroll\n mutable.hashFragment = hash\n mutable.scrollableSegments = []\n return handleMutable(state, mutable)\n }\n\n let currentTree = state.tree\n let currentCache = state.cache\n let scrollableSegments: FlightSegmentPath[] = []\n for (const normalizedFlightData of flightData) {\n const {\n pathToSegment: flightSegmentPath,\n seedData,\n head,\n isHeadPartial,\n isRootRender,\n } = normalizedFlightData\n let treePatch = normalizedFlightData.tree\n\n // TODO-APP: remove ''\n const flightSegmentPathWithLeadingEmpty = ['', ...flightSegmentPath]\n\n // Create new tree based on the flightSegmentPath and router state patch\n let newTree = applyRouterStatePatchToTree(\n // TODO-APP: remove ''\n flightSegmentPathWithLeadingEmpty,\n currentTree,\n treePatch,\n href\n )\n\n // If the tree patch can't be applied to the current tree then we use the tree at time of prefetch\n // TODO-APP: This should instead fill in the missing pieces in `currentTree` with the data from `treeAtTimeOfPrefetch`, then apply the patch.\n if (newTree === null) {\n newTree = applyRouterStatePatchToTree(\n // TODO-APP: remove ''\n flightSegmentPathWithLeadingEmpty,\n treeAtTimeOfPrefetch,\n treePatch,\n href\n )\n }\n\n if (newTree !== null) {\n if (\n // This is just a paranoid check. When a route is PPRed, the server\n // will send back a static response that's rendered from\n // the root. If for some reason it doesn't, we fall back to the\n // non-PPR implementation.\n // TODO: We should get rid of the else branch and do all navigations\n // via startPPRNavigation. The current structure is just\n // an incremental step.\n seedData &&\n isRootRender &&\n postponed\n ) {\n const task = startPPRNavigation(\n navigatedAt,\n currentCache,\n currentTree,\n treePatch,\n seedData,\n head,\n isHeadPartial,\n false,\n scrollableSegments\n )\n\n if (task !== null) {\n if (task.route === null) {\n // Detected a change to the root layout. Perform an full-\n // page navigation.\n return handleExternalUrl(state, mutable, href, pendingPush)\n }\n // Use the tree computed by startPPRNavigation instead\n // of the one computed by applyRouterStatePatchToTree.\n // TODO: We should remove applyRouterStatePatchToTree\n // from the PPR path entirely.\n const patchedRouterState: FlightRouterState = task.route\n newTree = patchedRouterState\n\n const newCache = task.node\n if (newCache !== null) {\n // We've created a new Cache Node tree that contains a prefetched\n // version of the next page. This can be rendered instantly.\n mutable.cache = newCache\n }\n const dynamicRequestTree = task.dynamicRequestTree\n if (dynamicRequestTree !== null) {\n // The prefetched tree has dynamic holes in it. We initiate a\n // dynamic request to fill them in.\n //\n // Do not block on the result. We'll immediately render the Cache\n // Node tree and suspend on the dynamic parts. When the request\n // comes in, we'll fill in missing data and ping React to\n // re-render. Unlike the lazy fetching model in the non-PPR\n // implementation, this is modeled as a single React update +\n // streaming, rather than multiple top-level updates. (However,\n // even in the new model, we'll still need to sometimes update the\n // root multiple times per navigation, like if the server sends us\n // a different response than we expected. For now, we revert back\n // to the lazy fetching mechanism in that case.)\n const dynamicRequest = fetchServerResponse(\n new URL(updatedCanonicalUrl, url.origin),\n {\n flightRouterState: dynamicRequestTree,\n nextUrl: state.nextUrl,\n }\n )\n\n listenForDynamicRequest(task, dynamicRequest)\n // We store the dynamic request on the `lazyData` property of the CacheNode\n // because we're not going to await the dynamic request here. Since we're not blocking\n // on the dynamic request, `layout-router` will\n // task.node.lazyData = dynamicRequest\n } else {\n // The prefetched tree does not contain dynamic holes — it's\n // fully static. We can skip the dynamic request.\n }\n } else {\n // Nothing changed, so reuse the old cache.\n // TODO: What if the head changed but not any of the segment data?\n // Is that possible? If so, we should clone the whole tree and\n // update the head.\n newTree = treePatch\n }\n } else {\n // The static response does not include any dynamic holes, so\n // there's no need to do a second request.\n // TODO: As an incremental step this just reverts back to the\n // non-PPR implementation. We can simplify this branch further,\n // given that PPR prefetches are always static and return the whole\n // tree. Or in the meantime we could factor it out into a\n // separate function.\n\n if (isNavigatingToNewRootLayout(currentTree, newTree)) {\n return handleExternalUrl(state, mutable, href, pendingPush)\n }\n\n const cache: CacheNode = createEmptyCacheNode()\n let applied = false\n\n if (\n prefetchValues.status === PrefetchCacheEntryStatus.stale &&\n !isFirstRead\n ) {\n // When we have a stale prefetch entry, we only want to re-use the loading state of the route we're navigating to, to support instant loading navigations\n // this will trigger a lazy fetch for the actual page data by nulling the `rsc` and `prefetchRsc` values for page data,\n // while copying over the `loading` for the segment that contains the page data.\n // We only do this on subsequent reads, as otherwise there'd be no loading data to re-use.\n\n // We skip this branch if only the hash fragment has changed, as we don't want to trigger a lazy fetch in that case\n applied = triggerLazyFetchForLeafSegments(\n cache,\n currentCache,\n flightSegmentPath,\n treePatch\n )\n // since we re-used the stale cache's loading state & refreshed the data,\n // update the `lastUsedTime` so that it can continue to be re-used for the next 30s\n prefetchValues.lastUsedTime = navigatedAt\n } else {\n applied = applyFlightData(\n navigatedAt,\n currentCache,\n cache,\n normalizedFlightData,\n prefetchValues\n )\n }\n\n const hardNavigate = shouldHardNavigate(\n // TODO-APP: remove ''\n flightSegmentPathWithLeadingEmpty,\n currentTree\n )\n\n if (hardNavigate) {\n // Copy rsc for the root node of the cache.\n cache.rsc = currentCache.rsc\n cache.prefetchRsc = currentCache.prefetchRsc\n\n invalidateCacheBelowFlightSegmentPath(\n cache,\n currentCache,\n flightSegmentPath\n )\n // Ensure the existing cache value is used when the cache was not invalidated.\n mutable.cache = cache\n } else if (applied) {\n mutable.cache = cache\n // If we applied the cache, we update the \"current cache\" value so any other\n // segments in the FlightDataPath will be able to reference the updated cache.\n currentCache = cache\n }\n\n for (const subSegment of generateSegmentsFromPatch(treePatch)) {\n const scrollableSegmentPath = [\n ...flightSegmentPath,\n ...subSegment,\n ]\n // Filter out the __DEFAULT__ paths as they shouldn't be scrolled to in this case.\n if (\n scrollableSegmentPath[scrollableSegmentPath.length - 1] !==\n DEFAULT_SEGMENT_KEY\n ) {\n scrollableSegments.push(scrollableSegmentPath)\n }\n }\n }\n\n currentTree = newTree\n }\n }\n\n mutable.patchedTree = currentTree\n mutable.canonicalUrl = updatedCanonicalUrl\n mutable.scrollableSegments = scrollableSegments\n mutable.hashFragment = hash\n mutable.shouldScroll = shouldScroll\n\n return handleMutable(state, mutable)\n },\n () => state\n )\n}\n","import { createHrefFromUrl } from '../create-href-from-url'\nimport { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'\nimport { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'\nimport type {\n ServerPatchAction,\n ReducerState,\n ReadonlyReducerState,\n Mutable,\n} from '../router-reducer-types'\nimport { handleExternalUrl } from './navigate-reducer'\nimport { applyFlightData } from '../apply-flight-data'\nimport { handleMutable } from '../handle-mutable'\nimport type { CacheNode } from '../../../../shared/lib/app-router-types'\nimport { createEmptyCacheNode } from '../../app-router'\n\nexport function serverPatchReducer(\n state: ReadonlyReducerState,\n action: ServerPatchAction\n): ReducerState {\n const {\n serverResponse: { flightData, canonicalUrl: canonicalUrlOverride },\n navigatedAt,\n } = action\n\n const mutable: Mutable = {}\n\n mutable.preserveCustomHistoryState = false\n\n // Handle case when navigating to page in `pages` from `app`\n if (typeof flightData === 'string') {\n return handleExternalUrl(\n state,\n mutable,\n flightData,\n state.pushRef.pendingPush\n )\n }\n\n let currentTree = state.tree\n let currentCache = state.cache\n\n for (const normalizedFlightData of flightData) {\n const { segmentPath: flightSegmentPath, tree: treePatch } =\n normalizedFlightData\n\n const newTree = applyRouterStatePatchToTree(\n // TODO-APP: remove ''\n ['', ...flightSegmentPath],\n currentTree,\n treePatch,\n state.canonicalUrl\n )\n\n // `applyRouterStatePatchToTree` returns `null` when it determined that the server response is not applicable to the current tree.\n // In other words, the server responded with a tree that doesn't match what the client is currently rendering.\n // This can happen if the server patch action took longer to resolve than a subsequent navigation which would have changed the tree.\n // Previously this case triggered an MPA navigation but it should be safe to simply discard the server response rather than forcing\n // the entire page to reload.\n if (newTree === null) {\n return state\n }\n\n if (isNavigatingToNewRootLayout(currentTree, newTree)) {\n return handleExternalUrl(\n state,\n mutable,\n state.canonicalUrl,\n state.pushRef.pendingPush\n )\n }\n\n const canonicalUrlOverrideHref = canonicalUrlOverride\n ? createHrefFromUrl(canonicalUrlOverride)\n : undefined\n\n if (canonicalUrlOverrideHref) {\n mutable.canonicalUrl = canonicalUrlOverrideHref\n }\n\n const cache: CacheNode = createEmptyCacheNode()\n applyFlightData(navigatedAt, currentCache, cache, normalizedFlightData)\n\n mutable.patchedTree = newTree\n mutable.cache = cache\n\n currentCache = cache\n currentTree = newTree\n }\n\n return handleMutable(state, mutable)\n}\n","import { createHrefFromUrl } from '../create-href-from-url'\nimport type {\n ReadonlyReducerState,\n ReducerState,\n RestoreAction,\n} from '../router-reducer-types'\nimport { extractPathFromFlightRouterState } from '../compute-changed-path'\nimport { updateCacheNodeOnPopstateRestoration } from '../ppr-navigations'\n\nexport function restoreReducer(\n state: ReadonlyReducerState,\n action: RestoreAction\n): ReducerState {\n const { url, tree } = action\n const href = createHrefFromUrl(url)\n // This action is used to restore the router state from the history state.\n // However, it's possible that the history state no longer contains the `FlightRouterState`.\n // We will copy over the internal state on pushState/replaceState events, but if a history entry\n // occurred before hydration, or if the user navigated to a hash using a regular anchor link,\n // the history state will not contain the `FlightRouterState`.\n // In this case, we'll continue to use the existing tree so the router doesn't get into an invalid state.\n const treeToRestore = tree || state.tree\n\n const oldCache = state.cache\n const newCache = process.env.__NEXT_PPR\n ? // When PPR is enabled, we update the cache to drop the prefetch\n // data for any segment whose dynamic data was already received. This\n // prevents an unnecessary flash back to PPR state during a\n // back/forward navigation.\n updateCacheNodeOnPopstateRestoration(oldCache, treeToRestore)\n : oldCache\n\n return {\n // Set canonical url\n canonicalUrl: href,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // Ensures that the custom history state that was set is preserved when applying this update.\n preserveCustomHistoryState: true,\n },\n focusAndScrollRef: state.focusAndScrollRef,\n cache: newCache,\n prefetchCache: state.prefetchCache,\n // Restore provided tree\n tree: treeToRestore,\n nextUrl: extractPathFromFlightRouterState(treeToRestore) ?? url.pathname,\n }\n}\n","import type { FlightRouterState } from '../../../shared/lib/app-router-types'\nimport { handleExternalUrl } from './reducers/navigate-reducer'\nimport type {\n ReadonlyReducerState,\n ReducerActions,\n} from './router-reducer-types'\n\n/**\n * Handles the case where the client router attempted to patch the tree but, due to a mismatch, the patch failed.\n * This will perform an MPA navigation to return the router to a valid state.\n */\nexport function handleSegmentMismatch(\n state: ReadonlyReducerState,\n action: ReducerActions,\n treePatch: FlightRouterState\n) {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Performing hard navigation because your application experienced an unrecoverable error. If this keeps occurring, please file a Next.js issue.\\n\\n' +\n 'Reason: Segment mismatch\\n' +\n `Last Action: ${action.type}\\n\\n` +\n `Current Tree: ${JSON.stringify(state.tree)}\\n\\n` +\n `Tree Patch Payload: ${JSON.stringify(treePatch)}`\n )\n }\n\n return handleExternalUrl(state, {}, state.canonicalUrl, true)\n}\n","import type { FlightRouterState } from '../../../../shared/lib/app-router-types'\nimport { isInterceptionRouteAppPath } from '../../../../shared/lib/router/utils/interception-routes'\n\nexport function hasInterceptionRouteInCurrentTree([\n segment,\n parallelRoutes,\n]: FlightRouterState): boolean {\n // If we have a dynamic segment, it's marked as an interception route by the presence of the `i` suffix.\n if (Array.isArray(segment) && (segment[2] === 'di' || segment[2] === 'ci')) {\n return true\n }\n\n // If segment is not an array, apply the existing string-based check\n if (typeof segment === 'string' && isInterceptionRouteAppPath(segment)) {\n return true\n }\n\n // Iterate through parallelRoutes if they exist\n if (parallelRoutes) {\n for (const key in parallelRoutes) {\n if (hasInterceptionRouteInCurrentTree(parallelRoutes[key])) {\n return true\n }\n }\n }\n\n return false\n}\n","import { fetchServerResponse } from '../fetch-server-response'\nimport { createHrefFromUrl } from '../create-href-from-url'\nimport { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'\nimport { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'\nimport type {\n Mutable,\n ReadonlyReducerState,\n ReducerState,\n RefreshAction,\n} from '../router-reducer-types'\nimport { handleExternalUrl } from './navigate-reducer'\nimport { handleMutable } from '../handle-mutable'\nimport type { CacheNode } from '../../../../shared/lib/app-router-types'\nimport { fillLazyItemsTillLeafWithHead } from '../fill-lazy-items-till-leaf-with-head'\nimport { createEmptyCacheNode } from '../../app-router'\nimport { handleSegmentMismatch } from '../handle-segment-mismatch'\nimport { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'\nimport { refreshInactiveParallelSegments } from '../refetch-inactive-parallel-segments'\nimport { revalidateEntireCache } from '../../segment-cache'\n\nexport function refreshReducer(\n state: ReadonlyReducerState,\n action: RefreshAction\n): ReducerState {\n const { origin } = action\n const mutable: Mutable = {}\n const href = state.canonicalUrl\n\n let currentTree = state.tree\n\n mutable.preserveCustomHistoryState = false\n\n const cache: CacheNode = createEmptyCacheNode()\n\n // If the current tree was intercepted, the nextUrl should be included in the request.\n // This is to ensure that the refresh request doesn't get intercepted, accidentally triggering the interception route.\n const includeNextUrl = hasInterceptionRouteInCurrentTree(state.tree)\n\n // TODO-APP: verify that `href` is not an external url.\n // Fetch data from the root of the tree.\n cache.lazyData = fetchServerResponse(new URL(href, origin), {\n flightRouterState: [\n currentTree[0],\n currentTree[1],\n currentTree[2],\n 'refetch',\n ],\n nextUrl: includeNextUrl ? state.nextUrl : null,\n })\n\n const navigatedAt = Date.now()\n return cache.lazyData.then(\n async ({ flightData, canonicalUrl: canonicalUrlOverride }) => {\n // Handle case when navigating to page in `pages` from `app`\n if (typeof flightData === 'string') {\n return handleExternalUrl(\n state,\n mutable,\n flightData,\n state.pushRef.pendingPush\n )\n }\n\n // Remove cache.lazyData as it has been resolved at this point.\n cache.lazyData = null\n\n for (const normalizedFlightData of flightData) {\n const {\n tree: treePatch,\n seedData: cacheNodeSeedData,\n head,\n isRootRender,\n } = normalizedFlightData\n\n if (!isRootRender) {\n // TODO-APP: handle this case better\n console.log('REFRESH FAILED')\n return state\n }\n\n const newTree = applyRouterStatePatchToTree(\n // TODO-APP: remove ''\n [''],\n currentTree,\n treePatch,\n state.canonicalUrl\n )\n\n if (newTree === null) {\n return handleSegmentMismatch(state, action, treePatch)\n }\n\n if (isNavigatingToNewRootLayout(currentTree, newTree)) {\n return handleExternalUrl(\n state,\n mutable,\n href,\n state.pushRef.pendingPush\n )\n }\n\n const canonicalUrlOverrideHref = canonicalUrlOverride\n ? createHrefFromUrl(canonicalUrlOverride)\n : undefined\n\n if (canonicalUrlOverride) {\n mutable.canonicalUrl = canonicalUrlOverrideHref\n }\n\n // Handles case where prefetch only returns the router tree patch without rendered components.\n if (cacheNodeSeedData !== null) {\n const rsc = cacheNodeSeedData[1]\n const loading = cacheNodeSeedData[3]\n cache.rsc = rsc\n cache.prefetchRsc = null\n cache.loading = loading\n fillLazyItemsTillLeafWithHead(\n navigatedAt,\n cache,\n // Existing cache is not passed in as `router.refresh()` has to invalidate the entire cache.\n undefined,\n treePatch,\n cacheNodeSeedData,\n head,\n undefined\n )\n if (process.env.__NEXT_CLIENT_SEGMENT_CACHE) {\n revalidateEntireCache(state.nextUrl, newTree)\n } else {\n mutable.prefetchCache = new Map()\n }\n }\n\n await refreshInactiveParallelSegments({\n navigatedAt,\n state,\n updatedTree: newTree,\n updatedCache: cache,\n includeNextUrl,\n canonicalUrl: mutable.canonicalUrl || state.canonicalUrl,\n })\n\n mutable.cache = cache\n mutable.patchedTree = newTree\n\n currentTree = newTree\n }\n\n return handleMutable(state, mutable)\n },\n () => state\n )\n}\n","import { fetchServerResponse } from '../fetch-server-response'\nimport { createHrefFromUrl } from '../create-href-from-url'\nimport { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'\nimport { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'\nimport type {\n ReadonlyReducerState,\n ReducerState,\n HmrRefreshAction,\n Mutable,\n} from '../router-reducer-types'\nimport { handleExternalUrl } from './navigate-reducer'\nimport { handleMutable } from '../handle-mutable'\nimport { applyFlightData } from '../apply-flight-data'\nimport type { CacheNode } from '../../../../shared/lib/app-router-types'\nimport { createEmptyCacheNode } from '../../app-router'\nimport { handleSegmentMismatch } from '../handle-segment-mismatch'\nimport { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'\n\n// A version of refresh reducer that keeps the cache around instead of wiping all of it.\nfunction hmrRefreshReducerImpl(\n state: ReadonlyReducerState,\n action: HmrRefreshAction\n): ReducerState {\n const { origin } = action\n const mutable: Mutable = {}\n const href = state.canonicalUrl\n\n mutable.preserveCustomHistoryState = false\n\n const cache: CacheNode = createEmptyCacheNode()\n // If the current tree was intercepted, the nextUrl should be included in the request.\n // This is to ensure that the refresh request doesn't get intercepted, accidentally triggering the interception route.\n const includeNextUrl = hasInterceptionRouteInCurrentTree(state.tree)\n\n // TODO-APP: verify that `href` is not an external url.\n // Fetch data from the root of the tree.\n const navigatedAt = Date.now()\n cache.lazyData = fetchServerResponse(new URL(href, origin), {\n flightRouterState: [state.tree[0], state.tree[1], state.tree[2], 'refetch'],\n nextUrl: includeNextUrl ? state.nextUrl : null,\n isHmrRefresh: true,\n })\n\n return cache.lazyData.then(\n ({ flightData, canonicalUrl: canonicalUrlOverride }) => {\n // Handle case when navigating to page in `pages` from `app`\n if (typeof flightData === 'string') {\n return handleExternalUrl(\n state,\n mutable,\n flightData,\n state.pushRef.pendingPush\n )\n }\n\n // Remove cache.lazyData as it has been resolved at this point.\n cache.lazyData = null\n\n let currentTree = state.tree\n let currentCache = state.cache\n\n for (const normalizedFlightData of flightData) {\n const { tree: treePatch, isRootRender } = normalizedFlightData\n if (!isRootRender) {\n // TODO-APP: handle this case better\n console.log('REFRESH FAILED')\n return state\n }\n\n const newTree = applyRouterStatePatchToTree(\n // TODO-APP: remove ''\n [''],\n currentTree,\n treePatch,\n state.canonicalUrl\n )\n\n if (newTree === null) {\n return handleSegmentMismatch(state, action, treePatch)\n }\n\n if (isNavigatingToNewRootLayout(currentTree, newTree)) {\n return handleExternalUrl(\n state,\n mutable,\n href,\n state.pushRef.pendingPush\n )\n }\n\n const canonicalUrlOverrideHref = canonicalUrlOverride\n ? createHrefFromUrl(canonicalUrlOverride)\n : undefined\n\n if (canonicalUrlOverride) {\n mutable.canonicalUrl = canonicalUrlOverrideHref\n }\n const applied = applyFlightData(\n navigatedAt,\n currentCache,\n cache,\n normalizedFlightData\n )\n\n if (applied) {\n mutable.cache = cache\n currentCache = cache\n }\n\n mutable.patchedTree = newTree\n mutable.canonicalUrl = href\n\n currentTree = newTree\n }\n return handleMutable(state, mutable)\n },\n () => state\n )\n}\n\nfunction hmrRefreshReducerNoop(\n state: ReadonlyReducerState,\n _action: HmrRefreshAction\n): ReducerState {\n return state\n}\n\nexport const hmrRefreshReducer =\n process.env.NODE_ENV === 'production'\n ? hmrRefreshReducerNoop\n : hmrRefreshReducerImpl\n","import { addBasePath } from './add-base-path'\n\n/**\n * Function to correctly assign location to URL\n *\n * The method will add basePath, and will also correctly add location (including if it is a relative path)\n * @param location Location that should be added to the url\n * @param url Base URL to which the location should be assigned\n */\nexport function assignLocation(location: string, url: URL): URL {\n if (location.startsWith('.')) {\n const urlBase = url.origin + url.pathname\n return new URL(\n // In order for a relative path to be added to the current url correctly, the current url must end with a slash\n // new URL('./relative', 'https://example.com/subdir').href -> 'https://example.com/relative'\n // new URL('./relative', 'https://example.com/subdir/').href -> 'https://example.com/subdir/relative'\n (urlBase.endsWith('/') ? urlBase : urlBase + '/') + location\n )\n }\n\n return new URL(addBasePath(location), url.href)\n}\n","export interface ServerReferenceInfo {\n type: 'server-action' | 'use-cache'\n usedArgs: [boolean, boolean, boolean, boolean, boolean, boolean]\n hasRestArgs: boolean\n}\n\n/**\n * Extracts info about the server reference for the given server reference ID by\n * parsing the first byte of the hex-encoded ID.\n *\n * ```\n * Bit positions: [7] [6] [5] [4] [3] [2] [1] [0]\n * Bits: typeBit argMask restArgs\n * ```\n *\n * If the `typeBit` is `1` the server reference represents a `\"use cache\"`\n * function, otherwise a server action.\n *\n * The `argMask` encodes whether the function uses the argument at the\n * respective position.\n *\n * The `restArgs` bit indicates whether the function uses a rest parameter. It's\n * also set to 1 if the function has more than 6 args.\n *\n * @param id hex-encoded server reference ID\n */\nexport function extractInfoFromServerReferenceId(\n id: string\n): ServerReferenceInfo {\n const infoByte = parseInt(id.slice(0, 2), 16)\n const typeBit = (infoByte >> 7) & 0x1\n const argMask = (infoByte >> 1) & 0x3f\n const restArgs = infoByte & 0x1\n const usedArgs = Array(6)\n\n for (let index = 0; index < 6; index++) {\n const bitPosition = 5 - index\n const bit = (argMask >> bitPosition) & 0x1\n usedArgs[index] = bit === 1\n }\n\n return {\n type: typeBit === 1 ? 'use-cache' : 'server-action',\n usedArgs: usedArgs as [\n boolean,\n boolean,\n boolean,\n boolean,\n boolean,\n boolean,\n ],\n hasRestArgs: restArgs === 1,\n }\n}\n\n/**\n * Creates a sparse array containing only the used arguments based on the\n * provided action info.\n */\nexport function omitUnusedArgs(\n args: unknown[],\n info: ServerReferenceInfo\n): unknown[] {\n const filteredArgs = new Array(args.length)\n\n for (let index = 0; index < args.length; index++) {\n if (\n (index < 6 && info.usedArgs[index]) ||\n // This assumes that the server reference info byte has the restArgs bit\n // set to 1 if there are more than 6 args.\n (index >= 6 && info.hasRestArgs)\n ) {\n filteredArgs[index] = args[index]\n }\n }\n\n return filteredArgs\n}\n","import type {\n ActionFlightResponse,\n ActionResult,\n} from '../../../../shared/lib/app-router-types'\nimport { callServer } from '../../../app-call-server'\nimport { findSourceMapURL } from '../../../app-find-source-map-url'\nimport {\n ACTION_HEADER,\n NEXT_ACTION_NOT_FOUND_HEADER,\n NEXT_IS_PRERENDER_HEADER,\n NEXT_HTML_REQUEST_ID_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_URL,\n RSC_CONTENT_TYPE_HEADER,\n} from '../../app-router-headers'\nimport { UnrecognizedActionError } from '../../unrecognized-action-error'\n\n// TODO: Explicitly import from client.browser\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n createFromFetch as createFromFetchBrowser,\n createTemporaryReferenceSet,\n encodeReply,\n} from 'react-server-dom-webpack/client'\n\nimport {\n PrefetchKind,\n type ReadonlyReducerState,\n type ReducerState,\n type ServerActionAction,\n type ServerActionMutable,\n} from '../router-reducer-types'\nimport { assignLocation } from '../../../assign-location'\nimport { createHrefFromUrl } from '../create-href-from-url'\nimport { handleExternalUrl } from './navigate-reducer'\nimport { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'\nimport { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'\nimport type { CacheNode } from '../../../../shared/lib/app-router-types'\nimport { handleMutable } from '../handle-mutable'\nimport { fillLazyItemsTillLeafWithHead } from '../fill-lazy-items-till-leaf-with-head'\nimport { createEmptyCacheNode } from '../../app-router'\nimport { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'\nimport { handleSegmentMismatch } from '../handle-segment-mismatch'\nimport { refreshInactiveParallelSegments } from '../refetch-inactive-parallel-segments'\nimport {\n normalizeFlightData,\n prepareFlightRouterStateForRequest,\n type NormalizedFlightData,\n} from '../../../flight-data-helpers'\nimport { getRedirectError } from '../../redirect'\nimport { RedirectType } from '../../redirect-error'\nimport { createSeededPrefetchCacheEntry } from '../prefetch-cache-utils'\nimport { removeBasePath } from '../../../remove-base-path'\nimport { hasBasePath } from '../../../has-base-path'\nimport {\n extractInfoFromServerReferenceId,\n omitUnusedArgs,\n} from '../../../../shared/lib/server-reference-info'\nimport { revalidateEntireCache } from '../../segment-cache'\n\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 (process.env.NODE_ENV !== 'production') {\n createDebugChannel = (\n require('../../../dev/debug-channel') as typeof import('../../../dev/debug-channel')\n ).createDebugChannel\n}\n\ntype FetchServerActionResult = {\n redirectLocation: URL | undefined\n redirectType: RedirectType | undefined\n actionResult: ActionResult | undefined\n actionFlightData: NormalizedFlightData[] | string | undefined\n isPrerender: boolean\n revalidatedParts: {\n tag: boolean\n cookie: boolean\n paths: string[]\n }\n}\n\nasync function fetchServerAction(\n state: ReadonlyReducerState,\n nextUrl: ReadonlyReducerState['nextUrl'],\n { actionId, actionArgs }: ServerActionAction\n): Promise<FetchServerActionResult> {\n const temporaryReferences = createTemporaryReferenceSet()\n const info = extractInfoFromServerReferenceId(actionId)\n\n // TODO: Currently, we're only omitting unused args for the experimental \"use\n // cache\" functions. Once the server reference info byte feature is stable, we\n // should apply this to server actions as well.\n const usedArgs =\n info.type === 'use-cache' ? omitUnusedArgs(actionArgs, info) : actionArgs\n\n const body = await encodeReply(usedArgs, { temporaryReferences })\n\n const headers: Record<string, string> = {\n Accept: RSC_CONTENT_TYPE_HEADER,\n [ACTION_HEADER]: actionId,\n [NEXT_ROUTER_STATE_TREE_HEADER]: prepareFlightRouterStateForRequest(\n state.tree\n ),\n }\n\n if (process.env.NEXT_DEPLOYMENT_ID) {\n headers['x-deployment-id'] = process.env.NEXT_DEPLOYMENT_ID\n }\n\n if (nextUrl) {\n headers[NEXT_URL] = nextUrl\n }\n\n if (process.env.NODE_ENV !== 'production' && self.__next_r) {\n headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r\n }\n\n const res = await fetch(state.canonicalUrl, { method: 'POST', headers, body })\n\n // Handle server actions that the server didn't recognize.\n const unrecognizedActionHeader = res.headers.get(NEXT_ACTION_NOT_FOUND_HEADER)\n if (unrecognizedActionHeader === '1') {\n throw new UnrecognizedActionError(\n `Server Action \"${actionId}\" was not found on the server. \\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`\n )\n }\n\n const redirectHeader = res.headers.get('x-action-redirect')\n const [location, _redirectType] = redirectHeader?.split(';') || []\n let redirectType: RedirectType | undefined\n switch (_redirectType) {\n case 'push':\n redirectType = RedirectType.push\n break\n case 'replace':\n redirectType = RedirectType.replace\n break\n default:\n redirectType = undefined\n }\n\n const isPrerender = !!res.headers.get(NEXT_IS_PRERENDER_HEADER)\n let revalidatedParts: FetchServerActionResult['revalidatedParts']\n try {\n const revalidatedHeader = JSON.parse(\n res.headers.get('x-action-revalidated') || '[[],0,0]'\n )\n revalidatedParts = {\n paths: revalidatedHeader[0] || [],\n tag: !!revalidatedHeader[1],\n cookie: revalidatedHeader[2],\n }\n } catch (e) {\n revalidatedParts = NO_REVALIDATED_PARTS\n }\n\n const redirectLocation = location\n ? assignLocation(\n location,\n new URL(state.canonicalUrl, window.location.href)\n )\n : undefined\n\n const contentType = res.headers.get('content-type')\n const isRscResponse = !!(\n contentType && contentType.startsWith(RSC_CONTENT_TYPE_HEADER)\n )\n\n // Handle invalid server action responses.\n // A valid response must have `content-type: text/x-component`, unless it's an external redirect.\n // (external redirects have an 'x-action-redirect' header, but the body is an empty 'text/plain')\n if (!isRscResponse && !redirectLocation) {\n // The server can respond with a text/plain error message, but we'll fallback to something generic\n // if there isn't one.\n const message =\n res.status >= 400 && contentType === 'text/plain'\n ? await res.text()\n : 'An unexpected response was received from the server.'\n\n throw new Error(message)\n }\n\n let actionResult: FetchServerActionResult['actionResult']\n let actionFlightData: FetchServerActionResult['actionFlightData']\n\n if (isRscResponse) {\n const response: ActionFlightResponse = await createFromFetch(\n Promise.resolve(res),\n {\n callServer,\n findSourceMapURL,\n temporaryReferences,\n debugChannel: createDebugChannel && createDebugChannel(res.headers),\n }\n )\n\n // An internal redirect can send an RSC response, but does not have a useful `actionResult`.\n actionResult = redirectLocation ? undefined : response.a\n actionFlightData = normalizeFlightData(response.f)\n } else {\n // An external redirect doesn't contain RSC data.\n actionResult = undefined\n actionFlightData = undefined\n }\n\n return {\n actionResult,\n actionFlightData,\n redirectLocation,\n redirectType,\n revalidatedParts,\n isPrerender,\n }\n}\n\nconst NO_REVALIDATED_PARTS = {\n paths: [],\n tag: false,\n cookie: false,\n}\n\n/*\n * This reducer is responsible for calling the server action and processing any side-effects from the server action.\n * It does not mutate the state by itself but rather delegates to other reducers to do the actual mutation.\n */\nexport function serverActionReducer(\n state: ReadonlyReducerState,\n action: ServerActionAction\n): ReducerState {\n const { resolve, reject } = action\n const mutable: ServerActionMutable = {}\n\n let currentTree = state.tree\n\n mutable.preserveCustomHistoryState = false\n\n // only pass along the `nextUrl` param (used for interception routes) if the current route was intercepted.\n // If the route has been intercepted, the action should be as well.\n // Otherwise the server action might be intercepted with the wrong action id\n // (ie, one that corresponds with the intercepted route)\n const nextUrl =\n state.nextUrl && hasInterceptionRouteInCurrentTree(state.tree)\n ? state.nextUrl\n : null\n\n const navigatedAt = Date.now()\n\n return fetchServerAction(state, nextUrl, action).then(\n async ({\n actionResult,\n actionFlightData: flightData,\n redirectLocation,\n redirectType,\n isPrerender,\n revalidatedParts,\n }) => {\n let redirectHref: string | undefined\n\n // honor the redirect type instead of defaulting to push in case of server actions.\n if (redirectLocation) {\n if (redirectType === RedirectType.replace) {\n state.pushRef.pendingPush = false\n mutable.pendingPush = false\n } else {\n state.pushRef.pendingPush = true\n mutable.pendingPush = true\n }\n\n redirectHref = createHrefFromUrl(redirectLocation, false)\n mutable.canonicalUrl = redirectHref\n }\n\n if (!flightData) {\n resolve(actionResult)\n\n // If there is a redirect but no flight data we need to do a mpaNavigation.\n if (redirectLocation) {\n return handleExternalUrl(\n state,\n mutable,\n redirectLocation.href,\n state.pushRef.pendingPush\n )\n }\n return state\n }\n\n if (typeof flightData === 'string') {\n // Handle case when navigating to page in `pages` from `app`\n resolve(actionResult)\n\n return handleExternalUrl(\n state,\n mutable,\n flightData,\n state.pushRef.pendingPush\n )\n }\n\n const actionRevalidated =\n revalidatedParts.paths.length > 0 ||\n revalidatedParts.tag ||\n revalidatedParts.cookie\n\n // Store whether this action triggered any revalidation\n // The action queue will use this information to potentially\n // trigger a refresh action if the action was discarded\n // (ie, due to a navigation, before the action completed)\n if (actionRevalidated) {\n action.didRevalidate = true\n }\n\n for (const normalizedFlightData of flightData) {\n const {\n tree: treePatch,\n seedData: cacheNodeSeedData,\n head,\n isRootRender,\n } = normalizedFlightData\n\n if (!isRootRender) {\n // TODO-APP: handle this case better\n console.log('SERVER ACTION APPLY FAILED')\n resolve(actionResult)\n\n return state\n }\n\n // Given the path can only have two items the items are only the router state and rsc for the root.\n const newTree = applyRouterStatePatchToTree(\n // TODO-APP: remove ''\n [''],\n currentTree,\n treePatch,\n redirectHref ? redirectHref : state.canonicalUrl\n )\n\n if (newTree === null) {\n resolve(actionResult)\n\n return handleSegmentMismatch(state, action, treePatch)\n }\n\n if (isNavigatingToNewRootLayout(currentTree, newTree)) {\n resolve(actionResult)\n\n return handleExternalUrl(\n state,\n mutable,\n redirectHref || state.canonicalUrl,\n state.pushRef.pendingPush\n )\n }\n\n // The server sent back RSC data for the server action, so we need to apply it to the cache.\n if (cacheNodeSeedData !== null) {\n const rsc = cacheNodeSeedData[1]\n const cache: CacheNode = createEmptyCacheNode()\n cache.rsc = rsc\n cache.prefetchRsc = null\n cache.loading = cacheNodeSeedData[3]\n fillLazyItemsTillLeafWithHead(\n navigatedAt,\n cache,\n // Existing cache is not passed in as server actions have to invalidate the entire cache.\n undefined,\n treePatch,\n cacheNodeSeedData,\n head,\n undefined\n )\n\n mutable.cache = cache\n if (process.env.__NEXT_CLIENT_SEGMENT_CACHE) {\n revalidateEntireCache(state.nextUrl, newTree)\n } else {\n mutable.prefetchCache = new Map()\n }\n if (actionRevalidated) {\n await refreshInactiveParallelSegments({\n navigatedAt,\n state,\n updatedTree: newTree,\n updatedCache: cache,\n includeNextUrl: Boolean(nextUrl),\n canonicalUrl: mutable.canonicalUrl || state.canonicalUrl,\n })\n }\n }\n\n mutable.patchedTree = newTree\n currentTree = newTree\n }\n\n if (redirectLocation && redirectHref) {\n if (!process.env.__NEXT_CLIENT_SEGMENT_CACHE && !actionRevalidated) {\n // Because the RedirectBoundary will trigger a navigation, we need to seed the prefetch cache\n // with the FlightData that we got from the server action for the target page, so that it's\n // available when the page is navigated to and doesn't need to be re-fetched.\n // We only do this if the server action didn't revalidate any data, as in that case the\n // client cache will be cleared and the data will be re-fetched anyway.\n // NOTE: We don't do this in the Segment Cache implementation.\n // Dynamic data should never be placed into the cache, unless it's\n // \"converted\" to static data using <Link prefetch={true}>. What we\n // do instead is re-prefetch links and forms whenever the cache is\n // invalidated.\n createSeededPrefetchCacheEntry({\n url: redirectLocation,\n data: {\n flightData,\n canonicalUrl: undefined,\n couldBeIntercepted: false,\n prerendered: false,\n postponed: false,\n // TODO: We should be able to set this if the server action\n // returned a fully static response.\n staleTime: -1,\n },\n tree: state.tree,\n prefetchCache: state.prefetchCache,\n nextUrl: state.nextUrl,\n kind: isPrerender ? PrefetchKind.FULL : PrefetchKind.AUTO,\n })\n mutable.prefetchCache = state.prefetchCache\n }\n\n // If the action triggered a redirect, the action promise will be rejected with\n // a redirect so that it's handled by RedirectBoundary as we won't have a valid\n // action result to resolve the promise with. This will effectively reset the state of\n // the component that called the action as the error boundary will remount the tree.\n // The status code doesn't matter here as the action handler will have already sent\n // a response with the correct status code.\n reject(\n getRedirectError(\n hasBasePath(redirectHref)\n ? removeBasePath(redirectHref)\n : redirectHref,\n redirectType || RedirectType.push\n )\n )\n } else {\n resolve(actionResult)\n }\n\n return handleMutable(state, mutable)\n },\n (e: any) => {\n // When the server action is rejected we don't update the state and instead call the reject handler of the promise.\n reject(e)\n\n return state\n }\n )\n}\n","import {\n ACTION_NAVIGATE,\n ACTION_SERVER_PATCH,\n ACTION_RESTORE,\n ACTION_REFRESH,\n ACTION_PREFETCH,\n ACTION_HMR_REFRESH,\n ACTION_SERVER_ACTION,\n} from './router-reducer-types'\nimport type {\n ReducerActions,\n ReducerState,\n ReadonlyReducerState,\n} from './router-reducer-types'\nimport { navigateReducer } from './reducers/navigate-reducer'\nimport { serverPatchReducer } from './reducers/server-patch-reducer'\nimport { restoreReducer } from './reducers/restore-reducer'\nimport { refreshReducer } from './reducers/refresh-reducer'\nimport { prefetchReducer } from './reducers/prefetch-reducer'\nimport { hmrRefreshReducer } from './reducers/hmr-refresh-reducer'\nimport { serverActionReducer } from './reducers/server-action-reducer'\n\n/**\n * Reducer that handles the app-router state updates.\n */\nfunction clientReducer(\n state: ReadonlyReducerState,\n action: ReducerActions\n): ReducerState {\n switch (action.type) {\n case ACTION_NAVIGATE: {\n return navigateReducer(state, action)\n }\n case ACTION_SERVER_PATCH: {\n return serverPatchReducer(state, action)\n }\n case ACTION_RESTORE: {\n return restoreReducer(state, action)\n }\n case ACTION_REFRESH: {\n return refreshReducer(state, action)\n }\n case ACTION_HMR_REFRESH: {\n return hmrRefreshReducer(state, action)\n }\n case ACTION_PREFETCH: {\n return prefetchReducer(state, action)\n }\n case ACTION_SERVER_ACTION: {\n return serverActionReducer(state, action)\n }\n // This case should never be hit as dispatch is strongly typed.\n default:\n throw new Error('Unknown action')\n }\n}\n\nfunction serverReducer(\n state: ReadonlyReducerState,\n _action: ReducerActions\n): ReducerState {\n return state\n}\n\n// we don't run the client reducer on the server, so we use a noop function for better tree shaking\nexport const reducer =\n typeof window === 'undefined' ? serverReducer : clientReducer\n","import {\n type AppRouterState,\n type ReducerActions,\n type ReducerState,\n ACTION_REFRESH,\n ACTION_SERVER_ACTION,\n ACTION_NAVIGATE,\n ACTION_RESTORE,\n type NavigateAction,\n ACTION_HMR_REFRESH,\n PrefetchKind,\n ACTION_PREFETCH,\n} from './router-reducer/router-reducer-types'\nimport { reducer } from './router-reducer/router-reducer'\nimport { startTransition } from 'react'\nimport { isThenable } from '../../shared/lib/is-thenable'\nimport {\n FetchStrategy,\n prefetch as prefetchWithSegmentCache,\n type PrefetchTaskFetchStrategy,\n} from './segment-cache'\nimport { dispatchAppRouterAction } from './use-action-queue'\nimport { addBasePath } from '../add-base-path'\nimport { createPrefetchURL, isExternalURL } from './app-router'\nimport { prefetchReducer } from './router-reducer/reducers/prefetch-reducer'\nimport type {\n AppRouterInstance,\n NavigateOptions,\n PrefetchOptions,\n} from '../../shared/lib/app-router-context.shared-runtime'\nimport { setLinkForCurrentNavigation, type LinkInstance } from './links'\nimport type { FlightRouterState } from '../../shared/lib/app-router-types'\nimport type { ClientInstrumentationHooks } from '../app-index'\nimport type { GlobalErrorComponent } from './builtin/global-error'\n\nexport type DispatchStatePromise = React.Dispatch<ReducerState>\n\nexport type AppRouterActionQueue = {\n state: AppRouterState\n dispatch: (payload: ReducerActions, setState: DispatchStatePromise) => void\n action: (state: AppRouterState, action: ReducerActions) => ReducerState\n\n onRouterTransitionStart:\n | ((url: string, type: 'push' | 'replace' | 'traverse') => void)\n | null\n\n pending: ActionQueueNode | null\n needsRefresh?: boolean\n last: ActionQueueNode | null\n}\n\nexport type GlobalErrorState = [\n GlobalError: GlobalErrorComponent,\n styles: React.ReactNode,\n]\n\nexport type ActionQueueNode = {\n payload: ReducerActions\n next: ActionQueueNode | null\n resolve: (value: ReducerState) => void\n reject: (err: Error) => void\n discarded?: boolean\n}\n\nfunction runRemainingActions(\n actionQueue: AppRouterActionQueue,\n setState: DispatchStatePromise\n) {\n if (actionQueue.pending !== null) {\n actionQueue.pending = actionQueue.pending.next\n if (actionQueue.pending !== null) {\n runAction({\n actionQueue,\n action: actionQueue.pending,\n setState,\n })\n }\n } else {\n // Check for refresh when pending is already null\n // This handles the case where a discarded server action completes\n // after the navigation has already finished and the queue is empty\n if (actionQueue.needsRefresh) {\n actionQueue.needsRefresh = false\n actionQueue.dispatch(\n {\n type: ACTION_REFRESH,\n origin: window.location.origin,\n },\n setState\n )\n }\n }\n}\n\nasync function runAction({\n actionQueue,\n action,\n setState,\n}: {\n actionQueue: AppRouterActionQueue\n action: ActionQueueNode\n setState: DispatchStatePromise\n}) {\n const prevState = actionQueue.state\n\n actionQueue.pending = action\n\n const payload = action.payload\n const actionResult = actionQueue.action(prevState, payload)\n\n function handleResult(nextState: AppRouterState) {\n // if we discarded this action, the state should also be discarded\n if (action.discarded) {\n // Check if the discarded server action revalidated data\n if (\n action.payload.type === ACTION_SERVER_ACTION &&\n action.payload.didRevalidate\n ) {\n // The server action was discarded but it revalidated data,\n // mark that we need to refresh after all actions complete\n actionQueue.needsRefresh = true\n }\n // Still need to run remaining actions even for discarded actions\n // to potentially trigger the refresh\n runRemainingActions(actionQueue, setState)\n return\n }\n\n actionQueue.state = nextState\n\n runRemainingActions(actionQueue, setState)\n action.resolve(nextState)\n }\n\n // if the action is a promise, set up a callback to resolve it\n if (isThenable(actionResult)) {\n actionResult.then(handleResult, (err) => {\n runRemainingActions(actionQueue, setState)\n action.reject(err)\n })\n } else {\n handleResult(actionResult)\n }\n}\n\nfunction dispatchAction(\n actionQueue: AppRouterActionQueue,\n payload: ReducerActions,\n setState: DispatchStatePromise\n) {\n let resolvers: {\n resolve: (value: ReducerState) => void\n reject: (reason: any) => void\n } = { resolve: setState, reject: () => {} }\n\n // most of the action types are async with the exception of restore\n // it's important that restore is handled quickly since it's fired on the popstate event\n // and we don't want to add any delay on a back/forward nav\n // this only creates a promise for the async actions\n if (payload.type !== ACTION_RESTORE) {\n // Create the promise and assign the resolvers to the object.\n const deferredPromise = new Promise<AppRouterState>((resolve, reject) => {\n resolvers = { resolve, reject }\n })\n\n startTransition(() => {\n // we immediately notify React of the pending promise -- the resolver is attached to the action node\n // and will be called when the associated action promise resolves\n setState(deferredPromise)\n })\n }\n\n const newAction: ActionQueueNode = {\n payload,\n next: null,\n resolve: resolvers.resolve,\n reject: resolvers.reject,\n }\n\n // Check if the queue is empty\n if (actionQueue.pending === null) {\n // The queue is empty, so add the action and start it immediately\n // Mark this action as the last in the queue\n actionQueue.last = newAction\n\n runAction({\n actionQueue,\n action: newAction,\n setState,\n })\n } else if (\n payload.type === ACTION_NAVIGATE ||\n payload.type === ACTION_RESTORE\n ) {\n // Navigations (including back/forward) take priority over any pending actions.\n // Mark the pending action as discarded (so the state is never applied) and start the navigation action immediately.\n actionQueue.pending.discarded = true\n\n // The rest of the current queue should still execute after this navigation.\n // (Note that it can't contain any earlier navigations, because we always put those into `actionQueue.pending` by calling `runAction`)\n newAction.next = actionQueue.pending.next\n\n runAction({\n actionQueue,\n action: newAction,\n setState,\n })\n } else {\n // The queue is not empty, so add the action to the end of the queue\n // It will be started by runRemainingActions after the previous action finishes\n if (actionQueue.last !== null) {\n actionQueue.last.next = newAction\n }\n actionQueue.last = newAction\n }\n}\n\nlet globalActionQueue: AppRouterActionQueue | null = null\n\nexport function createMutableActionQueue(\n initialState: AppRouterState,\n instrumentationHooks: ClientInstrumentationHooks | null\n): AppRouterActionQueue {\n const actionQueue: AppRouterActionQueue = {\n state: initialState,\n dispatch: (payload: ReducerActions, setState: DispatchStatePromise) =>\n dispatchAction(actionQueue, payload, setState),\n action: async (state: AppRouterState, action: ReducerActions) => {\n const result = reducer(state, action)\n return result\n },\n pending: null,\n last: null,\n onRouterTransitionStart:\n instrumentationHooks !== null &&\n typeof instrumentationHooks.onRouterTransitionStart === 'function'\n ? // This profiling hook will be called at the start of every navigation.\n instrumentationHooks.onRouterTransitionStart\n : null,\n }\n\n if (typeof window !== 'undefined') {\n // The action queue is lazily created on hydration, but after that point\n // it doesn't change. So we can store it in a global rather than pass\n // it around everywhere via props/context.\n if (globalActionQueue !== null) {\n throw new Error(\n 'Internal Next.js Error: createMutableActionQueue was called more ' +\n 'than once'\n )\n }\n globalActionQueue = actionQueue\n }\n\n return actionQueue\n}\n\nexport function getCurrentAppRouterState(): AppRouterState | null {\n return globalActionQueue !== null ? globalActionQueue.state : null\n}\n\nfunction getAppRouterActionQueue(): AppRouterActionQueue {\n if (globalActionQueue === null) {\n throw new Error(\n 'Internal Next.js error: Router action dispatched before initialization.'\n )\n }\n return globalActionQueue\n}\n\nfunction getProfilingHookForOnNavigationStart() {\n if (globalActionQueue !== null) {\n return globalActionQueue.onRouterTransitionStart\n }\n return null\n}\n\nexport function dispatchNavigateAction(\n href: string,\n navigateType: NavigateAction['navigateType'],\n shouldScroll: boolean,\n linkInstanceRef: LinkInstance | null\n): void {\n // TODO: This stuff could just go into the reducer. Leaving as-is for now\n // since we're about to rewrite all the router reducer stuff anyway.\n const url = new URL(addBasePath(href), location.href)\n if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {\n window.next.__pendingUrl = url\n }\n\n setLinkForCurrentNavigation(linkInstanceRef)\n\n const onRouterTransitionStart = getProfilingHookForOnNavigationStart()\n if (onRouterTransitionStart !== null) {\n onRouterTransitionStart(href, navigateType)\n }\n\n dispatchAppRouterAction({\n type: ACTION_NAVIGATE,\n url,\n isExternalUrl: isExternalURL(url),\n locationSearch: location.search,\n shouldScroll,\n navigateType,\n allowAliasing: true,\n })\n}\n\nexport function dispatchTraverseAction(\n href: string,\n tree: FlightRouterState | undefined\n) {\n const onRouterTransitionStart = getProfilingHookForOnNavigationStart()\n if (onRouterTransitionStart !== null) {\n onRouterTransitionStart(href, 'traverse')\n }\n dispatchAppRouterAction({\n type: ACTION_RESTORE,\n url: new URL(href),\n tree,\n })\n}\n\n/**\n * The app router that is exposed through `useRouter`. These are public API\n * methods. Internal Next.js code should call the lower level methods directly\n * (although there's lots of existing code that doesn't do that).\n */\nexport const publicAppRouterInstance: AppRouterInstance = {\n back: () => window.history.back(),\n forward: () => window.history.forward(),\n prefetch: process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ? // Unlike the old implementation, the Segment Cache doesn't store its\n // data in the router reducer state; it writes into a global mutable\n // cache. So we don't need to dispatch an action.\n (href: string, options?: PrefetchOptions) => {\n const actionQueue = getAppRouterActionQueue()\n const prefetchKind = options?.kind ?? PrefetchKind.AUTO\n\n // We don't currently offer a way to issue a runtime prefetch via `router.prefetch()`.\n // This will be possible when we update its API to not take a PrefetchKind.\n let fetchStrategy: PrefetchTaskFetchStrategy\n switch (prefetchKind) {\n case PrefetchKind.AUTO: {\n // We default to PPR. We'll discover whether or not the route supports it with the initial prefetch.\n fetchStrategy = FetchStrategy.PPR\n break\n }\n case PrefetchKind.FULL: {\n fetchStrategy = FetchStrategy.Full\n break\n }\n case PrefetchKind.TEMPORARY: {\n // This concept doesn't exist in the segment cache implementation.\n return\n }\n default: {\n prefetchKind satisfies never\n // Despite typescript thinking that this can't happen,\n // we might get an unexpected value from user code.\n // We don't know what they want, but we know they want a prefetch,\n // so use the default.\n fetchStrategy = FetchStrategy.PPR\n }\n }\n\n prefetchWithSegmentCache(\n href,\n actionQueue.state.nextUrl,\n actionQueue.state.tree,\n fetchStrategy,\n options?.onInvalidate ?? null\n )\n }\n : (href: string, options?: PrefetchOptions) => {\n // Use the old prefetch implementation.\n const actionQueue = getAppRouterActionQueue()\n const url = createPrefetchURL(href)\n if (url !== null) {\n // The prefetch reducer doesn't actually update any state or\n // trigger a rerender. It just writes to a mutable cache. So we\n // shouldn't bother calling setState/dispatch; we can just re-run\n // the reducer directly using the current state.\n // TODO: Refactor this away from a \"reducer\" so it's\n // less confusing.\n prefetchReducer(actionQueue.state, {\n type: ACTION_PREFETCH,\n url,\n kind: options?.kind ?? PrefetchKind.FULL,\n })\n }\n },\n replace: (href: string, options?: NavigateOptions) => {\n startTransition(() => {\n dispatchNavigateAction(href, 'replace', options?.scroll ?? true, null)\n })\n },\n push: (href: string, options?: NavigateOptions) => {\n startTransition(() => {\n dispatchNavigateAction(href, 'push', options?.scroll ?? true, null)\n })\n },\n refresh: () => {\n startTransition(() => {\n dispatchAppRouterAction({\n type: ACTION_REFRESH,\n origin: window.location.origin,\n })\n })\n },\n hmrRefresh: () => {\n if (process.env.NODE_ENV !== 'development') {\n throw new Error(\n 'hmrRefresh can only be used in development mode. Please use refresh instead.'\n )\n } else {\n startTransition(() => {\n dispatchAppRouterAction({\n type: ACTION_HMR_REFRESH,\n origin: window.location.origin,\n })\n })\n }\n },\n}\n\n// Exists for debugging purposes. Don't use in application code.\nif (typeof window !== 'undefined' && window.next) {\n window.next.router = publicAppRouterInstance\n}\n","import type { FlightRouterState } from '../../shared/lib/app-router-types'\nimport type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime'\nimport { getCurrentAppRouterState } from './app-router-instance'\nimport { createPrefetchURL } from './app-router'\nimport {\n FetchStrategy,\n isPrefetchTaskDirty,\n type PrefetchTaskFetchStrategy,\n} from './segment-cache'\nimport { createCacheKey } from './segment-cache'\nimport {\n type PrefetchTask,\n PrefetchPriority,\n schedulePrefetchTask as scheduleSegmentPrefetchTask,\n cancelPrefetchTask,\n reschedulePrefetchTask,\n} from './segment-cache'\nimport { startTransition } from 'react'\nimport { PrefetchKind } from './router-reducer/router-reducer-types'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\ntype Element = HTMLAnchorElement | 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 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}\n\nexport function mountLinkInstance(\n element: HTMLAnchorElement,\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,\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 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 if (!process.env.__NEXT_CLIENT_SEGMENT_CACHE) {\n // The old prefetch implementation does not have different priority levels.\n // Just schedule a new prefetch task.\n prefetchWithOldCacheImplementation(instance)\n return\n }\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\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\nfunction prefetchWithOldCacheImplementation(instance: PrefetchableInstance) {\n // This is the path used when the Segment Cache is not enabled.\n if (typeof window === 'undefined') {\n return\n }\n\n const doPrefetch = async () => {\n // note that `appRouter.prefetch()` is currently sync,\n // so we have to wrap this call in an async function to be able to catch() errors below.\n\n let prefetchKind: PrefetchKind\n switch (instance.fetchStrategy) {\n case FetchStrategy.PPR: {\n prefetchKind = PrefetchKind.AUTO\n break\n }\n case FetchStrategy.Full: {\n prefetchKind = PrefetchKind.FULL\n break\n }\n case FetchStrategy.PPRRuntime: {\n // We can only get here if Client Segment Cache is off, and in that case\n // it shouldn't be possible for a link to request a runtime prefetch.\n throw new InvariantError(\n 'FetchStrategy.PPRRuntime should never be used when `experimental.clientSegmentCache` is disabled'\n )\n }\n default: {\n instance.fetchStrategy satisfies never\n // Unreachable, but otherwise typescript will consider the variable unassigned\n prefetchKind = undefined!\n }\n }\n\n return instance.router.prefetch(instance.prefetchHref, {\n kind: prefetchKind,\n })\n }\n\n // Prefetch the page if asked (only in the client)\n // We need to handle a prefetch error here since we may be\n // loading with priority which can reject but we don't\n // want to force navigation since this is only a prefetch\n doPrefetch().catch((err) => {\n if (process.env.NODE_ENV !== 'production') {\n // rethrow to show invalid URL errors\n throw err\n }\n })\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","'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 { dispatchNavigateAction } from '../components/app-router-instance'\nimport {\n FetchStrategy,\n type PrefetchTaskFetchStrategy,\n} from '../components/segment-cache'\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 * 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 | 'unstable_forceStale'\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 * 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<HTMLAnchorElement>): boolean {\n const eventTarget = event.currentTarget\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<HTMLAnchorElement>,\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 (isModifiedEvent(e) || e.currentTarget.hasAttribute('download')) {\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 React.startTransition(() => {\n dispatchNavigateAction(\n as || href,\n replace ? 'replace' : 'push',\n scroll ?? true,\n linkInstanceRef.current\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 const linkInstanceRef = useRef<LinkInstance | null>(null)\n\n const {\n href: hrefProp,\n as: asProp,\n children,\n prefetch: prefetchProp = null,\n replace,\n shallow,\n scroll,\n onClick,\n onMouseEnter: onMouseEnterProp,\n onTouchStart: onTouchStartProp,\n onNavigate,\n ref: forwardedRef,\n unstable_dynamicOnHover,\n ...restProps\n } = props\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 // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 prefetch: true,\n unstable_dynamicOnHover: true,\n onClick: true,\n onMouseEnter: true,\n onTouchStart: 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 === '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 props[key] !== 'unstable_forceStale'\n ) {\n throw createPropError({\n key,\n expected: '`boolean | \"auto\" | \"unstable_forceStale\"`',\n actual: valType,\n })\n }\n } else {\n // TypeScript trick for type-guarding:\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 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>.\\nLearn more: https://nextjs.org/docs/messages/invalid-new-link-with-extra-anchor'\n )\n }\n }\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) => {\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, forwardedRef)\n\n const anchorProps: React.DetailedHTMLProps<\n React.AnchorHTMLAttributes<HTMLAnchorElement>,\n HTMLAnchorElement\n > = {\n ref: mergedRef,\n onClick(e) {\n if (typeof onClick === 'function') {\n onClick(e)\n }\n\n if (!router) {\n return\n }\n\n if (e.defaultPrevented) {\n return\n }\n\n linkClicked(e, href, as, linkInstanceRef, replace, scroll, onNavigate)\n },\n onMouseEnter(e) {\n if (typeof onMouseEnterProp === 'function') {\n onMouseEnterProp(e)\n }\n\n if (!router) {\n return\n }\n\n if (!prefetchEnabled || process.env.NODE_ENV === 'development') {\n return\n }\n\n const upgradeToDynamicPrefetch = unstable_dynamicOnHover === true\n onNavigationIntent(e.currentTarget, upgradeToDynamicPrefetch)\n },\n onTouchStart: process.env.__NEXT_LINK_NO_TOUCH_START\n ? undefined\n : function onTouchStart(e) {\n if (typeof onTouchStartProp === 'function') {\n onTouchStartProp(e)\n }\n\n if (!router) {\n return\n }\n\n if (!prefetchEnabled) {\n return\n }\n\n const upgradeToDynamicPrefetch = unstable_dynamicOnHover === true\n onNavigationIntent(e.currentTarget, upgradeToDynamicPrefetch)\n },\n }\n\n // If the url is absolute, we can bypass the logic to prepend the basePath.\n if (isAbsoluteUrl(as)) {\n anchorProps.href = as\n } else {\n anchorProps.href = addBasePath(as)\n }\n\n return (\n <LinkStatusContext.Provider value={linkStatus}>\n <a {...restProps} {...anchorProps}>\n {children}\n </a>\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 (\n process.env.__NEXT_CACHE_COMPONENTS &&\n process.env.__NEXT_CLIENT_SEGMENT_CACHE\n ) {\n // In the new implementation:\n // - `prefetch={true}` is a runtime prefetch\n // (includes cached IO + params + cookies, with dynamic holes for uncached IO).\n // - `unstable_forceStale` is a \"full\" prefetch\n // (forces inclusion of all dynamic data, i.e. the old behavior of `prefetch={true}`)\n if (prefetchProp === true) {\n return FetchStrategy.PPRRuntime\n }\n if (prefetchProp === 'unstable_forceStale') {\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 // In `clientSegmentCache`, we default to PPR, and we'll discover whether or not the route supports it with the initial prefetch.\n // If we're not using `clientSegmentCache`, this will be converted into a `PrefetchKind.AUTO`.\n return FetchStrategy.PPR\n } else {\n return prefetchProp === null || prefetchProp === 'auto'\n ? // In `clientSegmentCache`, we default to PPR, and we'll discover whether or not the route supports it with the initial prefetch.\n // If we're not using `clientSegmentCache`, this will be converted into a `PrefetchKind.AUTO`.\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","\"use client\"\n\nimport Link from \"next/link\"\nimport { useEffect, useState } from \"react\"\n\ninterface MCPTool {\n name: string\n description: string\n category: string\n parameters: Array<{\n name: string\n type: string\n optional?: boolean\n description: string\n }>\n}\n\ninterface ToolsResponse {\n tools: MCPTool[]\n endpoint: string\n totalTools: number\n categories: string[]\n}\n\nexport default function HomePage() {\n const [tools, setTools] = useState<ToolsResponse | null>(null)\n const [loading, setLoading] = useState(true)\n\n useEffect(() => {\n fetch(\"/api/tools\")\n .then((res) => res.json())\n .then((data) => {\n setTools(data)\n setLoading(false)\n })\n .catch(() => {\n setLoading(false)\n })\n }, [])\n\n return (\n <div className=\"min-h-screen bg-white\">\n {/* Header */}\n <header className=\"bg-gray-50 border-b border-gray-200\">\n <div className=\"max-w-7xl mx-auto px-6 py-8\">\n <div className=\"flex items-center justify-between\">\n <div>\n <div className=\"flex items-center gap-4 mb-3\">\n <div className=\"w-12 h-12 bg-black rounded flex items-center justify-center\">\n <span className=\"text-white font-mono font-bold\">d3k</span>\n </div>\n <div>\n <h1 className=\"text-3xl font-bold text-gray-900\">dev3000 MCP Server</h1>\n <div className=\"flex items-center gap-3 mt-2\">\n <span className=\"inline-flex items-center gap-2 text-sm text-green-600 font-medium\">\n <span className=\"w-2 h-2 bg-green-500 rounded-full\"></span>\n Server Running\n </span>\n <span className=\"text-gray-300\">•</span>\n <span className=\"text-sm text-gray-600\">Port 3684</span>\n </div>\n </div>\n </div>\n </div>\n <div className=\"flex items-center gap-4\">\n <Link\n href=\"/logs\"\n className=\"inline-flex items-center gap-2 px-5 py-3 bg-blue-600 text-white text-sm font-medium rounded hover:bg-blue-700 transition-colors\"\n >\n 📊 View Logs\n </Link>\n <a\n href=\"https://github.com/vercel-labs/dev3000#setup\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"inline-flex items-center gap-2 px-5 py-3 border border-gray-300 text-gray-700 text-sm font-medium rounded hover:bg-gray-50 transition-colors\"\n >\n 📖 Setup Guide\n </a>\n </div>\n </div>\n </div>\n </header>\n\n <div className=\"flex max-w-7xl mx-auto\">\n {/* Main Content */}\n <main className=\"flex-1 px-6 py-8 min-w-0 lg:pr-80\">\n {/* Quick Start */}\n <section className=\"mb-16\">\n <div className=\"bg-blue-50 border border-blue-200 rounded p-8\">\n <h2 className=\"text-xl font-semibold text-blue-900 mb-4\">🚀 Quick Start</h2>\n <div className=\"space-y-4\">\n <div>\n <span className=\"text-sm font-medium text-blue-800\">MCP Endpoint:</span>\n <code className=\"ml-3 px-4 py-2 bg-blue-100 text-blue-800 text-sm font-mono rounded\">\n {tools?.endpoint || \"http://localhost:3684/api/mcp/mcp\"}\n </code>\n </div>\n <div className=\"text-sm text-blue-700\">\n <p className=\"mb-3\">Connect your AI tools to this MCP server for real-time development debugging:</p>\n <div className=\"flex gap-6\">\n <a\n href=\"https://github.com/vercel-labs/dev3000#claude-desktop\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"text-blue-600 hover:text-blue-800 font-medium\"\n >\n Claude Desktop Setup →\n </a>\n <a\n href=\"https://github.com/vercel-labs/dev3000#cursor\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"text-blue-600 hover:text-blue-800 font-medium\"\n >\n Cursor Setup →\n </a>\n </div>\n </div>\n </div>\n </div>\n </section>\n\n {/* Tools Documentation */}\n <section>\n <div className=\"mb-12\">\n <div>\n <h2 className=\"text-3xl font-bold text-gray-900 mb-3\">Available Tools</h2>\n <p className=\"text-gray-600 text-lg\">\n {loading\n ? \"Loading MCP tools...\"\n : `${tools?.totalTools || 0} tools across ${\n tools?.categories.length || 0\n } categories for AI-powered development debugging`}\n </p>\n </div>\n </div>\n\n {loading ? (\n <div className=\"text-center py-16\">\n <div className=\"inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600\"></div>\n <p className=\"mt-6 text-gray-600\">Loading tool documentation...</p>\n </div>\n ) : tools ? (\n <div className=\"grid gap-6 lg:grid-cols-2\">\n {tools.tools.map((tool) => (\n <div\n key={tool.name}\n id={tool.name}\n className=\"border border-gray-200 rounded p-6 hover:border-gray-300 transition-colors\"\n >\n <div className=\"mb-4\">\n <h4 className=\"text-xl font-semibold text-gray-900 font-mono mb-3\">{tool.name}</h4>\n <p className=\"text-gray-600 leading-relaxed\">\n {tool.description.replace(/🚨|⏰|🔍|🪄|📊|🌐|⚙️/g, \"\").trim()}\n </p>\n </div>\n {tool.parameters.length > 0 && (\n <div>\n <h5 className=\"text-sm font-semibold text-gray-800 mb-3\">Parameters:</h5>\n <div className=\"space-y-2\">\n {tool.parameters.map((param) => (\n <div key={param.name} className=\"text-sm\">\n <div className=\"flex items-start gap-2\">\n <span className=\"font-mono text-blue-600 font-medium\">{param.name}</span>\n <span className=\"text-gray-500 text-xs\">\n {param.optional ? \"(optional)\" : \"(required)\"}\n </span>\n <span className=\"text-gray-400 text-xs\">- {param.type}</span>\n </div>\n {param.description && (\n <div className=\"text-gray-600 ml-1 mt-1 text-sm\">{param.description}</div>\n )}\n </div>\n ))}\n </div>\n </div>\n )}\n </div>\n ))}\n </div>\n ) : (\n <div className=\"text-center py-16\">\n <p className=\"text-red-600 mb-6\">Failed to load tool documentation</p>\n <button\n onClick={() => window.location.reload()}\n className=\"px-6 py-3 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 transition-colors\"\n type=\"button\"\n >\n Retry\n </button>\n </div>\n )}\n </section>\n\n {/* Magic Workflow */}\n <section className=\"mt-20 bg-gradient-to-r from-purple-50 to-blue-50 border border-purple-200 rounded p-10\">\n <h2 className=\"text-2xl font-semibold text-gray-900 mb-6 flex items-center gap-3\">🪄 The Magic Workflow</h2>\n <div className=\"grid md:grid-cols-3 gap-8\">\n <div className=\"text-center\">\n <div className=\"w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4\">\n <span className=\"text-blue-600 font-bold text-lg\">1</span>\n </div>\n <h3 className=\"font-semibold mb-3 text-lg\">AI Finds Issues</h3>\n <p className=\"text-gray-600 leading-relaxed\">\n Tools like debug_my_app and monitor_for_new_errors automatically detect problems\n </p>\n </div>\n <div className=\"text-center\">\n <div className=\"w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-4\">\n <span className=\"text-purple-600 font-bold text-lg\">2</span>\n </div>\n <h3 className=\"font-semibold mb-3 text-lg\">AI Fixes Code</h3>\n <p className=\"text-gray-600 leading-relaxed\">\n AI analyzes errors and edits your code files to resolve issues\n </p>\n </div>\n <div className=\"text-center\">\n <div className=\"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4\">\n <span className=\"text-green-600 font-bold text-lg\">3</span>\n </div>\n <h3 className=\"font-semibold mb-3 text-lg\">AI Verifies Fixes</h3>\n <p className=\"text-gray-600 leading-relaxed\">\n execute_browser_action tests the fixes in real-time with screenshots\n </p>\n </div>\n </div>\n </section>\n </main>\n\n {/* Table of Contents - Sticky Sidebar (Right) */}\n <aside className=\"lg:block w-72 flex-shrink-0 fixed right-0 top-0 h-screen overflow-y-auto z-10\">\n <div className=\"p-6 bg-gray-50 border-l border-gray-200 h-full\">\n <h3 className=\"text-sm font-semibold text-gray-900 mb-4\">Tools</h3>\n {loading ? (\n <div className=\"text-sm text-gray-500\">Loading tools...</div>\n ) : tools ? (\n <nav className=\"space-y-1 text-sm\">\n {tools.tools.map((tool) => (\n <a\n key={tool.name}\n href={`#${tool.name}`}\n className=\"text-gray-600 hover:text-blue-600 transition-colors block py-2 px-3 rounded hover:bg-white\"\n >\n {tool.name}\n </a>\n ))}\n </nav>\n ) : (\n <div className=\"text-sm text-gray-500\">Failed to load tools</div>\n )}\n </div>\n </aside>\n </div>\n\n {/* Footer */}\n <footer className=\"border-t border-gray-200 mt-20\">\n <div className=\"max-w-7xl mx-auto px-6 py-8\">\n <div className=\"flex items-center justify-between text-sm text-gray-600\">\n <div>\n <span className=\"font-semibold\">dev3000 MCP Server</span> - AI-powered development monitoring\n </div>\n <div className=\"flex items-center gap-8\">\n <a\n href=\"https://github.com/vercel-labs/dev3000\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"hover:text-gray-900 transition-colors\"\n >\n GitHub\n </a>\n <a\n href=\"https://dev3000.ai\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"hover:text-gray-900 transition-colors\"\n >\n Homepage\n </a>\n <Link href=\"/logs\" className=\"hover:text-gray-900 transition-colors\">\n Logs\n </Link>\n </div>\n </div>\n </div>\n </footer>\n </div>\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","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","ACTION_HMR_REFRESH","ACTION_NAVIGATE","ACTION_PREFETCH","ACTION_REFRESH","ACTION_RESTORE","ACTION_SERVER_ACTION","ACTION_SERVER_PATCH","PrefetchCacheEntryStatus","PrefetchKind","ACTION_HEADER","FLIGHT_HEADERS","NEXT_ACTION_NOT_FOUND_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","isThenable","promise","then","dispatchAppRouterAction","useActionQueue","dispatch","action","actionQueue","state","setState","React","useState","useAppDevRenderingIndicator","require","appDevRenderingIndicator","use","callServer","actionId","actionArgs","Promise","resolve","reject","startTransition","type","findSourceMapURL","filename","document","URL","getFlightDataPartsFromPath","getNextFlightSegmentPath","normalizeFlightData","prepareFlightRouterStateForRequest","flightDataPath","flightDataPathLength","tree","seedData","head","isHeadPartial","segmentPath","pathToSegment","segment","isRootRender","flightSegmentPath","flightData","map","flightRouterState","isHmrRefresh","stripClientOnlyDataFromFlightRouterState","parallelRoutes","_url","refreshMarker","isRootLayout","hasLoadingBoundary","cleanedSegment","stripSearchParamsFromPageSegment","cleanedParallelRoutes","childState","shouldPreserveRefreshMarker","PAGE_SEGMENT_KEY","Boolean","getAppBuildId","setAppBuildId","globalBuildId","buildId","djb2Hash","hexHash","str","i","char","charCodeAt","toString","computeCacheBustingSearchParam","prefetchHeader","segmentPrefetchHeader","stateTreeHeader","nextUrlHeader","setCacheBustingSearchParam","setCacheBustingSearchParamWithHash","headers","uniqueCacheKey","existingSearch","rawQuery","pairs","filter","pair","ROOT_SEGMENT_CACHE_KEY","ROOT_SEGMENT_REQUEST_KEY","appendSegmentCacheKeyPart","appendSegmentRequestKeyPart","convertSegmentPathToStaticExportFilename","createSegmentCacheKeyPart","createSegmentRequestKeyPart","safeName","encodeToFilesystemAndURLSafeString","paramType","encodedName","parentRequestKey","parallelRouteKey","childRequestKeyPart","slotKey","requestKeyPart","paramValue","safeValue","parentSegmentKey","childCacheKeyPart","simpleParamValueRegex","base64url","btoa","doesStaticSegmentAppearInURL","getCacheKeyForDynamicParam","getParamValueFromCacheKey","getRenderedPathname","getRenderedSearch","parseDynamicParamFromURLPart","urlToUrlWithoutFlightMarker","response","rewrittenQuery","get","rewrittenPath","pathnameParts","partIndex","s","DEFAULT_SEGMENT_KEY","renderedSearch","pageSegmentWithSearchParams","addSearchParamsIfPageSegment","fromEntries","urlWithoutFlightParameters","__NEXT_CONFIG_OUTPUT","paramCacheKey","isCatchAll","createFetch","createFromNextReadableStream","fetchServerResponse","createFromReadableStream","createFromReadableStreamBrowser","createDebugChannel","doMpaNavigation","canonicalUrl","couldBeIntercepted","prerendered","postponed","staleTime","abortController","AbortController","addEventListener","abort","options","nextUrl","prefetchKind","AUTO","fetchPriority","TEMPORARY","signal","responseUrl","redirected","contentType","interception","staleTimeHeaderSeconds","parseInt","isFlightResponse","ok","body","TURBOPACK","waitForWebpackRuntimeHotUpdate","flightStream","createUnclosingPrefetchStream","b","f","S","err","aborted","__NEXT_TEST_MODE","NEXT_DEPLOYMENT_ID","self","__next_r","fetchOptions","credentials","priority","fetchUrl","browserResponse","fetch","__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS","MAX_REDIRECTS","n","rscResponse","status","responseHeaders","debugChannel","originalFlightStream","reader","getReader","ReadableStream","pull","controller","done","read","enqueue","createHrefFromUrl","includeHash","createRouterCacheKey","withoutSearchParameters","invalidateCacheBelowFlightSegmentPath","newCache","existingCache","isLastEntry","cacheKey","existingChildSegmentMap","childSegmentMap","Map","existingChildCacheNode","childCacheNode","lazyData","rsc","prefetchRsc","prefetchHead","matchSegment","existingSegment","fillLazyItemsTillLeafWithHead","navigatedAt","routerState","cacheNodeSeedData","prefetchEntry","isLastSegment","parallelRouteState","segmentForParallelRoute","parallelSeedData","existingParallelRoutesCacheNode","hasReusablePrefetch","kind","reusable","parallelRouteCacheNode","existingCacheNode","newCacheNode","seedNode","loading","existingParallelRoutes","invalidateCacheByRouterState","fillCacheWithNewSubTreeData","fillCacheWithNewSubTreeDataButOnlyLoading","fillCacheHelper","fillLazyItems","treePatch","incomingSegment","applyFlightData","cache","addRefreshMarkerToActiveParallelSegments","refreshInactiveParallelSegments","fetchedSegments","Set","refreshInactiveParallelSegmentsImpl","rootTree","updatedTree","updatedCache","includeNextUrl","refetchPath","refetchMarker","fetchPromises","has","add","fetchPromise","parallelFetchPromise","all","applyRouterStatePatchToTree","applyPatch","initialTree","patchTree","initialSegment","initialParallelRoutes","patchSegment","patchParallelRoutes","newParallelRoutes","isInPatchTreeParallelRoutes","refetch","currentSegment","lastSegment","parallelRoutePatch","shouldHardNavigate","isNavigatingToNewRootLayout","currentTree","nextTree","currentTreeSegment","nextTreeSegment","currentTreeChild","values","nextTreeChild","ensureLeadingSlash","normalizeAppPath","normalizeRscURL","reduce","index","segments","isGroupSegment","INTERCEPTION_ROUTE_MARKERS","extractInterceptionRouteInformation","isInterceptionRouteAppPath","find","m","interceptingRoute","marker","interceptedRoute","concat","splitInterceptingRoute","computeChangedPath","extractPathFromFlightRouterState","getSelectedParams","removeLeadingSlash","segmentToPathname","normalizeSegments","acc","some","childrenPath","children","childPath","computeChangedPathImpl","treeA","treeB","segmentA","parallelRoutesA","segmentB","parallelRoutesB","normalizedSegmentA","normalizedSegmentB","parallelRouterKey","changedPath","params","parallelRoute","isDynamicParameter","segmentValue","handleMutable","isNotUndefined","mutable","shouldScroll","patchedTree","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","apply","scrollableSegments","onlyHashChange","hashFragment","decodeURIComponent","segmentPaths","prefetchCache","PromiseQueue","promiseFn","taskResolve","taskReject","taskPromise","task","enqueueResult","bump","findIndex","bumpedItem","splice","unshift","maxConcurrency","forced","shift","DYNAMIC_STALETIME_MS","STATIC_STALETIME_MS","createSeededPrefetchCacheEntry","getOrCreatePrefetchCacheEntry","prunePrefetchCache","INTERCEPTION_CACHE_KEY_MARKER","createPrefetchCacheKeyImpl","includeSearchParams","pathnameFromUrl","createPrefetchCacheKey","FULL","getExistingCacheEntry","allowAliasing","maybeNextUrl","cacheKeyWithParams","cacheKeyWithoutParams","cacheKeyToUse","existingEntry","isAliased","aliased","entryWithoutParams","cacheEntry","existingCacheEntry","getPrefetchEntryCacheStatus","switchedToFullPrefetch","data","prefetchResponse","isFullPrefetch","createLazyPrefetchEntry","prefixExistingPrefetchCacheEntry","existingCacheKey","newCacheKey","prefetchCacheKey","treeAtTimeOfPrefetch","prefetchTime","Date","now","lastUsedTime","fresh","prefetchQueue","prefetchCacheEntry","expired","Number","__NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME","__NEXT_CLIENT_ROUTER_STATIC_STALETIME","stale","prefetchReducer","__NEXT_CLIENT_SEGMENT_CACHE","identityReducerWhenSegmentCacheIsEnabled","prefetchReducerImpl","HTML_LIMITED_BOT_UA_RE","HTML_LIMITED_BOT_UA_RE_STRING","getBotType","isBot","HEADLESS_BROWSER_BOT_UA_RE","source","isDomBotUA","userAgent","isHtmlLimitedBotUA","AppRouterAnnouncer","ANNOUNCER_TYPE","ANNOUNCER_ID","getAnnouncerNode","existingAnnouncer","getElementsByName","shadowRoot","childNodes","container","createElement","style","cssText","announcer","ariaLive","id","role","shadow","attachShadow","mode","appendChild","portalNode","setPortalNode","useEffect","getElementsByTagName","isConnected","removeChild","routeAnnouncement","setRouteAnnouncement","previousTitle","useRef","currentTitle","title","pageHeader","querySelector","innerText","textContent","current","createPortal","RedirectBoundary","RedirectErrorBoundary","HandleRedirect","redirect","reset","redirectType","router","useRouter","RedirectType","getDerivedStateFromError","isRedirectError","getURLFromRedirectError","getRedirectTypeFromError","render","findHeadInCache","findHeadInCacheImpl","keyPrefix","keyPrefixWithoutSearchParams","isLastItem","parallelRoutesKeys","childParallelRoutes","cacheKeyWithoutSearchParams","cacheNode","unresolvedThenable","pathHasPrefix","hasBasePath","removeBasePath","handleHardNavError","useNavFailureHandler","next","__pendingUrl","__NEXT_APP_NAV_FAIL_HANDLING","uncaughtExceptionHandler","evt","reason","removeEventListener","GracefulDegradeBoundary","getDomNodeAttributes","node","attributes","attr","_","hasError","componentDidMount","htmlNode","htmlRef","htmlAttributes","setAttribute","rootHtml","documentElement","innerHTML","html","ref","suppressHydrationWarning","dangerouslySetInnerHTML","__html","createRef","useUntrackedPathname","hasFallbackRouteParams","workUnitAsyncStorage","workUnitStore","getStore","fallbackParams","fallbackRouteParams","size","useContext","PathnameContext","ErrorBoundary","ErrorBoundaryHandler","isBotUserAgent","navigator","isNextRouterError","getDerivedStateFromProps","previousPathname","HandleISRError","errorStyles","errorScripts","this","errorComponent","RootErrorBoundary","MetadataBoundary","OutletBoundary","RootLayoutBoundary","ViewportBoundary","NameSpace","METADATA_BOUNDARY_NAME","VIEWPORT_BOUNDARY_NAME","OUTLET_BOUNDARY_NAME","ROOT_LAYOUT_BOUNDARY_NAME","createEmptyCacheNode","createPrefetchURL","AppRouter","isExternalURL","globalMutable","HistoryUpdater","appRouterState","useInsertionEffect","historyState","history","__NA","__PRIVATE_NEXTJS_INTERNALS_TREE","pushState","replaceState","pingVisibleLinks","copyNextJsInternalHistoryState","currentState","Head","headCacheNode","resolvedPrefetchRsc","useDeferredValue","Router","globalError","webSocket","staticIndicatorState","useMemo","nd","publicAppRouterInstance","handlePageShow","event","persisted","pendingMpaPath","handleUnhandledRedirect","preventDefault","originalPushState","bind","originalReplaceState","applyUrlFromHistoryPushReplace","_unused","_N","onPopState","reload","dispatchTraverseAction","matchingHead","pathParams","layoutRouterContext","parentTree","parentCacheNode","parentSegmentPath","globalLayoutRouterContext","headKey","headKeyWithoutSearchParams","content","DevRootHTTPAccessFallbackBoundary","HotReloader","default","RuntimeStyles","PathParamsContext","Provider","SearchParamsContext","GlobalLayoutRouterContext","AppRouterContext","LayoutRouterContext","globalErrorState","DefaultGlobalError","runtimeStyles","runtimeStyleChanged","globalThis","_N_E_STYLE_LOAD","len","cb","forceUpdate","renderedStylesSize","changed","c","dplId","link","rel","precedence","abortTask","listenForDynamicRequest","startPPRNavigation","updateCacheNodeOnPopstateRestoration","MPA_NAVIGATION_TASK","dynamicRequestTree","oldCacheNode","oldRouterState","newRouterState","prefetchData","isPrefetchHeadPartial","isSamePageNavigation","scrollableSegmentsResult","updateCacheNodeOnNavigation","didFindRootLayout","oldRouterStateChildren","newRouterStateChildren","prefetchDataChildren","oldParallelRoutes","prefetchParallelRoutes","patchedRouterStateChildren","taskChildren","needsDynamicRequest","dynamicRequestTreeChildren","newRouterStateChild","oldRouterStateChild","oldSegmentMapChild","prefetchDataChild","newSegmentChild","newSegmentPathChild","newSegmentKeyChild","oldSegmentChild","oldCacheNodeChild","taskChild","spawnReusedTask","beginRenderingNewRouteTree","newCacheNodeChild","newSegmentMapChild","taskChildRoute","dynamicRequestTreeChild","patchRouterStateWithNewChildren","possiblyPartialPrefetchHead","createCacheNodeOnNavigation","routerStateChildren","isLeafSegment","cacheNodeNavigatedAt","isPrefetchRscPartial","spawnPendingTask","existingCacheNodeChildren","cacheNodeChildren","routerStateChild","existingSegmentMapChild","segmentChild","segmentPathChild","segmentKeyChild","existingCacheNodeChild","baseRouterState","newChildren","clone","newTask","createPendingCacheNode","reusedRouterState","responsePromise","normalizedFlightData","serverRouterState","dynamicData","dynamicHead","writeDynamicDataIntoPendingTask","rootTask","taskSegment","finishTaskUsingDynamicDataPayload","taskNode","finishPendingCacheNode","serverChildren","dynamicDataChildren","serverRouterStateChild","dynamicDataChild","maybePrefetchRsc","createDeferredRsc","taskState","serverState","taskStateChildren","serverStateChildren","dataChildren","taskStateChild","serverStateChild","dataChild","segmentMapChild","taskSegmentChild","taskSegmentKeyChild","cacheNodeChild","abortPendingCacheNode","dynamicSegmentData","isDeferredRsc","dynamicLoading","shouldUsePrefetch","DEFERRED","Symbol","tag","pendingRsc","rej","fulfilledRsc","rejectedRsc","clearCacheNodeDataForSegmentPath","addSearchParamsToPageSegments","handleAliasedPrefetchEntry","currentCache","applied","hasLoadingComponentInSeedData","flightSegmentPathWithLeadingEmpty","newTree","fillNewTreeWithOnlyLoadingSegments","subSegment","generateSegmentsFromPatch","scrollableSegmentPath","rest","newSegment","updatedParallelRoutes","FetchStrategy","NavigationResultTag","PrefetchPriority","cancelPrefetchTask","createCacheKey","getCurrentCacheVersion","isPrefetchTaskDirty","navigate","prefetch","reschedulePrefetchTask","revalidateEntireCache","schedulePrefetchTask","notEnabled","handleExternalUrl","navigateReducer","flightRouterPatch","childSegment","triggerLazyFetchForLeafSegments","appliedPatch","segmentPathsToFill","handleNavigationResult","MPA","newUrl","NoOp","newCanonicalUrl","oldUrl","Success","Async","asyncResult","isExternalUrl","navigateType","getElementById","navigateUsingSegmentCache","prefetchValues","canonicalUrlOverride","isFirstRead","urlWithCanonicalPathname","updatedCanonicalUrl","patchedRouterState","dynamicRequest","hardNavigate","serverPatchReducer","serverResponse","canonicalUrlOverrideHref","restoreReducer","treeToRestore","oldCache","__NEXT_PPR","handleSegmentMismatch","hasInterceptionRouteInCurrentTree","refreshReducer","log","hmrRefreshReducer","hmrRefreshReducerImpl","hmrRefreshReducerNoop","_action","assignLocation","urlBase","extractInfoFromServerReferenceId","omitUnusedArgs","infoByte","typeBit","argMask","restArgs","usedArgs","bitPosition","bit","hasRestArgs","info","filteredArgs","serverActionReducer","createFromFetch","createFromFetchBrowser","fetchServerAction","temporaryReferences","createTemporaryReferenceSet","encodeReply","Accept","unrecognizedActionHeader","UnrecognizedActionError","redirectHeader","_redirectType","isPrerender","revalidatedParts","revalidatedHeader","parse","paths","cookie","e","NO_REVALIDATED_PARTS","redirectLocation","isRscResponse","text","actionResult","actionFlightData","a","redirectHref","actionRevalidated","didRevalidate","getRedirectError","reducer","clientReducer","serverReducer","createMutableActionQueue","dispatchNavigateAction","getCurrentAppRouterState","runRemainingActions","pending","runAction","needsRefresh","prevState","payload","handleResult","nextState","discarded","dispatchAction","resolvers","deferredPromise","newAction","last","globalActionQueue","initialState","instrumentationHooks","onRouterTransitionStart","getAppRouterActionQueue","getProfilingHookForOnNavigationStart","linkInstanceRef","setLinkForCurrentNavigation","locationSearch","back","forward","fetchStrategy","PPR","Full","prefetchWithSegmentCache","onInvalidate","scroll","refresh","hmrRefresh","IDLE_LINK_STATUS","PENDING_LINK_STATUS","mountFormInstance","mountLinkInstance","onLinkVisibilityChanged","onNavigationIntent","unmountLinkForCurrentNavigation","unmountPrefetchableInstance","linkForMostRecentNavigation","setOptimisticLinkStatus","prefetchable","WeakMap","prefetchableAndVisible","observer","IntersectionObserver","handleIntersect","rootMargin","observeVisibility","element","instance","existingInstance","observe","coercePrefetchableUrl","reportErrorFn","reportError","prefetchEnabled","prefetchURL","isVisible","prefetchTask","prefetchHref","unobserve","entry","intersectionRatio","rescheduleLinkPrefetch","Default","unstable_upgradeToDynamicPrefetch","__NEXT_DYNAMIC_ON_HOVER","Intent","existingPrefetchTask","prefetchWithOldCacheImplementation","scheduleSegmentPrefetchTask","doPrefetch","PPRRuntime","InvariantError","catch","isLocalURL","locationOrigin","resolved","LinkComponent","useLinkStatus","isModifiedEvent","eventTarget","currentTarget","getAttribute","metaKey","ctrlKey","shiftKey","altKey","nativeEvent","which","linkClicked","as","onNavigate","hasAttribute","isDefaultPrevented","formatStringOrUrl","urlObjOrString","linkStatus","useOptimistic","hrefProp","asProp","prefetchProp","shallow","onClick","onMouseEnter","onMouseEnterProp","onTouchStart","onTouchStartProp","forwardedRef","unstable_dynamicOnHover","restProps","getFetchStrategyFromPrefetchProp","createPropError","expected","actual","requiredPropsGuard","requiredProps","optionalPropsGuard","optionalProps","valType","locale","warnOnce","hasDynamicSegment","resolvedHref","observeLinkVisibilityOnMount","useCallback","mergedRef","useMergedRef","anchorProps","defaultPrevented","upgradeToDynamicPrefetch","__NEXT_LINK_NO_TOUCH_START","LinkStatusContext","createContext","__NEXT_CACHE_COMPONENTS"],"mappings":"6CAEO,SAASC,EACdE,CAA6B,EAE7B,IAAMC,EAAwB,CAAC,EAC/B,IAAK,GAAM,CAACC,EAAKC,EAAM,GAAIH,EAAaI,OAAO,GAAI,CACjD,IAAMC,EAAWJ,CAAK,CAACC,EAAI,AACvB,MAAoB,IAAbG,EACTJ,CAAK,CAACC,EAAI,CAAGC,EADsB,AAE1BG,MAAMC,OAAO,CAACF,GACvBA,EAASG,IAAI,CAACL,CADoB,EAGlCF,CAAK,CAACC,EAAI,CAAG,CAACG,EAAUF,EAAM,AAElC,CACA,OAAOF,CACT,CAEA,SAASQ,EAAuBC,CAAc,QAC5C,AAAqB,UAAU,AAA3B,OAAOA,EACFA,GAIW,UAAjB,EAA6B,KAAtBA,GAAuBC,MAAMD,EAAAA,GACpB,WAAjB,AACA,OADOA,EAIA,GAFAE,OAAOF,EAIlB,CAEO,SAASX,EAAuBE,CAAqB,EAC1D,IAAMD,EAAe,IAAIa,gBACzB,IAAK,GAAM,CAACX,EAAKC,EAAM,GAAIW,OAAOV,OAAO,CAACH,GACxC,GAAIK,CAD4C,KACtCC,OAAO,CAACJ,GAChB,IAAK,CADmB,GACbY,KAAQZ,EACjBH,EAAagB,EADW,IACL,CAACd,EAAKO,EAAuBM,SAGlDf,EAAaiB,GAAG,CAACf,EAAKO,EAAuBN,IAGjD,OAAOH,CACT,CAEO,SAASH,EACdqB,CAAuB,EACvB,IAAA,IAAA,EAAA,UAAA,MAAA,CAAGC,EAAH,MAAA,EAAA,EAAA,EAAA,EAAA,GAAA,EAAA,EAAA,EAAA,EAAA,IAAGA,CAAAA,CAAH,CAAA,CAAA,EAAA,CAAA,SAAA,CAAA,EAAsC,CAEtC,IAAK,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