| self.__BUILD_MANIFEST = { | ||
| "__rewrites": { | ||
| "afterFiles": [], | ||
| "beforeFiles": [], | ||
| "fallback": [] | ||
| }, | ||
| "sortedPages": [ | ||
| "/_app", | ||
| "/_error" | ||
| ] | ||
| };self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB() |
| self.__MIDDLEWARE_MATCHERS = [];self.__MIDDLEWARE_MATCHERS_CB && self.__MIDDLEWARE_MATCHERS_CB() |
| self.__SSG_MANIFEST=new Set([]);self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB() |
| --- | ||
| title: Optimizing prefetching | ||
| description: Resolve per-link URL data with the prefetch prop, or include session data in the App Shell. | ||
| nav_title: Optimizing prefetching | ||
| related: | ||
| title: Learn more | ||
| description: Validate your structure and review the caching primitives. | ||
| links: | ||
| - app/api-reference/config/next-config-js/partialPrefetching | ||
| - app/api-reference/file-conventions/route-segment-config/prefetch | ||
| - app/api-reference/file-conventions/route-segment-config/instant | ||
| - app/api-reference/directives/use-cache-private | ||
| - app/getting-started/caching | ||
| - app/guides/instant-navigation | ||
| - app/guides/prefetching | ||
| --- | ||
| Prefetching downloads a route's JavaScript, CSS, and RSC payload before the user navigates to it, so the router can render the next route without waiting for a round trip. The [Prefetching guide](/docs/app/guides/prefetching) covers what the App Router prefetches by default. | ||
| With [Cache Components](/docs/app/getting-started/caching) and [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching), a [`<Link>`](/docs/app/api-reference/components/link) prefetches one reusable [**App Shell**](/docs/app/glossary#app-shell) per route by default. The App Shell includes the route's static output. For routes that read [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers), it also includes session-specific UI. Links to the same route reuse that App Shell. | ||
| The shared App Shell does not include URL data that varies by destination, such as [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) and [`params`](/docs/app/api-reference/file-conventions/page#params-optional). Set `prefetch={true}` on a link to resolve cached content that depends on its [URL data](/docs/app/glossary#url-data) before navigation instead of streaming that content after navigation. | ||
| This guide assumes [Cache Components](/docs/app/getting-started/caching) with [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) enabled: | ||
| ```ts filename="next.config.ts" highlight={4,5} | ||
| import type { NextConfig } from 'next' | ||
| const nextConfig: NextConfig = { | ||
| cacheComponents: true, | ||
| partialPrefetching: true, | ||
| } | ||
| export default nextConfig | ||
| ``` | ||
| It also assumes your route is already structured for instant navigation. If it isn't, start with the [Instant navigation guide](/docs/app/guides/instant-navigation) to validate its caching structure first. | ||
| ## Resolve URL data at prefetch time | ||
| Set `<Link prefetch={true}>` to resolve URL data for that link before navigation. The destination must use [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching), enabled globally with `partialPrefetching` or per segment with [`prefetch = 'partial'`](/docs/app/api-reference/file-conventions/route-segment-config/prefetch#partial). | ||
| A user on `/` sees links to `/search?q=react` and `/search?q=next`, each opting in with `prefetch={true}`: | ||
| ```tsx filename="app/page.tsx" | ||
| import Link from 'next/link' | ||
| export default function Home() { | ||
| return ( | ||
| <nav> | ||
| <Link href="/search?q=react" prefetch={true}> | ||
| React | ||
| </Link> | ||
| <Link href="/search?q=next" prefetch={true}> | ||
| Next.js | ||
| </Link> | ||
| </nav> | ||
| ) | ||
| } | ||
| ``` | ||
| The destination renders a static heading and a `<Results>` list whose contents depend on the query. Each query is cached, computed once and reused. | ||
| ```tsx filename="app/search/page.tsx" | ||
| import { Suspense } from 'react' | ||
| export default function SearchPage({ searchParams }: PageProps<'/search'>) { | ||
| return ( | ||
| <> | ||
| <h1>Search</h1> | ||
| <Suspense fallback={<ResultsSkeleton />}> | ||
| <Results searchParams={searchParams} /> | ||
| </Suspense> | ||
| </> | ||
| ) | ||
| } | ||
| async function Results({ | ||
| searchParams, | ||
| }: { | ||
| searchParams: PageProps<'/search'>['searchParams'] | ||
| }) { | ||
| const { q } = await searchParams | ||
| return <ResultList items={await search(q)} /> | ||
| } | ||
| async function search(q: string) { | ||
| 'use cache' | ||
| return db.search(q) | ||
| } | ||
| ``` | ||
| Without `prefetch={true}`, the App Shell renders `<h1>` and shows the `<Results>` fallback. The query resolves after the click and streams the results in. | ||
| With `prefetch={true}` on the link, the router prefetches a prerender that resolves `<Results>` before the click. The `q` value comes from the link's URL, known at prefetch time, and the cached `search(q)` provides the result. On the click, the results render immediately, with no fallback. | ||
| The prerender advances through anything static or cached, then stops at uncached reads and falls back to the surrounding `<Suspense>` boundary. That boundary is already in place from [structuring the route for instant navigation](/docs/app/guides/instant-navigation). | ||
| Generating the per-link prefetch costs **a server invocation per prefetchable link**, so it is opt-in per link. On pages where all the content is statically renderable, Next.js serves the prefetch from the static cache instead. A page that accesses non-static data is generated per prefetch. | ||
| > **Good to know:** A cold cache (first visit, or after expiration) means the server still has to compute the cached result. Users may see a loading spinner on that first navigation. Subsequent navigations are instant as long as the cache is warm. | ||
| Like `searchParams`, `params` needs a `<Suspense>` boundary, even when the values are predefined by [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params). A statically known param still belongs to one URL. A per-link prefetch with `prefetch={true}` resolves the values `generateStaticParams` does not cover. | ||
| ## Include session data in the shell | ||
| `prefetch={true}` resolves URL data. Session data is handled separately. A route that reads `cookies()` or `headers()`, including through `"use cache: private"`, gets an App Shell that includes its session data, cached per session on the client and ready on navigation without a per-link prefetch. | ||
| A lookup based on session data needs a cache lifetime, the same way `search(q)` did for the URL. Take a dashboard nav that reads a cookie, then looks up content based on it: | ||
| ```tsx filename="app/dashboard/layout.tsx" | ||
| import { Suspense } from 'react' | ||
| export default function DashboardLayout({ | ||
| children, | ||
| }: LayoutProps<'/dashboard'>) { | ||
| return ( | ||
| <div> | ||
| <Suspense fallback={<nav>Loading...</nav>}> | ||
| <UserNav /> | ||
| </Suspense> | ||
| <main>{children}</main> | ||
| </div> | ||
| ) | ||
| } | ||
| ``` | ||
| The cookie itself is session data the App Shell already knows. But `"use cache"` can't read `cookies()` inside the cached function, so two patterns bridge it: | ||
| - **Extract and pass** when the lookup result is shared across many sessions. | ||
| - **`"use cache: private"`** when it is tied to one. | ||
| ### Extract and pass | ||
| Read the cookie outside the cached function and pass the value in as an argument. The `cookies()` call stays outside the cache scope, the argument crosses the boundary, and the cached function has a deterministic signature. The cache entry is keyed on that argument, and sessions that share the value share the entry. | ||
| ```tsx filename="app/dashboard/user-nav.tsx" | ||
| import { cookies } from 'next/headers' | ||
| async function UserNav() { | ||
| const team = (await cookies()).get('team')?.value | ||
| const topics = await getTopics(team) | ||
| return ( | ||
| <nav> | ||
| {topics.map((topic) => ( | ||
| <a key={topic.id} href={topic.href}> | ||
| {topic.label} | ||
| </a> | ||
| ))} | ||
| </nav> | ||
| ) | ||
| } | ||
| async function getTopics(team: string | undefined) { | ||
| 'use cache' | ||
| return db.topics.forTeam(team) | ||
| } | ||
| ``` | ||
| On a direct visit, `<UserNav>` shows its fallback until the lookup resolves. On navigation, the App Shell has already resolved it, because the team cookie is session data the shell can read. Because sessions on the same team share the cache entry, traffic to the underlying data scales with team count, not session count. | ||
| Anything without a caching directive still streams in after navigation. A shell holds only what can be prepared ahead of the navigation, not the whole page. It advances only as far as the caching structure allows. | ||
| ### `"use cache: private"` | ||
| When the lookup is tied to a single session, use [`"use cache: private"`](/docs/app/api-reference/directives/use-cache-private). It assigns a cache lifetime to a function that reads cookies, headers, or other runtime data directly. Results are cached in the browser only, scoped to that session. | ||
| ```tsx filename="app/dashboard/user-nav.tsx" | ||
| import { cookies } from 'next/headers' | ||
| async function UserNav() { | ||
| const user = await getUser() | ||
| return <nav>{user.name}</nav> | ||
| } | ||
| async function getUser() { | ||
| 'use cache: private' | ||
| const session = (await cookies()).get('session')?.value | ||
| return db.users.findBySession(session) | ||
| } | ||
| ``` | ||
| Here `cookies()` lives inside the cached function, which only works under `"use cache: private"`. This is also the pattern when you can't extract the runtime data from the outside: auth helpers that check `Date.now()` against a token's expiry, or session helpers that read cookies deep inside their own code, can't be wrapped at the call site. | ||
| Everything inside the scope shares the same lifetime. Colocate `"use cache: private"` as close to the runtime data access as possible. | ||
| {/* TODO(optimizing-prefetching): add an "Exclude content until navigation" section once `await navigation()` (ships as `unstable_navigation`, vercel/next.js#96069) merges. This is the second direction, gating content OUT of the prefetch rather than resolving URL data into it: the prefetch stops at `await navigation()` (code after it does not run at prefetch time), and on the actual navigation (or build/ISR) it runs and streams in. Unlike `await connection()`, content below the gate stays cacheable. It can't be called inside `use cache` / `use cache: private` yet, so the pattern is `await navigation()` in an uncached wrapper with the cache directive on an inner function below the gate. Do NOT publish until merged; validate empirically against the PR branch first. */} | ||
| ## Trade-offs | ||
| Use `prefetch={true}` on routes where: | ||
| - Part of the component tree depends on URL data: the full URL, `searchParams`, or `params` not resolved by [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) | ||
| - That part of the tree has a known cache lifetime (it can be expressed with `"use cache"` or `"use cache: private"`) | ||
| - The traffic justifies the per-link server invocation | ||
| Skip it when the prefetch can't produce a better UI than the App Shell. Each visible `<Link prefetch={true}>` can wake a server, and that cost only pays off if more of the page is ready before the click: | ||
| - The route has little or no URL-data dependency. The App Shell already makes the navigation instant. | ||
| - The dependent content has to be fresh on every request. The prerender stops at the same `<Suspense>` fallback, so the user sees the same UI either way. | ||
| - The route is rarely navigated to. You pay per visible link, regardless of click-through. | ||
| A per-link prefetch is best-effort. It only helps the navigations where it completes before the click. On a slow connection, on a feed of many links, or on a direct visit, it may not be ready when the user navigates, and the navigation falls back to the App Shell. | ||
| When many links to a route are visible at once, such as a grid of cards, each `<Link prefetch={true}>` prefetches that link's content as it enters the viewport, so the grid makes one such server request per card. Prefetch on intent instead. A [hover-triggered prefetch](/docs/app/guides/prefetching#hover-triggered-prefetch) fetches only the links the user is likely to click. The default `<Link>` (without `prefetch={true}`) prefetches only the App Shell, so it doesn't carry this cost. | ||
| | | App Shell | Per-link prefetch with `prefetch={true}` | | ||
| | ------- | ------------------------------------------- | ---------------------------------------- | | ||
| | Scope | One per route | One per visible `<Link prefetch={true}>` | | ||
| | Content | Route's rendered output minus per-link data | Same, plus per-link URL data resolved | | ||
| | Cost | Bounded by route count | Bounded by visible-link count | | ||
| | Role | Default prefetch | More rendered before click | | ||
| ## Next steps | ||
| - [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for how `<Link>` behaves under the new model and how to migrate existing apps. | ||
| - [`prefetch` API reference](/docs/app/api-reference/file-conventions/route-segment-config/prefetch) for all prefetch modes. | ||
| - [`use cache: private` reference](/docs/app/api-reference/directives/use-cache-private) for per-user caching specifics. | ||
| - [Instant navigation guide](/docs/app/guides/instant-navigation) for validating the route's caching structure. | ||
| - [Caching](/docs/app/getting-started/caching) for background on `use cache`, Suspense, and Partial Prerendering. |
| /** | ||
| * Percent-encode every character other than horizontal tab and printable ASCII | ||
| * so a value can be safely serialized into an HTTP header. | ||
| * | ||
| * Node's `validateHeaderValue` and `fetch`'s ByteString conversion accept | ||
| * different character ranges. Restricting values to `\t\x20-\x7e` produces a | ||
| * conservative representation that both can serialize. Characters outside a | ||
| * transport's accepted range (Hebrew, Arabic, Chinese, emoji, …) would | ||
| * otherwise throw `ERR_INVALID_CHAR` or a `TypeError`, which crashes ISR or | ||
| * fails a cache read on every affected request. | ||
| * | ||
| * Cache tags are encoded at the public boundaries — tag construction | ||
| * (`getImplicitTags`, `validateTags`) and invalidation input | ||
| * (`revalidatePath`, `revalidateTag`, `updateTag`) — so storage, comparison, | ||
| * and the wire all see the same canonical form. | ||
| * | ||
| * The class is narrower than either transport accepts. Everything inside it | ||
| * passes through byte-for-byte, including `,`, `/`, `%`, `[`, `]`, `_`, `-` and | ||
| * `\t`, which preserves the comma-separated header format and the | ||
| * dynamic-segment markers in derived tags (`_N_T_/[slug]/page`). | ||
| * | ||
| * Properties: | ||
| * - Fast-path: input that already fits the class is returned unchanged. This | ||
| * makes the encoder idempotent on already-encoded `%xx` sequences. | ||
| * - Matches *runs* of out-of-class code units so surrogate pairs (e.g. an | ||
| * emoji) are handed to `encodeURIComponent` as a complete code point — a | ||
| * per-code-unit regex would split the pair and throw `URIError`. | ||
| */ const OUT_OF_CLASS_CHAR = /[^\t\x20-\x7e]/; | ||
| const OUT_OF_CLASS_RUN = /[^\t\x20-\x7e]+/g; | ||
| export function encodeHeaderSafe(value) { | ||
| return OUT_OF_CLASS_CHAR.test(value) ? value.replace(OUT_OF_CLASS_RUN, (run)=>encodeURIComponent(run)) : value; | ||
| } | ||
| //# sourceMappingURL=encode-header-safe.js.map |
| {"version":3,"sources":["../../../../src/server/lib/encode-header-safe.ts"],"sourcesContent":["/**\n * Percent-encode every character other than horizontal tab and printable ASCII\n * so a value can be safely serialized into an HTTP header.\n *\n * Node's `validateHeaderValue` and `fetch`'s ByteString conversion accept\n * different character ranges. Restricting values to `\\t\\x20-\\x7e` produces a\n * conservative representation that both can serialize. Characters outside a\n * transport's accepted range (Hebrew, Arabic, Chinese, emoji, …) would\n * otherwise throw `ERR_INVALID_CHAR` or a `TypeError`, which crashes ISR or\n * fails a cache read on every affected request.\n *\n * Cache tags are encoded at the public boundaries — tag construction\n * (`getImplicitTags`, `validateTags`) and invalidation input\n * (`revalidatePath`, `revalidateTag`, `updateTag`) — so storage, comparison,\n * and the wire all see the same canonical form.\n *\n * The class is narrower than either transport accepts. Everything inside it\n * passes through byte-for-byte, including `,`, `/`, `%`, `[`, `]`, `_`, `-` and\n * `\\t`, which preserves the comma-separated header format and the\n * dynamic-segment markers in derived tags (`_N_T_/[slug]/page`).\n *\n * Properties:\n * - Fast-path: input that already fits the class is returned unchanged. This\n * makes the encoder idempotent on already-encoded `%xx` sequences.\n * - Matches *runs* of out-of-class code units so surrogate pairs (e.g. an\n * emoji) are handed to `encodeURIComponent` as a complete code point — a\n * per-code-unit regex would split the pair and throw `URIError`.\n */\nconst OUT_OF_CLASS_CHAR = /[^\\t\\x20-\\x7e]/\nconst OUT_OF_CLASS_RUN = /[^\\t\\x20-\\x7e]+/g\n\nexport function encodeHeaderSafe(value: string): string {\n return OUT_OF_CLASS_CHAR.test(value)\n ? value.replace(OUT_OF_CLASS_RUN, (run) => encodeURIComponent(run))\n : value\n}\n"],"names":["OUT_OF_CLASS_CHAR","OUT_OF_CLASS_RUN","encodeHeaderSafe","value","test","replace","run","encodeURIComponent"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,MAAMA,oBAAoB;AAC1B,MAAMC,mBAAmB;AAEzB,OAAO,SAASC,iBAAiBC,KAAa;IAC5C,OAAOH,kBAAkBI,IAAI,CAACD,SAC1BA,MAAME,OAAO,CAACJ,kBAAkB,CAACK,MAAQC,mBAAmBD,QAC5DH;AACN","ignoreList":[0]} |
| export declare function encodeHeaderSafe(value: string): string; |
| /** | ||
| * Percent-encode every character other than horizontal tab and printable ASCII | ||
| * so a value can be safely serialized into an HTTP header. | ||
| * | ||
| * Node's `validateHeaderValue` and `fetch`'s ByteString conversion accept | ||
| * different character ranges. Restricting values to `\t\x20-\x7e` produces a | ||
| * conservative representation that both can serialize. Characters outside a | ||
| * transport's accepted range (Hebrew, Arabic, Chinese, emoji, …) would | ||
| * otherwise throw `ERR_INVALID_CHAR` or a `TypeError`, which crashes ISR or | ||
| * fails a cache read on every affected request. | ||
| * | ||
| * Cache tags are encoded at the public boundaries — tag construction | ||
| * (`getImplicitTags`, `validateTags`) and invalidation input | ||
| * (`revalidatePath`, `revalidateTag`, `updateTag`) — so storage, comparison, | ||
| * and the wire all see the same canonical form. | ||
| * | ||
| * The class is narrower than either transport accepts. Everything inside it | ||
| * passes through byte-for-byte, including `,`, `/`, `%`, `[`, `]`, `_`, `-` and | ||
| * `\t`, which preserves the comma-separated header format and the | ||
| * dynamic-segment markers in derived tags (`_N_T_/[slug]/page`). | ||
| * | ||
| * Properties: | ||
| * - Fast-path: input that already fits the class is returned unchanged. This | ||
| * makes the encoder idempotent on already-encoded `%xx` sequences. | ||
| * - Matches *runs* of out-of-class code units so surrogate pairs (e.g. an | ||
| * emoji) are handed to `encodeURIComponent` as a complete code point — a | ||
| * per-code-unit regex would split the pair and throw `URIError`. | ||
| */ "use strict"; | ||
| Object.defineProperty(exports, "__esModule", { | ||
| value: true | ||
| }); | ||
| Object.defineProperty(exports, "encodeHeaderSafe", { | ||
| enumerable: true, | ||
| get: function() { | ||
| return encodeHeaderSafe; | ||
| } | ||
| }); | ||
| const OUT_OF_CLASS_CHAR = /[^\t\x20-\x7e]/; | ||
| const OUT_OF_CLASS_RUN = /[^\t\x20-\x7e]+/g; | ||
| function encodeHeaderSafe(value) { | ||
| return OUT_OF_CLASS_CHAR.test(value) ? value.replace(OUT_OF_CLASS_RUN, (run)=>encodeURIComponent(run)) : value; | ||
| } | ||
| //# sourceMappingURL=encode-header-safe.js.map |
| {"version":3,"sources":["../../../src/server/lib/encode-header-safe.ts"],"sourcesContent":["/**\n * Percent-encode every character other than horizontal tab and printable ASCII\n * so a value can be safely serialized into an HTTP header.\n *\n * Node's `validateHeaderValue` and `fetch`'s ByteString conversion accept\n * different character ranges. Restricting values to `\\t\\x20-\\x7e` produces a\n * conservative representation that both can serialize. Characters outside a\n * transport's accepted range (Hebrew, Arabic, Chinese, emoji, …) would\n * otherwise throw `ERR_INVALID_CHAR` or a `TypeError`, which crashes ISR or\n * fails a cache read on every affected request.\n *\n * Cache tags are encoded at the public boundaries — tag construction\n * (`getImplicitTags`, `validateTags`) and invalidation input\n * (`revalidatePath`, `revalidateTag`, `updateTag`) — so storage, comparison,\n * and the wire all see the same canonical form.\n *\n * The class is narrower than either transport accepts. Everything inside it\n * passes through byte-for-byte, including `,`, `/`, `%`, `[`, `]`, `_`, `-` and\n * `\\t`, which preserves the comma-separated header format and the\n * dynamic-segment markers in derived tags (`_N_T_/[slug]/page`).\n *\n * Properties:\n * - Fast-path: input that already fits the class is returned unchanged. This\n * makes the encoder idempotent on already-encoded `%xx` sequences.\n * - Matches *runs* of out-of-class code units so surrogate pairs (e.g. an\n * emoji) are handed to `encodeURIComponent` as a complete code point — a\n * per-code-unit regex would split the pair and throw `URIError`.\n */\nconst OUT_OF_CLASS_CHAR = /[^\\t\\x20-\\x7e]/\nconst OUT_OF_CLASS_RUN = /[^\\t\\x20-\\x7e]+/g\n\nexport function encodeHeaderSafe(value: string): string {\n return OUT_OF_CLASS_CHAR.test(value)\n ? value.replace(OUT_OF_CLASS_RUN, (run) => encodeURIComponent(run))\n : value\n}\n"],"names":["encodeHeaderSafe","OUT_OF_CLASS_CHAR","OUT_OF_CLASS_RUN","value","test","replace","run","encodeURIComponent"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC;;;;+BAIeA;;;eAAAA;;;AAHhB,MAAMC,oBAAoB;AAC1B,MAAMC,mBAAmB;AAElB,SAASF,iBAAiBG,KAAa;IAC5C,OAAOF,kBAAkBG,IAAI,CAACD,SAC1BA,MAAME,OAAO,CAACH,kBAAkB,CAACI,MAAQC,mBAAmBD,QAC5DH;AACN","ignoreList":[0]} |
@@ -142,3 +142,3 @@ "use strict"; | ||
| }({}); | ||
| const nextVersion = "16.3.1-canary.10"; | ||
| const nextVersion = "16.3.1-canary.11"; | ||
| const ArchName = (0, _os.arch)(); | ||
@@ -145,0 +145,0 @@ const PlatformName = (0, _os.platform)(); |
@@ -164,3 +164,2 @@ "use strict"; | ||
| enableTainting: nextConfig.experimental.taint, | ||
| htmlLimitedBots: nextConfig.htmlLimitedBots, | ||
| reactMaxHeadersLength: nextConfig.reactMaxHeadersLength, | ||
@@ -167,0 +166,0 @@ multiZoneDraftMode: false, |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/build/templates/edge-ssr-app.ts"],"sourcesContent":["import '../../server/web/globals'\nimport {\n adapter,\n type EdgeHandler,\n type NextRequestHint,\n} from '../../server/web/adapter'\nimport { IncrementalCache } from '../../server/lib/incremental-cache'\n\nimport * as pageMod from 'VAR_USERLAND'\n\nimport { setManifestsSingleton } from '../../server/app-render/manifests-singleton'\nimport * as cacheHandlers from '../../server/use-cache/handlers'\nimport { BaseServerSpan } from '../../server/lib/trace/constants'\nimport {\n getTracer,\n SpanKind,\n SpanStatusCode,\n type Span,\n} from '../../server/lib/trace/tracer'\nimport { WebNextRequest, WebNextResponse } from '../../server/base-http/web'\nimport type { NextFetchEvent } from '../../server/web/spec-extension/fetch-event'\nimport type {\n AppPageRouteHandlerContext,\n AppPageRouteModule,\n} from '../../server/route-modules/app-page/module.compiled'\nimport type { AppPageRenderResultMetadata } from '../../server/render-result'\nimport type RenderResult from '../../server/render-result'\nimport { getIsPossibleServerAction } from '../../server/lib/server-action-request-meta'\nimport { getBotType } from '../../shared/lib/router/utils/is-bot'\nimport { interopDefault } from '../../lib/interop-default'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport { checkIsOnDemandRevalidate } from '../../server/api-utils'\nimport { CloseController } from '../../server/web/web-on-close'\nimport { parseMaxPostponedStateSize } from '../../shared/lib/size-limit'\nimport { toNodeOutgoingHttpHeaders } from '../../server/web/utils'\nimport type { RequestMeta } from '../../server/request-meta'\n\ndeclare const incrementalCacheHandler: any\n// OPTIONAL_IMPORT:incrementalCacheHandler\n// INJECT_RAW:cacheHandlerImports\n\nconst maybeJSONParse = (str?: string) => (str ? JSON.parse(str) : undefined)\n\nconst rscManifest = self.__RSC_MANIFEST?.['VAR_PAGE']\nconst rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST)\n\nif (rscManifest && rscServerManifest) {\n setManifestsSingleton({\n page: 'VAR_PAGE',\n clientReferenceManifest: rscManifest,\n serverActionsManifest: rscServerManifest,\n })\n}\n\nexport const ComponentMod = pageMod\n\nasync function requestHandler(\n req: NextRequestHint,\n event: NextFetchEvent\n): Promise<Response> {\n let srcPage = 'VAR_PAGE'\n\n const normalizedSrcPage = normalizeAppPath(srcPage)\n const relativeUrl = `${req.nextUrl.pathname}${req.nextUrl.search}`\n const baseReq = new WebNextRequest(req)\n const baseRes = new WebNextResponse(undefined)\n\n const pageRouteModule = pageMod.routeModule as AppPageRouteModule\n const prepareResult = await pageRouteModule.prepare(baseReq, null, {\n srcPage,\n multiZoneDraftMode: false,\n })\n\n if (!prepareResult) {\n return new Response('Bad Request', {\n status: 400,\n })\n }\n const {\n query,\n params,\n buildId,\n nextConfig,\n buildManifest,\n prerenderManifest,\n reactLoadableManifest,\n subresourceIntegrityManifest,\n dynamicCssManifest,\n nextFontManifest,\n resolvedPathname,\n interceptionRoutePatterns,\n routerServerContext,\n deploymentId,\n clientAssetToken,\n } = prepareResult\n\n // Initialize the cache handlers interface.\n cacheHandlers.initializeCacheHandlers(nextConfig.cacheMaxMemorySize)\n // INJECT_RAW:cacheHandlerRegistration\n\n const isPossibleServerAction = getIsPossibleServerAction(req)\n const botType = getBotType(req.headers.get('User-Agent') || '')\n const { isOnDemandRevalidate } = checkIsOnDemandRevalidate(\n req.headers,\n prerenderManifest.preview\n )\n\n const closeController = new CloseController()\n\n const renderContext: AppPageRouteHandlerContext = {\n page: normalizedSrcPage,\n query,\n params,\n\n sharedContext: {\n buildId,\n deploymentId,\n clientAssetToken,\n },\n fallbackRouteParams: null,\n\n renderOpts: {\n App: () => null,\n Document: () => null,\n pageConfig: {},\n ComponentMod,\n Component: interopDefault(ComponentMod),\n routeModule: pageRouteModule,\n\n params,\n page: srcPage,\n postponed: undefined,\n serveStreamingMetadata: true,\n supportsDynamicResponse: true,\n buildManifest,\n nextFontManifest,\n reactLoadableManifest,\n subresourceIntegrityManifest,\n dynamicCssManifest,\n setIsrStatus: routerServerContext?.setIsrStatus,\n\n dir: pageRouteModule.relativeProjectDir,\n botType,\n isDraftMode: false,\n isOnDemandRevalidate,\n isPossibleServerAction,\n assetPrefix: nextConfig.assetPrefix,\n nextConfigOutput: nextConfig.output,\n crossOrigin: nextConfig.crossOrigin,\n trailingSlash: nextConfig.trailingSlash,\n images: nextConfig.images,\n previewProps: prerenderManifest.preview,\n enableTainting: nextConfig.experimental.taint,\n htmlLimitedBots: nextConfig.htmlLimitedBots,\n reactMaxHeadersLength: nextConfig.reactMaxHeadersLength,\n\n multiZoneDraftMode: false,\n cacheLifeProfiles: nextConfig.cacheLife,\n staticPageGenerationTimeout: nextConfig.staticPageGenerationTimeout,\n basePath: nextConfig.basePath,\n serverActions: nextConfig.experimental.serverActions,\n logServerFunctions:\n typeof nextConfig.logging === 'object' &&\n Boolean(nextConfig.logging.serverFunctions),\n cacheComponents: Boolean(nextConfig.cacheComponents),\n validationLevel: nextConfig.experimental.instantInsights.validationLevel,\n experimental: {\n isRoutePPREnabled: false,\n expireTime: nextConfig.expireTime,\n staleTimes: nextConfig.experimental.staleTimes,\n dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover),\n optimisticRouting: Boolean(nextConfig.experimental.optimisticRouting),\n inlineCss: Boolean(nextConfig.experimental.inlineCss),\n prefetchInlining: nextConfig.experimental.prefetchInlining ?? false,\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts),\n // Edge has no Node response-close signal, so HMR cancellation is a\n // no-op.\n serverComponentsHmrCancellation: false,\n useCacheTimeout: nextConfig.experimental.useCacheTimeout,\n cachedNavigations: nextConfig.experimental.cachedNavigations ?? false,\n clientTraceMetadata:\n nextConfig.experimental.clientTraceMetadata || ([] as any),\n clientParamParsingOrigins:\n nextConfig.experimental.clientParamParsingOrigins,\n maxPostponedStateSizeBytes: parseMaxPostponedStateSize(\n nextConfig.experimental.maxPostponedStateSize\n ),\n exposeTestingApi:\n nextConfig.cacheComponents === true &&\n (pageRouteModule.isDev === true ||\n nextConfig.experimental.exposeTestingApiInProductionBuild === true),\n },\n\n incrementalCache: await pageRouteModule.getIncrementalCache(\n baseReq,\n nextConfig,\n prerenderManifest,\n true\n ),\n\n waitUntil: event.waitUntil.bind(event),\n onClose: (cb) => {\n closeController.onClose(cb)\n },\n onAfterTaskError: () => {},\n\n onInstrumentationRequestError: (\n error,\n _request,\n errorContext,\n silenceLog\n ) =>\n pageRouteModule.onRequestError(\n baseReq,\n error,\n errorContext,\n silenceLog,\n routerServerContext\n ),\n },\n }\n let finalStatus = 200\n\n const renderResultToResponse = (\n result: RenderResult<AppPageRenderResultMetadata>\n ): Response => {\n const varyHeader = pageRouteModule.getVaryHeader(\n resolvedPathname,\n interceptionRoutePatterns\n )\n // Handle null responses\n if (result.isNull) {\n finalStatus = 500\n closeController.dispatchClose()\n return new Response(null, { status: 500 })\n }\n\n // Extract metadata\n const { metadata } = result\n const headers = new Headers()\n finalStatus = metadata.statusCode || baseRes.statusCode || 200\n // Pull any fetch metrics from the render onto the request.\n ;(req as any).fetchMetrics = metadata.fetchMetrics\n\n // Set content type\n const contentType = result.contentType || 'text/html; charset=utf-8'\n headers.set('Content-Type', contentType)\n headers.set('x-edge-runtime', '1')\n\n if (varyHeader) {\n headers.set('Vary', varyHeader)\n }\n\n // Add existing headers\n for (const [key, value] of Object.entries({\n ...baseRes.getHeaders(),\n ...metadata.headers,\n })) {\n if (value !== undefined) {\n if (Array.isArray(value)) {\n // Handle multiple header values\n for (const v of value) {\n headers.append(key, String(v))\n }\n } else {\n headers.set(key, String(value))\n }\n }\n }\n\n // Handle static response\n if (!result.isDynamic) {\n const body = result.toUnchunkedString()\n headers.set(\n 'Content-Length',\n String(new TextEncoder().encode(body).length)\n )\n closeController.dispatchClose()\n return new Response(body, {\n status: finalStatus,\n headers,\n })\n }\n\n // Handle dynamic/streaming response\n // For edge runtime, we need to create a readable stream that pipes from the result\n const { readable, writable } = new TransformStream()\n\n // Start piping the result to the writable stream\n // This is done asynchronously to avoid blocking the response creation\n result\n .pipeTo(writable)\n .catch((err: unknown) => {\n console.error('Error piping RenderResult to response:', err)\n })\n .finally(() => closeController.dispatchClose())\n\n return new Response(readable, {\n status: finalStatus,\n headers,\n })\n }\n\n const invokeRender = async (span?: Span): Promise<Response> => {\n try {\n const result = await pageRouteModule\n .render(baseReq, baseRes, renderContext)\n .finally(() => {\n if (!span) return\n\n span.setAttributes({\n 'http.status_code': finalStatus,\n 'next.rsc': false,\n })\n\n if (finalStatus && finalStatus >= 500) {\n // For 5xx status codes: SHOULD be set to 'Error' span status.\n // x-ref: https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status\n span.setStatus({\n code: SpanStatusCode.ERROR,\n })\n // For span status 'Error', SHOULD set 'error.type' attribute.\n span.setAttribute('error.type', finalStatus.toString())\n }\n\n const rootSpanAttributes = tracer.getRootSpanAttributes()\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return\n }\n\n if (\n rootSpanAttributes.get('next.span_type') !==\n BaseServerSpan.handleRequest\n ) {\n console.warn(\n `Unexpected root span type '${rootSpanAttributes.get(\n 'next.span_type'\n )}'. Please report this Next.js issue https://github.com/vercel/next.js`\n )\n return\n }\n\n const route = normalizedSrcPage\n if (route) {\n const name = `${req.method} ${route}`\n\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name,\n })\n span.updateName(name)\n } else {\n span.updateName(`${req.method} ${srcPage}`)\n }\n })\n\n return renderResultToResponse(result)\n } catch (err) {\n const silenceLog = false\n await pageRouteModule.onRequestError(\n baseReq,\n err,\n {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'render',\n revalidateReason: undefined,\n },\n silenceLog\n )\n // rethrow so that we can handle serving error page\n throw err\n }\n }\n\n const tracer = getTracer()\n\n return tracer.withPropagatedContext(req.headers, () =>\n tracer.trace(\n BaseServerSpan.handleRequest,\n {\n spanName: `${req.method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': req.method,\n 'http.target': relativeUrl,\n 'http.route': normalizedSrcPage,\n },\n },\n invokeRender\n )\n )\n}\n\nconst internalHandler: EdgeHandler = (opts) => {\n return adapter({\n ...opts,\n IncrementalCache,\n handler: requestHandler,\n incrementalCacheHandler,\n page: 'VAR_PAGE',\n })\n}\n\nexport async function handler(\n request: Request,\n ctx: {\n waitUntil?: (prom: Promise<void>) => void\n signal?: AbortSignal\n requestMeta?: RequestMeta\n }\n): Promise<Response> {\n const result = await internalHandler({\n request: {\n url: request.url,\n method: request.method,\n headers: toNodeOutgoingHttpHeaders(request.headers),\n nextConfig: {\n basePath: process.env.__NEXT_BASE_PATH,\n i18n: process.env.__NEXT_I18N_CONFIG as any,\n trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),\n experimental: {\n cacheLife: process.env.__NEXT_CACHE_LIFE as any,\n authInterrupts: Boolean(\n process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS\n ),\n clientParamParsingOrigins: process.env\n .__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any,\n },\n },\n page: {\n name: 'VAR_PAGE',\n },\n body:\n request.method !== 'GET' && request.method !== 'HEAD'\n ? (request.body ?? undefined)\n : undefined,\n waitUntil: ctx.waitUntil,\n requestMeta: ctx.requestMeta,\n signal: ctx.signal || new AbortController().signal,\n },\n })\n\n ctx.waitUntil?.(result.waitUntil)\n\n return result.response\n}\n\n// backwards compat\nexport default internalHandler\n"],"names":["ComponentMod","handler","self","maybeJSONParse","str","JSON","parse","undefined","rscManifest","__RSC_MANIFEST","rscServerManifest","__RSC_SERVER_MANIFEST","setManifestsSingleton","page","clientReferenceManifest","serverActionsManifest","pageMod","requestHandler","req","event","srcPage","normalizedSrcPage","normalizeAppPath","relativeUrl","nextUrl","pathname","search","baseReq","WebNextRequest","baseRes","WebNextResponse","pageRouteModule","routeModule","prepareResult","prepare","multiZoneDraftMode","Response","status","query","params","buildId","nextConfig","buildManifest","prerenderManifest","reactLoadableManifest","subresourceIntegrityManifest","dynamicCssManifest","nextFontManifest","resolvedPathname","interceptionRoutePatterns","routerServerContext","deploymentId","clientAssetToken","cacheHandlers","initializeCacheHandlers","cacheMaxMemorySize","isPossibleServerAction","getIsPossibleServerAction","botType","getBotType","headers","get","isOnDemandRevalidate","checkIsOnDemandRevalidate","preview","closeController","CloseController","renderContext","sharedContext","fallbackRouteParams","renderOpts","App","Document","pageConfig","Component","interopDefault","postponed","serveStreamingMetadata","supportsDynamicResponse","setIsrStatus","dir","relativeProjectDir","isDraftMode","assetPrefix","nextConfigOutput","output","crossOrigin","trailingSlash","images","previewProps","enableTainting","experimental","taint","htmlLimitedBots","reactMaxHeadersLength","cacheLifeProfiles","cacheLife","staticPageGenerationTimeout","basePath","serverActions","logServerFunctions","logging","Boolean","serverFunctions","cacheComponents","validationLevel","instantInsights","isRoutePPREnabled","expireTime","staleTimes","dynamicOnHover","optimisticRouting","inlineCss","prefetchInlining","authInterrupts","serverComponentsHmrCancellation","useCacheTimeout","cachedNavigations","clientTraceMetadata","clientParamParsingOrigins","maxPostponedStateSizeBytes","parseMaxPostponedStateSize","maxPostponedStateSize","exposeTestingApi","isDev","exposeTestingApiInProductionBuild","incrementalCache","getIncrementalCache","waitUntil","bind","onClose","cb","onAfterTaskError","onInstrumentationRequestError","error","_request","errorContext","silenceLog","onRequestError","finalStatus","renderResultToResponse","result","varyHeader","getVaryHeader","isNull","dispatchClose","metadata","Headers","statusCode","fetchMetrics","contentType","set","key","value","Object","entries","getHeaders","Array","isArray","v","append","String","isDynamic","body","toUnchunkedString","TextEncoder","encode","length","readable","writable","TransformStream","pipeTo","catch","err","console","finally","invokeRender","span","render","setAttributes","setStatus","code","SpanStatusCode","ERROR","setAttribute","toString","rootSpanAttributes","tracer","getRootSpanAttributes","BaseServerSpan","handleRequest","warn","route","name","method","updateName","routerKind","routePath","routeType","revalidateReason","getTracer","withPropagatedContext","trace","spanName","kind","SpanKind","SERVER","attributes","internalHandler","opts","adapter","IncrementalCache","incrementalCacheHandler","request","ctx","url","toNodeOutgoingHttpHeaders","process","env","__NEXT_BASE_PATH","i18n","__NEXT_I18N_CONFIG","__NEXT_TRAILING_SLASH","__NEXT_CACHE_LIFE","__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS","__NEXT_CLIENT_PARAM_PARSING_ORIGINS","requestMeta","signal","AbortController","response"],"mappings":";;;;;;;;;;;;;;;;IAsDaA,YAAY;eAAZA;;IA4Yb,mBAAmB;IACnB,OAA8B;eAA9B;;IA7CsBC,OAAO;eAAPA;;;QAtZf;yBAKA;kCAC0B;sEAER;oCAEa;kEACP;2BACA;wBAMxB;qBAC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EAACH,QAAQzJ,OAAO;YAClDnB,YAAY;gBACVyD,UAAUuH,QAAQC,GAAG,CAACC,gBAAgB;gBACtCC,MAAMH,QAAQC,GAAG,CAACG,kBAAkB;gBACpCtI,eAAee,QAAQmH,QAAQC,GAAG,CAACI,qBAAqB;gBACxDnI,cAAc;oBACZK,WAAWyH,QAAQC,GAAG,CAACK,iBAAiB;oBACxC7G,gBAAgBZ,QACdmH,QAAQC,GAAG,CAACM,mCAAmC;oBAEjDzG,2BAA2BkG,QAAQC,GAAG,CACnCO,mCAAmC;gBACxC;YACF;YACApN,MAAM;gBACJoL,MAAM;YACR;YACA9B,MACEkD,QAAQnB,MAAM,KAAK,SAASmB,QAAQnB,MAAM,KAAK,SAC1CmB,QAAQlD,IAAI,IAAI5J,YACjBA;YACNyH,WAAWsF,IAAItF,SAAS;YACxBkG,aAAaZ,IAAIY,WAAW;YAC5BC,QAAQb,IAAIa,MAAM,IAAI,IAAIC,kBAAkBD,MAAM;QACpD;IACF;IAEAb,IAAItF,SAAS,oBAAbsF,IAAItF,SAAS,MAAbsF,KAAgBzE,OAAOb,SAAS;IAEhC,OAAOa,OAAOwF,QAAQ;AACxB;MAGA,WAAerB","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/build/templates/edge-ssr-app.ts"],"sourcesContent":["import '../../server/web/globals'\nimport {\n adapter,\n type EdgeHandler,\n type NextRequestHint,\n} from '../../server/web/adapter'\nimport { IncrementalCache } from '../../server/lib/incremental-cache'\n\nimport * as pageMod from 'VAR_USERLAND'\n\nimport { setManifestsSingleton } from '../../server/app-render/manifests-singleton'\nimport * as cacheHandlers from '../../server/use-cache/handlers'\nimport { BaseServerSpan } from '../../server/lib/trace/constants'\nimport {\n getTracer,\n SpanKind,\n SpanStatusCode,\n type Span,\n} from '../../server/lib/trace/tracer'\nimport { WebNextRequest, WebNextResponse } from '../../server/base-http/web'\nimport type { NextFetchEvent } from '../../server/web/spec-extension/fetch-event'\nimport type {\n AppPageRouteHandlerContext,\n AppPageRouteModule,\n} from '../../server/route-modules/app-page/module.compiled'\nimport type { AppPageRenderResultMetadata } from '../../server/render-result'\nimport type RenderResult from '../../server/render-result'\nimport { getIsPossibleServerAction } from '../../server/lib/server-action-request-meta'\nimport { getBotType } from '../../shared/lib/router/utils/is-bot'\nimport { interopDefault } from '../../lib/interop-default'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport { checkIsOnDemandRevalidate } from '../../server/api-utils'\nimport { CloseController } from '../../server/web/web-on-close'\nimport { parseMaxPostponedStateSize } from '../../shared/lib/size-limit'\nimport { toNodeOutgoingHttpHeaders } from '../../server/web/utils'\nimport type { RequestMeta } from '../../server/request-meta'\n\ndeclare const incrementalCacheHandler: any\n// OPTIONAL_IMPORT:incrementalCacheHandler\n// INJECT_RAW:cacheHandlerImports\n\nconst maybeJSONParse = (str?: string) => (str ? JSON.parse(str) : undefined)\n\nconst rscManifest = self.__RSC_MANIFEST?.['VAR_PAGE']\nconst rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST)\n\nif (rscManifest && rscServerManifest) {\n setManifestsSingleton({\n page: 'VAR_PAGE',\n clientReferenceManifest: rscManifest,\n serverActionsManifest: rscServerManifest,\n })\n}\n\nexport const ComponentMod = pageMod\n\nasync function requestHandler(\n req: NextRequestHint,\n event: NextFetchEvent\n): Promise<Response> {\n let srcPage = 'VAR_PAGE'\n\n const normalizedSrcPage = normalizeAppPath(srcPage)\n const relativeUrl = `${req.nextUrl.pathname}${req.nextUrl.search}`\n const baseReq = new WebNextRequest(req)\n const baseRes = new WebNextResponse(undefined)\n\n const pageRouteModule = pageMod.routeModule as AppPageRouteModule\n const prepareResult = await pageRouteModule.prepare(baseReq, null, {\n srcPage,\n multiZoneDraftMode: false,\n })\n\n if (!prepareResult) {\n return new Response('Bad Request', {\n status: 400,\n })\n }\n const {\n query,\n params,\n buildId,\n nextConfig,\n buildManifest,\n prerenderManifest,\n reactLoadableManifest,\n subresourceIntegrityManifest,\n dynamicCssManifest,\n nextFontManifest,\n resolvedPathname,\n interceptionRoutePatterns,\n routerServerContext,\n deploymentId,\n clientAssetToken,\n } = prepareResult\n\n // Initialize the cache handlers interface.\n cacheHandlers.initializeCacheHandlers(nextConfig.cacheMaxMemorySize)\n // INJECT_RAW:cacheHandlerRegistration\n\n const isPossibleServerAction = getIsPossibleServerAction(req)\n const botType = getBotType(req.headers.get('User-Agent') || '')\n const { isOnDemandRevalidate } = checkIsOnDemandRevalidate(\n req.headers,\n prerenderManifest.preview\n )\n\n const closeController = new CloseController()\n\n const renderContext: AppPageRouteHandlerContext = {\n page: normalizedSrcPage,\n query,\n params,\n\n sharedContext: {\n buildId,\n deploymentId,\n clientAssetToken,\n },\n fallbackRouteParams: null,\n\n renderOpts: {\n App: () => null,\n Document: () => null,\n pageConfig: {},\n ComponentMod,\n Component: interopDefault(ComponentMod),\n routeModule: pageRouteModule,\n\n params,\n page: srcPage,\n postponed: undefined,\n serveStreamingMetadata: true,\n supportsDynamicResponse: true,\n buildManifest,\n nextFontManifest,\n reactLoadableManifest,\n subresourceIntegrityManifest,\n dynamicCssManifest,\n setIsrStatus: routerServerContext?.setIsrStatus,\n\n dir: pageRouteModule.relativeProjectDir,\n botType,\n isDraftMode: false,\n isOnDemandRevalidate,\n isPossibleServerAction,\n assetPrefix: nextConfig.assetPrefix,\n nextConfigOutput: nextConfig.output,\n crossOrigin: nextConfig.crossOrigin,\n trailingSlash: nextConfig.trailingSlash,\n images: nextConfig.images,\n previewProps: prerenderManifest.preview,\n enableTainting: nextConfig.experimental.taint,\n reactMaxHeadersLength: nextConfig.reactMaxHeadersLength,\n\n multiZoneDraftMode: false,\n cacheLifeProfiles: nextConfig.cacheLife,\n staticPageGenerationTimeout: nextConfig.staticPageGenerationTimeout,\n basePath: nextConfig.basePath,\n serverActions: nextConfig.experimental.serverActions,\n logServerFunctions:\n typeof nextConfig.logging === 'object' &&\n Boolean(nextConfig.logging.serverFunctions),\n cacheComponents: Boolean(nextConfig.cacheComponents),\n validationLevel: nextConfig.experimental.instantInsights.validationLevel,\n experimental: {\n isRoutePPREnabled: false,\n expireTime: nextConfig.expireTime,\n staleTimes: nextConfig.experimental.staleTimes,\n dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover),\n optimisticRouting: Boolean(nextConfig.experimental.optimisticRouting),\n inlineCss: Boolean(nextConfig.experimental.inlineCss),\n prefetchInlining: nextConfig.experimental.prefetchInlining ?? false,\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts),\n // Edge has no Node response-close signal, so HMR cancellation is a\n // no-op.\n serverComponentsHmrCancellation: false,\n useCacheTimeout: nextConfig.experimental.useCacheTimeout,\n cachedNavigations: nextConfig.experimental.cachedNavigations ?? false,\n clientTraceMetadata:\n nextConfig.experimental.clientTraceMetadata || ([] as any),\n clientParamParsingOrigins:\n nextConfig.experimental.clientParamParsingOrigins,\n maxPostponedStateSizeBytes: parseMaxPostponedStateSize(\n nextConfig.experimental.maxPostponedStateSize\n ),\n exposeTestingApi:\n nextConfig.cacheComponents === true &&\n (pageRouteModule.isDev === true ||\n nextConfig.experimental.exposeTestingApiInProductionBuild === true),\n },\n\n incrementalCache: await pageRouteModule.getIncrementalCache(\n baseReq,\n nextConfig,\n prerenderManifest,\n true\n ),\n\n waitUntil: event.waitUntil.bind(event),\n onClose: (cb) => {\n closeController.onClose(cb)\n },\n onAfterTaskError: () => {},\n\n onInstrumentationRequestError: (\n error,\n _request,\n errorContext,\n silenceLog\n ) =>\n pageRouteModule.onRequestError(\n baseReq,\n error,\n errorContext,\n silenceLog,\n routerServerContext\n ),\n },\n }\n let finalStatus = 200\n\n const renderResultToResponse = (\n result: RenderResult<AppPageRenderResultMetadata>\n ): Response => {\n const varyHeader = pageRouteModule.getVaryHeader(\n resolvedPathname,\n interceptionRoutePatterns\n )\n // Handle null responses\n if (result.isNull) {\n finalStatus = 500\n closeController.dispatchClose()\n return new Response(null, { status: 500 })\n }\n\n // Extract metadata\n const { metadata } = result\n const headers = new Headers()\n finalStatus = metadata.statusCode || baseRes.statusCode || 200\n // Pull any fetch metrics from the render onto the request.\n ;(req as any).fetchMetrics = metadata.fetchMetrics\n\n // Set content type\n const contentType = result.contentType || 'text/html; charset=utf-8'\n headers.set('Content-Type', contentType)\n headers.set('x-edge-runtime', '1')\n\n if (varyHeader) {\n headers.set('Vary', varyHeader)\n }\n\n // Add existing headers\n for (const [key, value] of Object.entries({\n ...baseRes.getHeaders(),\n ...metadata.headers,\n })) {\n if (value !== undefined) {\n if (Array.isArray(value)) {\n // Handle multiple header values\n for (const v of value) {\n headers.append(key, String(v))\n }\n } else {\n headers.set(key, String(value))\n }\n }\n }\n\n // Handle static response\n if (!result.isDynamic) {\n const body = result.toUnchunkedString()\n headers.set(\n 'Content-Length',\n String(new TextEncoder().encode(body).length)\n )\n closeController.dispatchClose()\n return new Response(body, {\n status: finalStatus,\n headers,\n })\n }\n\n // Handle dynamic/streaming response\n // For edge runtime, we need to create a readable stream that pipes from the result\n const { readable, writable } = new TransformStream()\n\n // Start piping the result to the writable stream\n // This is done asynchronously to avoid blocking the response creation\n result\n .pipeTo(writable)\n .catch((err: unknown) => {\n console.error('Error piping RenderResult to response:', err)\n })\n .finally(() => closeController.dispatchClose())\n\n return new Response(readable, {\n status: finalStatus,\n headers,\n })\n }\n\n const invokeRender = async (span?: Span): Promise<Response> => {\n try {\n const result = await pageRouteModule\n .render(baseReq, baseRes, renderContext)\n .finally(() => {\n if (!span) return\n\n span.setAttributes({\n 'http.status_code': finalStatus,\n 'next.rsc': false,\n })\n\n if (finalStatus && finalStatus >= 500) {\n // For 5xx status codes: SHOULD be set to 'Error' span status.\n // x-ref: https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status\n span.setStatus({\n code: SpanStatusCode.ERROR,\n })\n // For span status 'Error', SHOULD set 'error.type' attribute.\n span.setAttribute('error.type', finalStatus.toString())\n }\n\n const rootSpanAttributes = tracer.getRootSpanAttributes()\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return\n }\n\n if (\n rootSpanAttributes.get('next.span_type') !==\n BaseServerSpan.handleRequest\n ) {\n console.warn(\n `Unexpected root span type '${rootSpanAttributes.get(\n 'next.span_type'\n )}'. Please report this Next.js issue https://github.com/vercel/next.js`\n )\n return\n }\n\n const route = normalizedSrcPage\n if (route) {\n const name = `${req.method} ${route}`\n\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name,\n })\n span.updateName(name)\n } else {\n span.updateName(`${req.method} ${srcPage}`)\n }\n })\n\n return renderResultToResponse(result)\n } catch (err) {\n const silenceLog = false\n await pageRouteModule.onRequestError(\n baseReq,\n err,\n {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'render',\n revalidateReason: undefined,\n },\n silenceLog\n )\n // rethrow so that we can handle serving error page\n throw err\n }\n }\n\n const tracer = getTracer()\n\n return tracer.withPropagatedContext(req.headers, () =>\n tracer.trace(\n BaseServerSpan.handleRequest,\n {\n spanName: `${req.method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': req.method,\n 'http.target': relativeUrl,\n 'http.route': normalizedSrcPage,\n },\n },\n invokeRender\n )\n )\n}\n\nconst internalHandler: EdgeHandler = (opts) => {\n return adapter({\n ...opts,\n IncrementalCache,\n handler: requestHandler,\n incrementalCacheHandler,\n page: 'VAR_PAGE',\n })\n}\n\nexport async function handler(\n request: Request,\n ctx: {\n waitUntil?: (prom: Promise<void>) => void\n signal?: AbortSignal\n requestMeta?: RequestMeta\n }\n): Promise<Response> {\n const result = await internalHandler({\n request: {\n url: request.url,\n method: request.method,\n headers: toNodeOutgoingHttpHeaders(request.headers),\n nextConfig: {\n basePath: process.env.__NEXT_BASE_PATH,\n i18n: process.env.__NEXT_I18N_CONFIG as any,\n trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),\n experimental: {\n cacheLife: process.env.__NEXT_CACHE_LIFE as any,\n authInterrupts: Boolean(\n process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS\n ),\n clientParamParsingOrigins: process.env\n .__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any,\n },\n },\n page: {\n name: 'VAR_PAGE',\n },\n body:\n request.method !== 'GET' && request.method !== 'HEAD'\n ? (request.body ?? undefined)\n : undefined,\n waitUntil: ctx.waitUntil,\n requestMeta: ctx.requestMeta,\n signal: ctx.signal || new AbortController().signal,\n },\n })\n\n ctx.waitUntil?.(result.waitUntil)\n\n return result.response\n}\n\n// backwards compat\nexport default internalHandler\n"],"names":["ComponentMod","handler","self","maybeJSONParse","str","JSON","parse","undefined","rscManifest","__RSC_MANIFEST","rscServerManifest","__RSC_SERVER_MANIFEST","setManifestsSingleton","page","clientReferenceManifest","serverActionsManifest","pageMod","requestHandler","req","event","srcPage","normalizedSrcPage","normalizeAppPath","relativeUrl","nextUrl","pathname","search","baseReq","WebNextRequest","baseRes","WebNextResponse","pageRouteModule","routeModule","prepareResult","prepare","multiZoneDraftMode","Response","status","query","params","buildId","nextConfig","buildManifest","prerenderManifest","reactLoadableManifest","subresourceIntegrityManifest","dynamicCssManifest","nextFontManifest","resolvedPathname","interceptionRoutePatterns","routerServerContext","deploymentId","clientAssetToken","cacheHandlers","initializeCacheHandlers","cacheMaxMemorySize","isPossibleServerAction","getIsPossibleServerAction","botType","getBotType","headers","get","isOnDemandRevalidate","checkIsOnDemandRevalidate","preview","closeController","CloseController","renderContext","sharedContext","fallbackRouteParams","renderOpts","App","Document","pageConfig","Component","interopDefault","postponed","serveStreamingMetadata","supportsDynamicResponse","setIsrStatus","dir","relativeProjectDir","isDraftMode","assetPrefix","nextConfigOutput","output","crossOrigin","trailingSlash","images","previewProps","enableTainting","experimental","taint","reactMaxHeadersLength","cacheLifeProfiles","cacheLife","staticPageGenerationTimeout","basePath","serverActions","logServerFunctions","logging","Boolean","serverFunctions","cacheComponents","validationLevel","instantInsights","isRoutePPREnabled","expireTime","staleTimes","dynamicOnHover","optimisticRouting","inlineCss","prefetchInlining","authInterrupts","serverComponentsHmrCancellation","useCacheTimeout","cachedNavigations","clientTraceMetadata","clientParamParsingOrigins","maxPostponedStateSizeBytes","parseMaxPostponedStateSize","maxPostponedStateSize","exposeTestingApi","isDev","exposeTestingApiInProductionBuild","incrementalCache","getIncrementalCache","waitUntil","bind","onClose","cb","onAfterTaskError","onInstrumentationRequestError","error","_request","errorContext","silenceLog","onRequestError","finalStatus","renderResultToResponse","result","varyHeader","getVaryHeader","isNull","dispatchClose","metadata","Headers","statusCode","fetchMetrics","contentType","set","key","value","Object","entries","getHeaders","Array","isArray","v","append","String","isDynamic","body","toUnchunkedString","TextEncoder","encode","length","readable","writable","TransformStream","pipeTo","catch","err","console","finally","invokeRender","span","render","setAttributes","setStatus","code","SpanStatusCode","ERROR","setAttribute","toString","rootSpanAttributes","tracer","getRootSpanAttributes","BaseServerSpan","handleRequest","warn","route","name","method","updateName","routerKind","routePath","routeType","revalidateReason","getTracer","withPropagatedContext","trace","spanName","kind","SpanKind","SERVER","attributes","internalHandler","opts","adapter","IncrementalCache","incrementalCacheHandler","request","ctx","url","toNodeOutgoingHttpHeaders","process","env","__NEXT_BASE_PATH","i18n","__NEXT_I18N_CONFIG","__NEXT_TRAILING_SLASH","__NEXT_CACHE_LIFE","__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS","__NEXT_CLIENT_PARAM_PARSING_ORIGINS","requestMeta","signal","AbortController","response"],"mappings":";;;;;;;;;;;;;;;;IAsDaA,YAAY;eAAZA;;IA2Yb,mBAAmB;IACnB,OAA8B;eAA9B;;IA7CsBC,OAAO;eAAPA;;;QArZf;yBAKA;kCAC0B;sEAER;oCAEa;kEACP;2BACA;wBAMxB;qBACyC;yCAQN;uBACf;gCACI;0BACE;0BACS;4BACV;2BACW;uBACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAStBC;AALpB,0CAA0C;AAC1C,iCAAiC;AAEjC,MAAMC,iBAAiB,CAACC,MAAkBA,MAAMC,KAAKC,KAAK,CAACF,O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,gBAAgBZ,QACdmH,QAAQC,GAAG,CAACM,mCAAmC;oBAEjDzG,2BAA2BkG,QAAQC,GAAG,CACnCO,mCAAmC;gBACxC;YACF;YACAnN,MAAM;gBACJmL,MAAM;YACR;YACA9B,MACEkD,QAAQnB,MAAM,KAAK,SAASmB,QAAQnB,MAAM,KAAK,SAC1CmB,QAAQlD,IAAI,IAAI3J,YACjBA;YACNwH,WAAWsF,IAAItF,SAAS;YACxBkG,aAAaZ,IAAIY,WAAW;YAC5BC,QAAQb,IAAIa,MAAM,IAAI,IAAIC,kBAAkBD,MAAM;QACpD;IACF;IAEAb,IAAItF,SAAS,oBAAbsF,IAAItF,SAAS,MAAbsF,KAAgBzE,OAAOb,SAAS;IAEhC,OAAOa,OAAOwF,QAAQ;AACxB;MAGA,WAAerB","ignoreList":[0]} |
@@ -96,3 +96,3 @@ "use strict"; | ||
| isPersistentCachingEnabled: persistentCaching, | ||
| nextVersion: "16.3.1-canary.10" | ||
| nextVersion: "16.3.1-canary.11" | ||
| }, { | ||
@@ -99,0 +99,0 @@ turbopackMemoryEviction: config.experimental.turbopackMemoryEvictionMode, |
@@ -119,3 +119,3 @@ // Import cpu-profile first to start profiling early if enabled | ||
| deferredEntries: config.experimental.deferredEntries, | ||
| nextVersion: "16.3.1-canary.10" | ||
| nextVersion: "16.3.1-canary.11" | ||
| }; | ||
@@ -122,0 +122,0 @@ if (config.experimental.turbopackSeedCacheFromWorktree) { |
@@ -6,5 +6,5 @@ 1:"$Sreact.fragment" | ||
| 7:"$Sreact.suspense" | ||
| 0:{"rsc":["$","$1","c",{"children":[["$","$L2",null,{"Component":"$3","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@4","$@5"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/16s6g-zs4p3i7.js","async":true}]],["$","$L6",null,{"children":["$","$7",null,{"name":"Next.MetadataOutlet","children":"$@8"}]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"XmRGcu2mYFcHhNv6FcydE"} | ||
| 0:{"rsc":["$","$1","c",{"children":[["$","$L2",null,{"Component":"$3","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@4","$@5"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/16s6g-zs4p3i7.js","async":true}]],["$","$L6",null,{"children":["$","$7",null,{"name":"Next.MetadataOutlet","children":"$@8"}]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"sR5ErRj0ZbecEXQPAlvNc"} | ||
| 4:{} | ||
| 5:"$0:rsc:props:children:0:props:serverProvidedParams:params" | ||
| 8:null |
@@ -12,3 +12,3 @@ 1:"$Sreact.fragment" | ||
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"P":null,"c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[["$","$L4",null,{"Component":"$5","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@6","$@7"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/16s6g-zs4p3i7.js","async":true,"nonce":"$undefined"}]],["$","$L8",null,{"children":["$","$9",null,{"name":"Next.MetadataOutlet","children":"$@a"}]}]]}],{},null,false,null]},null,false,null],["$","$1","h",{"children":[null,["$","$Lb",null,{"children":"$Lc"}],["$","div",null,{"hidden":true,"children":["$","$Ld",null,{"children":["$","$9",null,{"name":"Next.Metadata","children":"$Le"}]}]}],null]}],false]],"m":"$undefined","G":["$f",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"XmRGcu2mYFcHhNv6FcydE"} | ||
| 0:{"P":null,"c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[["$","$L4",null,{"Component":"$5","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@6","$@7"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/16s6g-zs4p3i7.js","async":true,"nonce":"$undefined"}]],["$","$L8",null,{"children":["$","$9",null,{"name":"Next.MetadataOutlet","children":"$@a"}]}]]}],{},null,false,null]},null,false,null],["$","$1","h",{"children":[null,["$","$Lb",null,{"children":"$Lc"}],["$","div",null,{"hidden":true,"children":["$","$Ld",null,{"children":["$","$9",null,{"name":"Next.Metadata","children":"$Le"}]}]}],null]}],false]],"m":"$undefined","G":["$f",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"sR5ErRj0ZbecEXQPAlvNc"} | ||
| 6:{} | ||
@@ -15,0 +15,0 @@ 7:"$0:f:0:1:1:children:0:props:children:0:props:serverProvidedParams:params" |
@@ -5,2 +5,2 @@ 1:"$Sreact.fragment" | ||
| 4:"$Sreact.suspense" | ||
| 0:{"rsc":["$","$1","h",{"children":[null,["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"Next.js Bundle Analyzer"}],["$","meta","1",{"name":"description","content":"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"}]]}]}]}],null]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"XmRGcu2mYFcHhNv6FcydE"} | ||
| 0:{"rsc":["$","$1","h",{"children":[null,["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"Next.js Bundle Analyzer"}],["$","meta","1",{"name":"description","content":"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"}]]}]}]}],null]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"sR5ErRj0ZbecEXQPAlvNc"} |
@@ -5,2 +5,2 @@ 1:"$Sreact.fragment" | ||
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"XmRGcu2mYFcHhNv6FcydE"} | ||
| 0:{"rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"sR5ErRj0ZbecEXQPAlvNc"} |
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"tree":{"name":"","param":null,"prefetchHints":16,"slots":{"children":{"name":"__PAGE__","param":null,"prefetchHints":0,"slots":null}}},"staleTime":300,"buildId":"XmRGcu2mYFcHhNv6FcydE"} | ||
| 0:{"tree":{"name":"","param":null,"prefetchHints":16,"slots":{"children":{"name":"__PAGE__","param":null,"prefetchHints":0,"slots":null}}},"staleTime":300,"buildId":"sR5ErRj0ZbecEXQPAlvNc"} |
@@ -10,2 +10,2 @@ <!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="/_next/static/chunks/0i88bcw_h0tc6.css" data-precedence="next"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/0kor3_y3m.uh~.js"/><script src="/_next/static/chunks/0gto6h.7wfb54.js" async=""></script><script src="/_next/static/chunks/0o1qc.kvvuq1u.js" async=""></script><script src="/_next/static/chunks/turbopack-0vhvx5o96qn.d.js" async=""></script><script src="/_next/static/chunks/09tfif45vshr2.js" async=""></script><meta name="robots" content="noindex"/><title>404: This page could not be found.</title><title>Next.js Bundle Analyzer</title><meta name="description" content="Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"/><script> | ||
| })(); | ||
| </script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><div style="font-family:system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding:0 23px 0 0;font-size:24px;font-weight:500;vertical-align:top;line-height:49px">404</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:49px;margin:0">This page could not be found.</h2></div></div></div><!--$--><!--/$--><script src="/_next/static/chunks/0kor3_y3m.uh~.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[85600,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n3:I[67998,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n4:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"OutletBoundary\"]\n5:\"$Sreact.suspense\"\n8:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"ViewportBoundary\"]\na:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"MetadataBoundary\"]\nc:I[90533,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"_not-found\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"/_not-found\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/09tfif45vshr2.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style\",\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style\",\"children\":404}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style\",\"children\":[\"$\",\"h2\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style\",\"children\":\"This page could not be found.\"}]}]]}]}]],null,[\"$\",\"$L4\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@6\"}]}]]}],{},null,false,null]},null,false,\"$@7\"]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[[\"$\",\"meta\",null,{\"name\":\"robots\",\"content\":\"noindex\"}],[\"$\",\"$L8\",null,{\"children\":\"$L9\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$La\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Lb\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$c\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"XmRGcu2mYFcHhNv6FcydE\"}\n"])</script><script>self.__next_f.push([1,"d:[]\n7:\"$Wd\"\n"])</script><script>self.__next_f.push([1,"9:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"6:null\nb:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html> | ||
| </script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><div style="font-family:system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding:0 23px 0 0;font-size:24px;font-weight:500;vertical-align:top;line-height:49px">404</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:49px;margin:0">This page could not be found.</h2></div></div></div><!--$--><!--/$--><script src="/_next/static/chunks/0kor3_y3m.uh~.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[85600,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n3:I[67998,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n4:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"OutletBoundary\"]\n5:\"$Sreact.suspense\"\n8:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"ViewportBoundary\"]\na:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"MetadataBoundary\"]\nc:I[90533,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"_not-found\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"/_not-found\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/09tfif45vshr2.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style\",\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style\",\"children\":404}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style\",\"children\":[\"$\",\"h2\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style\",\"children\":\"This page could not be found.\"}]}]]}]}]],null,[\"$\",\"$L4\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@6\"}]}]]}],{},null,false,null]},null,false,\"$@7\"]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[[\"$\",\"meta\",null,{\"name\":\"robots\",\"content\":\"noindex\"}],[\"$\",\"$L8\",null,{\"children\":\"$L9\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$La\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Lb\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$c\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"sR5ErRj0ZbecEXQPAlvNc\"}\n"])</script><script>self.__next_f.push([1,"d:[]\n7:\"$Wd\"\n"])</script><script>self.__next_f.push([1,"9:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"6:null\nb:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html> |
@@ -10,3 +10,3 @@ 1:"$Sreact.fragment" | ||
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"P":null,"c":["","_not-found"],"q":"","i":false,"f":[[["",{"children":["/_not-found",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","forbidden":"$undefined","unauthorized":"$undefined"}]]}],{"children":[["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style","children":404}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style","children":["$","h2",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style","children":"This page could not be found."}]}]]}]}]],null,["$","$L4",null,{"children":["$","$5",null,{"name":"Next.MetadataOutlet","children":"$@6"}]}]]}],{},null,false,null]},null,false,"$@7"]},null,false,null],["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L8",null,{"children":"$L9"}],["$","div",null,{"hidden":true,"children":["$","$La",null,{"children":["$","$5",null,{"name":"Next.Metadata","children":"$Lb"}]}]}],null]}],false]],"m":"$undefined","G":["$c",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"XmRGcu2mYFcHhNv6FcydE"} | ||
| 0:{"P":null,"c":["","_not-found"],"q":"","i":false,"f":[[["",{"children":["/_not-found",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","forbidden":"$undefined","unauthorized":"$undefined"}]]}],{"children":[["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style","children":404}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style","children":["$","h2",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style","children":"This page could not be found."}]}]]}]}]],null,["$","$L4",null,{"children":["$","$5",null,{"name":"Next.MetadataOutlet","children":"$@6"}]}]]}],{},null,false,null]},null,false,"$@7"]},null,false,null],["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L8",null,{"children":"$L9"}],["$","div",null,{"hidden":true,"children":["$","$La",null,{"children":["$","$5",null,{"name":"Next.Metadata","children":"$Lb"}]}]}],null]}],false]],"m":"$undefined","G":["$c",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"sR5ErRj0ZbecEXQPAlvNc"} | ||
| d:[] | ||
@@ -13,0 +13,0 @@ 7:"$Wd" |
@@ -10,3 +10,3 @@ 1:"$Sreact.fragment" | ||
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"P":null,"c":["","_not-found"],"q":"","i":false,"f":[[["",{"children":["/_not-found",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","forbidden":"$undefined","unauthorized":"$undefined"}]]}],{"children":[["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style","children":404}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style","children":["$","h2",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style","children":"This page could not be found."}]}]]}]}]],null,["$","$L4",null,{"children":["$","$5",null,{"name":"Next.MetadataOutlet","children":"$@6"}]}]]}],{},null,false,null]},null,false,"$@7"]},null,false,null],["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L8",null,{"children":"$L9"}],["$","div",null,{"hidden":true,"children":["$","$La",null,{"children":["$","$5",null,{"name":"Next.Metadata","children":"$Lb"}]}]}],null]}],false]],"m":"$undefined","G":["$c",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"XmRGcu2mYFcHhNv6FcydE"} | ||
| 0:{"P":null,"c":["","_not-found"],"q":"","i":false,"f":[[["",{"children":["/_not-found",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","forbidden":"$undefined","unauthorized":"$undefined"}]]}],{"children":[["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style","children":404}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style","children":["$","h2",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style","children":"This page could not be found."}]}]]}]}]],null,["$","$L4",null,{"children":["$","$5",null,{"name":"Next.MetadataOutlet","children":"$@6"}]}]]}],{},null,false,null]},null,false,"$@7"]},null,false,null],["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L8",null,{"children":"$L9"}],["$","div",null,{"hidden":true,"children":["$","$La",null,{"children":["$","$5",null,{"name":"Next.Metadata","children":"$Lb"}]}]}],null]}],false]],"m":"$undefined","G":["$c",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"sR5ErRj0ZbecEXQPAlvNc"} | ||
| d:[] | ||
@@ -13,0 +13,0 @@ 7:"$Wd" |
@@ -5,2 +5,2 @@ 1:"$Sreact.fragment" | ||
| 4:"$Sreact.suspense" | ||
| 0:{"rsc":["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"Next.js Bundle Analyzer"}],["$","meta","1",{"name":"description","content":"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"}]]}]}]}],null]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"XmRGcu2mYFcHhNv6FcydE"} | ||
| 0:{"rsc":["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"Next.js Bundle Analyzer"}],["$","meta","1",{"name":"description","content":"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"}]]}]}]}],null]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"sR5ErRj0ZbecEXQPAlvNc"} |
@@ -5,2 +5,2 @@ 1:"$Sreact.fragment" | ||
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"XmRGcu2mYFcHhNv6FcydE"} | ||
| 0:{"rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"sR5ErRj0ZbecEXQPAlvNc"} |
| 1:"$Sreact.fragment" | ||
| 2:I[12361,["/_next/static/chunks/09tfif45vshr2.js"],"OutletBoundary"] | ||
| 3:"$Sreact.suspense" | ||
| 0:{"rsc":["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],null,["$","$L2",null,{"children":["$","$3",null,{"name":"Next.MetadataOutlet","children":"$@4"}]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"XmRGcu2mYFcHhNv6FcydE"} | ||
| 0:{"rsc":["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],null,["$","$L2",null,{"children":["$","$3",null,{"name":"Next.MetadataOutlet","children":"$@4"}]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"sR5ErRj0ZbecEXQPAlvNc"} | ||
| 4:null |
@@ -5,2 +5,2 @@ 1:"$Sreact.fragment" | ||
| 4:[] | ||
| 0:{"rsc":["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}]}]]}],"isPartial":false,"staleTime":300,"varyParams":"$W4","buildId":"XmRGcu2mYFcHhNv6FcydE"} | ||
| 0:{"rsc":["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}]}]]}],"isPartial":false,"staleTime":300,"varyParams":"$W4","buildId":"sR5ErRj0ZbecEXQPAlvNc"} |
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"tree":{"name":"","param":null,"prefetchHints":16,"slots":{"children":{"name":"/_not-found","param":null,"prefetchHints":0,"slots":{"children":{"name":"__PAGE__","param":null,"prefetchHints":0,"slots":null}}}}},"staleTime":300,"buildId":"XmRGcu2mYFcHhNv6FcydE"} | ||
| 0:{"tree":{"name":"","param":null,"prefetchHints":16,"slots":{"children":{"name":"/_not-found","param":null,"prefetchHints":0,"slots":{"children":{"name":"__PAGE__","param":null,"prefetchHints":0,"slots":null}}}}},"staleTime":300,"buildId":"sR5ErRj0ZbecEXQPAlvNc"} |
@@ -10,2 +10,2 @@ <!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="/_next/static/chunks/0i88bcw_h0tc6.css" data-precedence="next"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/0kor3_y3m.uh~.js"/><script src="/_next/static/chunks/0gto6h.7wfb54.js" async=""></script><script src="/_next/static/chunks/0o1qc.kvvuq1u.js" async=""></script><script src="/_next/static/chunks/turbopack-0vhvx5o96qn.d.js" async=""></script><script src="/_next/static/chunks/09tfif45vshr2.js" async=""></script><meta name="robots" content="noindex"/><title>404: This page could not be found.</title><title>Next.js Bundle Analyzer</title><meta name="description" content="Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"/><script> | ||
| })(); | ||
| </script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><div style="font-family:system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding:0 23px 0 0;font-size:24px;font-weight:500;vertical-align:top;line-height:49px">404</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:49px;margin:0">This page could not be found.</h2></div></div></div><!--$--><!--/$--><script src="/_next/static/chunks/0kor3_y3m.uh~.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[85600,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n3:I[67998,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n4:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"OutletBoundary\"]\n5:\"$Sreact.suspense\"\n8:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"ViewportBoundary\"]\na:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"MetadataBoundary\"]\nc:I[90533,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"_not-found\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"/_not-found\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/09tfif45vshr2.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style\",\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style\",\"children\":404}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style\",\"children\":[\"$\",\"h2\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style\",\"children\":\"This page could not be found.\"}]}]]}]}]],null,[\"$\",\"$L4\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@6\"}]}]]}],{},null,false,null]},null,false,\"$@7\"]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[[\"$\",\"meta\",null,{\"name\":\"robots\",\"content\":\"noindex\"}],[\"$\",\"$L8\",null,{\"children\":\"$L9\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$La\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Lb\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$c\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"XmRGcu2mYFcHhNv6FcydE\"}\n"])</script><script>self.__next_f.push([1,"d:[]\n7:\"$Wd\"\n"])</script><script>self.__next_f.push([1,"9:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"6:null\nb:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html> | ||
| </script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><div style="font-family:system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding:0 23px 0 0;font-size:24px;font-weight:500;vertical-align:top;line-height:49px">404</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:49px;margin:0">This page could not be found.</h2></div></div></div><!--$--><!--/$--><script src="/_next/static/chunks/0kor3_y3m.uh~.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[85600,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n3:I[67998,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n4:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"OutletBoundary\"]\n5:\"$Sreact.suspense\"\n8:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"ViewportBoundary\"]\na:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"MetadataBoundary\"]\nc:I[90533,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"_not-found\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"/_not-found\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/09tfif45vshr2.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style\",\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style\",\"children\":404}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style\",\"children\":[\"$\",\"h2\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style\",\"children\":\"This page could not be found.\"}]}]]}]}]],null,[\"$\",\"$L4\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@6\"}]}]]}],{},null,false,null]},null,false,\"$@7\"]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[[\"$\",\"meta\",null,{\"name\":\"robots\",\"content\":\"noindex\"}],[\"$\",\"$L8\",null,{\"children\":\"$L9\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$La\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Lb\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$c\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"sR5ErRj0ZbecEXQPAlvNc\"}\n"])</script><script>self.__next_f.push([1,"d:[]\n7:\"$Wd\"\n"])</script><script>self.__next_f.push([1,"9:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"6:null\nb:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html> |
@@ -10,2 +10,2 @@ <!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="/_next/static/chunks/0i88bcw_h0tc6.css" data-precedence="next"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/0kor3_y3m.uh~.js"/><script src="/_next/static/chunks/0gto6h.7wfb54.js" async=""></script><script src="/_next/static/chunks/0o1qc.kvvuq1u.js" async=""></script><script src="/_next/static/chunks/turbopack-0vhvx5o96qn.d.js" async=""></script><script src="/_next/static/chunks/09tfif45vshr2.js" async=""></script><script src="/_next/static/chunks/16s6g-zs4p3i7.js" async=""></script><title>Next.js Bundle Analyzer</title><meta name="description" content="Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"/><script> | ||
| })(); | ||
| </script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><main class="h-screen flex flex-col bg-background"><div class="flex-none px-4 py-2 border-b border-border flex items-center gap-3"><div class="flex-1 flex"><div class="flex items-center gap-2 min-w-64 max-w-full"><button class="inline-flex items-center gap-2 whitespace-nowrap rounded-md font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2 flex-grow-1 w-full justify-between font-mono text-sm" role="combobox" aria-expanded="false" disabled="" type="button" aria-haspopup="dialog" aria-controls="radix-_R_lbtb_" data-state="closed"><div class="flex items-center"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-loader mr-2 inline animate-spin" aria-hidden="true"><path d="M12 2v4"></path><path d="m16.2 7.8 2.9-2.9"></path><path d="M18 12h4"></path><path d="m16.2 16.2 2.9 2.9"></path><path d="M12 18v4"></path><path d="m4.9 19.1 2.9-2.9"></path><path d="M2 12h4"></path><path d="m4.9 4.9 2.9 2.9"></path></svg>Loading routes...</div><div class="flex items-center gap-2"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevrons-up-down h-4 w-4 shrink-0 opacity-50" aria-hidden="true"><path d="m7 15 5 5 5-5"></path><path d="m7 9 5-5 5 5"></path></svg></div></button></div></div><div class="flex items-center gap-2"></div></div><div class="flex-1 flex min-h-0"><div class="flex-1 min-w-0 p-4 bg-background"><div class="h-full w-full grid grid-cols-12 grid-rows-8 gap-2"><div class="animate-pulse rounded-md bg-muted col-span-5 row-span-4"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-3"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-3"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-1"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-4"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div></div></div><button type="button" class="flex-none w-1 bg-border cursor-col-resize transition-colors" disabled="" aria-label="Resize sidebar"></button><div class="flex-none bg-muted border-l border-border overflow-y-auto" style="width:20%"><div class="flex-1 p-3 space-y-4 overflow-y-auto"><div class="animate-pulse rounded-md bg-muted h-4 w-3/4"></div><div class="animate-pulse rounded-md bg-muted h-4 w-full"></div><div class="animate-pulse rounded-md bg-muted h-4 w-5/6"></div><div class="mt-4 space-y-2"><div class="animate-pulse rounded-md bg-muted h-3 w-full"></div><div class="animate-pulse rounded-md bg-muted h-3 w-full"></div><div class="animate-pulse rounded-md bg-muted h-3 w-4/5"></div></div></div></div></div></main><!--$--><!--/$--><script src="/_next/static/chunks/0kor3_y3m.uh~.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[85600,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n3:I[67998,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n4:I[41813,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"ClientPageRoot\"]\n5:I[79331,[\"/_next/static/chunks/09tfif45vshr2.js\",\"/_next/static/chunks/16s6g-zs4p3i7.js\"],\"default\"]\n8:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"OutletBoundary\"]\n9:\"$Sreact.suspense\"\nb:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"ViewportBoundary\"]\nd:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"MetadataBoundary\"]\nf:I[90533,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"__PAGE__\",{}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/09tfif45vshr2.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[\"$\",\"$L4\",null,{\"Component\":\"$5\",\"serverProvidedParams\":{\"searchParams\":{},\"params\":{},\"promises\":[\"$@6\",\"$@7\"]}}],[[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/16s6g-zs4p3i7.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"$L8\",null,{\"children\":[\"$\",\"$9\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@a\"}]}]]}],{},null,false,null]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[null,[\"$\",\"$Lb\",null,{\"children\":\"$Lc\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$Ld\",null,{\"children\":[\"$\",\"$9\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Le\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$f\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"XmRGcu2mYFcHhNv6FcydE\"}\n"])</script><script>self.__next_f.push([1,"6:{}\n7:\"$0:f:0:1:1:children:0:props:children:0:props:serverProvidedParams:params\"\n"])</script><script>self.__next_f.push([1,"c:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"a:null\ne:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html> | ||
| </script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><main class="h-screen flex flex-col bg-background"><div class="flex-none px-4 py-2 border-b border-border flex items-center gap-3"><div class="flex-1 flex"><div class="flex items-center gap-2 min-w-64 max-w-full"><button class="inline-flex items-center gap-2 whitespace-nowrap rounded-md font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2 flex-grow-1 w-full justify-between font-mono text-sm" role="combobox" aria-expanded="false" disabled="" type="button" aria-haspopup="dialog" aria-controls="radix-_R_lbtb_" data-state="closed"><div class="flex items-center"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-loader mr-2 inline animate-spin" aria-hidden="true"><path d="M12 2v4"></path><path d="m16.2 7.8 2.9-2.9"></path><path d="M18 12h4"></path><path d="m16.2 16.2 2.9 2.9"></path><path d="M12 18v4"></path><path d="m4.9 19.1 2.9-2.9"></path><path d="M2 12h4"></path><path d="m4.9 4.9 2.9 2.9"></path></svg>Loading routes...</div><div class="flex items-center gap-2"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevrons-up-down h-4 w-4 shrink-0 opacity-50" aria-hidden="true"><path d="m7 15 5 5 5-5"></path><path d="m7 9 5-5 5 5"></path></svg></div></button></div></div><div class="flex items-center gap-2"></div></div><div class="flex-1 flex min-h-0"><div class="flex-1 min-w-0 p-4 bg-background"><div class="h-full w-full grid grid-cols-12 grid-rows-8 gap-2"><div class="animate-pulse rounded-md bg-muted col-span-5 row-span-4"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-3"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-3"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-1"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-4"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div></div></div><button type="button" class="flex-none w-1 bg-border cursor-col-resize transition-colors" disabled="" aria-label="Resize sidebar"></button><div class="flex-none bg-muted border-l border-border overflow-y-auto" style="width:20%"><div class="flex-1 p-3 space-y-4 overflow-y-auto"><div class="animate-pulse rounded-md bg-muted h-4 w-3/4"></div><div class="animate-pulse rounded-md bg-muted h-4 w-full"></div><div class="animate-pulse rounded-md bg-muted h-4 w-5/6"></div><div class="mt-4 space-y-2"><div class="animate-pulse rounded-md bg-muted h-3 w-full"></div><div class="animate-pulse rounded-md bg-muted h-3 w-full"></div><div class="animate-pulse rounded-md bg-muted h-3 w-4/5"></div></div></div></div></div></main><!--$--><!--/$--><script src="/_next/static/chunks/0kor3_y3m.uh~.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[85600,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n3:I[67998,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\"]\n4:I[41813,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"ClientPageRoot\"]\n5:I[79331,[\"/_next/static/chunks/09tfif45vshr2.js\",\"/_next/static/chunks/16s6g-zs4p3i7.js\"],\"default\"]\n8:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"OutletBoundary\"]\n9:\"$Sreact.suspense\"\nb:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"ViewportBoundary\"]\nd:I[12361,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"MetadataBoundary\"]\nf:I[90533,[\"/_next/static/chunks/09tfif45vshr2.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"__PAGE__\",{}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/09tfif45vshr2.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[\"$\",\"$L4\",null,{\"Component\":\"$5\",\"serverProvidedParams\":{\"searchParams\":{},\"params\":{},\"promises\":[\"$@6\",\"$@7\"]}}],[[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/16s6g-zs4p3i7.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"$L8\",null,{\"children\":[\"$\",\"$9\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@a\"}]}]]}],{},null,false,null]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[null,[\"$\",\"$Lb\",null,{\"children\":\"$Lc\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$Ld\",null,{\"children\":[\"$\",\"$9\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Le\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$f\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"sR5ErRj0ZbecEXQPAlvNc\"}\n"])</script><script>self.__next_f.push([1,"6:{}\n7:\"$0:f:0:1:1:children:0:props:children:0:props:serverProvidedParams:params\"\n"])</script><script>self.__next_f.push([1,"c:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"a:null\ne:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html> |
@@ -12,3 +12,3 @@ 1:"$Sreact.fragment" | ||
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"P":null,"c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[["$","$L4",null,{"Component":"$5","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@6","$@7"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/16s6g-zs4p3i7.js","async":true,"nonce":"$undefined"}]],["$","$L8",null,{"children":["$","$9",null,{"name":"Next.MetadataOutlet","children":"$@a"}]}]]}],{},null,false,null]},null,false,null],["$","$1","h",{"children":[null,["$","$Lb",null,{"children":"$Lc"}],["$","div",null,{"hidden":true,"children":["$","$Ld",null,{"children":["$","$9",null,{"name":"Next.Metadata","children":"$Le"}]}]}],null]}],false]],"m":"$undefined","G":["$f",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"XmRGcu2mYFcHhNv6FcydE"} | ||
| 0:{"P":null,"c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/09tfif45vshr2.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[["$","$L4",null,{"Component":"$5","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@6","$@7"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/16s6g-zs4p3i7.js","async":true,"nonce":"$undefined"}]],["$","$L8",null,{"children":["$","$9",null,{"name":"Next.MetadataOutlet","children":"$@a"}]}]]}],{},null,false,null]},null,false,null],["$","$1","h",{"children":[null,["$","$Lb",null,{"children":"$Lc"}],["$","div",null,{"hidden":true,"children":["$","$Ld",null,{"children":["$","$9",null,{"name":"Next.Metadata","children":"$Le"}]}]}],null]}],false]],"m":"$undefined","G":["$f",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"sR5ErRj0ZbecEXQPAlvNc"} | ||
| 6:{} | ||
@@ -15,0 +15,0 @@ 7:"$0:f:0:1:1:children:0:props:children:0:props:serverProvidedParams:params" |
@@ -42,3 +42,3 @@ #!/usr/bin/env node | ||
| const nextBuild = async (options, directory)=>{ | ||
| process.title = `next-build (v${"16.3.1-canary.10"})`; | ||
| process.title = `next-build (v${"16.3.1-canary.11"})`; | ||
| process.on('SIGTERM', ()=>{ | ||
@@ -45,0 +45,0 @@ (0, _cpuprofile.saveCpuProfile)(); |
@@ -43,3 +43,3 @@ #!/usr/bin/env node | ||
| const bindings = await (0, _swc.loadBindings)((_config_experimental1 = config.experimental) == null ? void 0 : _config_experimental1.useWasmBinary); | ||
| await bindings.turbo.databaseCompact(cachePath, "16.3.1-canary.10"); | ||
| await bindings.turbo.databaseCompact(cachePath, "16.3.1-canary.11"); | ||
| console.log('Turbopack database compaction complete.'); | ||
@@ -46,0 +46,0 @@ }; |
@@ -18,3 +18,3 @@ /** | ||
| const _setattributesfromprops = require("./set-attributes-from-props"); | ||
| const version = "16.3.1-canary.10"; | ||
| const version = "16.3.1-canary.11"; | ||
| window.next = { | ||
@@ -21,0 +21,0 @@ version, |
@@ -342,3 +342,3 @@ "use strict"; | ||
| }, []); | ||
| const { cache, tree, nextUrl, focusAndScrollRef, previousNextUrl } = state; | ||
| const { cache, tree, nextUrl, scrollRef, previousNextUrl } = state; | ||
| const matchingHead = (0, _react.useMemo)(()=>{ | ||
@@ -388,3 +388,3 @@ return (0, _findheadincache.findHeadInCache)(cache, tree[1]); | ||
| tree, | ||
| focusAndScrollRef, | ||
| scrollRef, | ||
| nextUrl, | ||
@@ -395,3 +395,3 @@ previousNextUrl | ||
| tree, | ||
| focusAndScrollRef, | ||
| scrollRef, | ||
| nextUrl, | ||
@@ -398,0 +398,0 @@ previousNextUrl |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/client/components/app-router.tsx"],"sourcesContent":["import 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 { CacheNode } from '../../shared/lib/app-router-types'\nimport { ACTION_RESTORE } from './router-reducer/router-reducer-types'\nimport type {\n AppHistoryState,\n AppRouterState,\n} from './router-reducer/router-reducer-types'\nimport { createHrefFromUrl } from './router-reducer/create-href-from-url'\nimport {\n SearchParamsContext,\n PathnameContext,\n PathParamsContext,\n NavigationPromisesContext,\n type NavigationPromises,\n} from '../../shared/lib/hooks-client-context.shared-runtime'\nimport { dispatchAppRouterAction, useActionQueue } from './use-action-queue'\nimport { setLastCommittedTree } from './router-reducer/reducers/committed-state'\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 {\n extractSourcePageFromFlightRouterState,\n getSelectedParams,\n} 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 } 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'\nimport { getAssetTokenQuery } from '../../shared/lib/deployment-id'\n\nconst globalMutable: {\n pendingMpaPath?: string\n} = {}\n\n// A Back/Forward press before the router's popstate listener exists moves the\n// browser to a different history entry than the one the document was activated\n// on, and the resulting popstate fires with nobody listening. The activation\n// entry is fixed for the document's lifetime and entry keys are stable across\n// replaceState, so until the listener is installed a key mismatch means a\n// traversal went unobserved.\nfunction hasMissedTraversal(): boolean {\n if (typeof window.navigation === 'undefined') {\n return false\n }\n const activationEntry = window.navigation.activation?.entry\n const currentEntry = window.navigation.currentEntry\n return (\n activationEntry != null &&\n currentEntry != null &&\n activationEntry.key !== currentEntry.key &&\n // Only entries written by the app router can be restored; on any other\n // entry the traversal is left unhandled, as before.\n window.history.state?.__NA === true\n )\n}\n\nlet checkedMissedTraversalBeforeHistoryWrite = false\nlet checkedMissedTraversalBeforeReplay = false\n\n/**\n * Handles a popstate event (or one that was missed before hydration).\n * By default dispatches ACTION_RESTORE, however if the history entry was not\n * pushed/replaced by app-router it will reload the page.\n * That case can happen when the old router injected the history entry.\n */\nfunction handlePopState(state: PopStateEvent['state']): void {\n if (!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 (!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 state.__PRIVATE_NEXTJS_INTERNALS_TREE\n )\n })\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, renderedSearch } = appRouterState\n\n if (!checkedMissedTraversalBeforeHistoryWrite) {\n checkedMissedTraversalBeforeHistoryWrite = true\n if (hasMissedTraversal()) {\n // Skip the write: it would overwrite the traversed-to entry's state.\n // The tree was rendered even though the history write is skipped.\n setLastCommittedTree(tree)\n return\n }\n }\n\n const appHistoryState: AppHistoryState = {\n tree,\n renderedSearch,\n }\n\n // TODO: Use Navigation API if available\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: appHistoryState,\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\n setLastCommittedTree(tree)\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 pingVisibleLinks(appRouterState.nextUrl, appRouterState.tree)\n }, [appRouterState.nextUrl, appRouterState.tree])\n\n return null\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 const { cache, 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 tree,\n }\n }, [cache, tree])\n }\n\n useEffect(() => {\n const sourcePage = extractSourcePageFromFlightRouterState(state.tree)\n\n if (sourcePage !== undefined) {\n window.next.__internal_src_page = sourcePage\n } else {\n delete window.next.__internal_src_page\n }\n }, [state.tree])\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 historyState: 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 === '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 appHistoryState: AppHistoryState | 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 historyState: appHistoryState,\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 // TODO: Warn when Navigation API is available (navigation.navigate() should be used)\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 // TODO: Warn when Navigation API is available (navigation.navigate() should be used)\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 const onPopState = (event: PopStateEvent) => handlePopState(event.state)\n\n window.addEventListener('popstate', onPopState)\n\n if (!checkedMissedTraversalBeforeReplay) {\n checkedMissedTraversalBeforeReplay = true\n if (hasMissedTraversal()) {\n handlePopState(window.history.state)\n }\n }\n\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, previousNextUrl } = 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 // Create instrumented promises for navigation hooks (dev-only)\n // These are specially instrumented promises to show in the Suspense DevTools\n // Promises are cached outside of render to survive suspense retries.\n let instrumentedNavigationPromises: NavigationPromises | null = null\n if (process.env.NODE_ENV !== 'production') {\n const { createRootNavigationPromises } =\n require('./navigation-devtools') as typeof import('./navigation-devtools')\n\n instrumentedNavigationPromises = createRootNavigationPromises(\n tree,\n pathname,\n searchParams,\n pathParams\n )\n }\n\n const layoutRouterContext = useMemo(() => {\n return {\n parentTree: tree,\n parentCacheNode: cache,\n parentSegmentPath: null,\n parentParams: {},\n parentLoadingData: null,\n // This is the <Activity> \"name\" that shows up in the Suspense DevTools.\n // It represents the root of the app.\n debugNameContext: '/',\n // Root node always has `url`\n // Provided in AppTreeContext to ensure it can be overwritten in layout-router\n url: canonicalUrl,\n // Root segment is always active\n isActive: true,\n }\n }, [tree, cache, canonicalUrl])\n\n const globalLayoutRouterContext = useMemo(() => {\n return {\n tree,\n focusAndScrollRef,\n nextUrl,\n previousNextUrl,\n }\n }, [tree, focusAndScrollRef, nextUrl, previousNextUrl])\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.__NEXT_DEV_SERVER) {\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 // TODO(browser-variant): migrate to a .ts/.browser.ts split so the browser bundle drops the server branch; see scripts/generate-browser-variant-aliases.mjs\n // ast-grep-ignore: no-typeof-window-require-tsx\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 if (process.env.__NEXT_USE_OFFLINE) {\n const { OfflineProvider } =\n require('./use-offline') as typeof import('./use-offline')\n content = <OfflineProvider>{content}</OfflineProvider>\n }\n\n return (\n <>\n <HistoryUpdater appRouterState={state} />\n {process.env.TURBOPACK ? null : <RuntimeStylesForWebpack />}\n <NavigationPromisesContext.Provider\n value={instrumentedNavigationPromises}\n >\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 </NavigationPromisesContext.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\nlet runtimeStyles: Set<string> | undefined\nlet runtimeStyleChanged: Set<() => void> | undefined\nif (!process.env.TURBOPACK && typeof window !== 'undefined') {\n runtimeStyles = new Set<string>()\n runtimeStyleChanged = new Set<() => void>()\n\n globalThis._N_E_STYLE_LOAD = function (href: string) {\n if (!runtimeStyles || !runtimeStyleChanged) return Promise.resolve()\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}\n\nfunction RuntimeStylesForWebpack() {\n const [, forceUpdate] = React.useState(0)\n const renderedStylesSize = runtimeStyles?.size ?? 0\n useEffect(() => {\n if (!runtimeStyles || !runtimeStyleChanged) return\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 query = getAssetTokenQuery()\n return [...(runtimeStyles || [])].map((href, i) => (\n <link\n key={i}\n rel=\"stylesheet\"\n href={`${href}${query}`}\n // @ts-ignore\n precedence=\"next\"\n // TODO figure out crossOrigin and nonce\n // crossOrigin={TODO}\n // nonce={TODO}\n />\n ))\n}\n"],"names":["AppRouter","globalMutable","hasMissedTraversal","window","navigation","activationEntry","activation","entry","currentEntry","key","history","state","__NA","checkedMissedTraversalBeforeHistoryWrite","checkedMissedTraversalBeforeReplay","handlePopState","location","reload","startTransition","dispatchTraverseAction","href","__PRIVATE_NEXTJS_INTERNALS_TREE","HistoryUpdater","appRouterState","useInsertionEffect","process","env","__NEXT_APP_NAV_FAIL_HANDLING","next","__pendingUrl","undefined","tree","pushRef","canonicalUrl","renderedSearch","setLastCommittedTree","appHistoryState","historyState","preserveCustomHistoryState","pendingPush","createHrefFromUrl","URL","pushState","replaceState","useEffect","pingVisibleLinks","nextUrl","copyNextJsInternalHistoryState","data","currentState","Head","headCacheNode","head","prefetchHead","resolvedPrefetchRsc","useDeferredValue","Router","actionQueue","globalError","webSocket","staticIndicatorState","useActionQueue","searchParams","pathname","useMemo","url","hasBasePath","removeBasePath","NODE_ENV","cache","nd","router","publicAppRouterInstance","sourcePage","extractSourcePageFromFlightRouterState","__internal_src_page","handlePageShow","event","persisted","pendingMpaPath","dispatchAppRouterAction","type","ACTION_RESTORE","addEventListener","removeEventListener","handleUnhandledRedirect","error","reason","isRedirectError","preventDefault","getURLFromRedirectError","redirectType","getRedirectTypeFromError","push","replace","mpaNavigation","assign","unresolvedThenable","originalPushState","bind","originalReplaceState","applyUrlFromHistoryPushReplace","_unused","_N","onPopState","focusAndScrollRef","previousNextUrl","matchingHead","findHeadInCache","pathParams","getSelectedParams","instrumentedNavigationPromises","createRootNavigationPromises","require","layoutRouterContext","parentTree","parentCacheNode","parentSegmentPath","parentParams","parentLoadingData","debugNameContext","isActive","globalLayoutRouterContext","headKey","headKeyWithoutSearchParams","content","RedirectBoundary","RootLayoutBoundary","rsc","AppRouterAnnouncer","__NEXT_DEV_SERVER","DevRootHTTPAccessFallbackBoundary","HotReloader","default","RootErrorBoundary","errorComponent","errorStyles","__NEXT_USE_OFFLINE","OfflineProvider","TURBOPACK","RuntimeStylesForWebpack","NavigationPromisesContext","Provider","value","PathParamsContext","PathnameContext","SearchParamsContext","GlobalLayoutRouterContext","AppRouterContext","LayoutRouterContext","globalErrorState","useNavFailureHandler","DefaultGlobalError","runtimeStyles","runtimeStyleChanged","Set","globalThis","_N_E_STYLE_LOAD","Promise","resolve","len","size","add","forEach","cb","forceUpdate","React","useState","renderedStylesSize","changed","c","delete","query","getAssetTokenQuery","map","i","link","r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C;IACvC,MAAMC,qBAAqBf,eAAeQ,QAAQ;IAClDrH,IAAAA,gBAAS,EAAC;QACR,IAAI,CAAC6G,iBAAiB,CAACC,qBAAqB;QAC5C,MAAMe,UAAU,IAAMJ,YAAY,CAACK,IAAMA,IAAI;QAC7ChB,oBAAoBQ,GAAG,CAACO;QACxB,IAAID,uBAAuBf,cAAcQ,IAAI,EAAE;YAC7CQ;QACF;QACA,OAAO;YACLf,oBAAoBiB,MAAM,CAACF;QAC7B;IACF,GAAG;QAACD;QAAoBH;KAAY;IAEpC,MAAMO,QAAQC,IAAAA,gCAAkB;IAChC,OAAO;WAAKpB,iBAAiB,EAAE;KAAE,CAACqB,GAAG,CAAC,CAAC1J,MAAM2J,kBAC3C,qBAACC;YAECC,KAAI;YACJ7J,MAAM,GAAGA,OAAOwJ,OAAO;YACvB,aAAa;YACbM,YAAW;WAJNH;AAUX","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/client/components/app-router.tsx"],"sourcesContent":["import 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 { CacheNode } from '../../shared/lib/app-router-types'\nimport { ACTION_RESTORE } from './router-reducer/router-reducer-types'\nimport type {\n AppHistoryState,\n AppRouterState,\n} from './router-reducer/router-reducer-types'\nimport { createHrefFromUrl } from './router-reducer/create-href-from-url'\nimport {\n SearchParamsContext,\n PathnameContext,\n PathParamsContext,\n NavigationPromisesContext,\n type NavigationPromises,\n} from '../../shared/lib/hooks-client-context.shared-runtime'\nimport { dispatchAppRouterAction, useActionQueue } from './use-action-queue'\nimport { setLastCommittedTree } from './router-reducer/reducers/committed-state'\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 {\n extractSourcePageFromFlightRouterState,\n getSelectedParams,\n} 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 } 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'\nimport { getAssetTokenQuery } from '../../shared/lib/deployment-id'\n\nconst globalMutable: {\n pendingMpaPath?: string\n} = {}\n\n// A Back/Forward press before the router's popstate listener exists moves the\n// browser to a different history entry than the one the document was activated\n// on, and the resulting popstate fires with nobody listening. The activation\n// entry is fixed for the document's lifetime and entry keys are stable across\n// replaceState, so until the listener is installed a key mismatch means a\n// traversal went unobserved.\nfunction hasMissedTraversal(): boolean {\n if (typeof window.navigation === 'undefined') {\n return false\n }\n const activationEntry = window.navigation.activation?.entry\n const currentEntry = window.navigation.currentEntry\n return (\n activationEntry != null &&\n currentEntry != null &&\n activationEntry.key !== currentEntry.key &&\n // Only entries written by the app router can be restored; on any other\n // entry the traversal is left unhandled, as before.\n window.history.state?.__NA === true\n )\n}\n\nlet checkedMissedTraversalBeforeHistoryWrite = false\nlet checkedMissedTraversalBeforeReplay = false\n\n/**\n * Handles a popstate event (or one that was missed before hydration).\n * By default dispatches ACTION_RESTORE, however if the history entry was not\n * pushed/replaced by app-router it will reload the page.\n * That case can happen when the old router injected the history entry.\n */\nfunction handlePopState(state: PopStateEvent['state']): void {\n if (!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 (!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 state.__PRIVATE_NEXTJS_INTERNALS_TREE\n )\n })\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, renderedSearch } = appRouterState\n\n if (!checkedMissedTraversalBeforeHistoryWrite) {\n checkedMissedTraversalBeforeHistoryWrite = true\n if (hasMissedTraversal()) {\n // Skip the write: it would overwrite the traversed-to entry's state.\n // The tree was rendered even though the history write is skipped.\n setLastCommittedTree(tree)\n return\n }\n }\n\n const appHistoryState: AppHistoryState = {\n tree,\n renderedSearch,\n }\n\n // TODO: Use Navigation API if available\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: appHistoryState,\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\n setLastCommittedTree(tree)\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 pingVisibleLinks(appRouterState.nextUrl, appRouterState.tree)\n }, [appRouterState.nextUrl, appRouterState.tree])\n\n return null\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 const { cache, 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 tree,\n }\n }, [cache, tree])\n }\n\n useEffect(() => {\n const sourcePage = extractSourcePageFromFlightRouterState(state.tree)\n\n if (sourcePage !== undefined) {\n window.next.__internal_src_page = sourcePage\n } else {\n delete window.next.__internal_src_page\n }\n }, [state.tree])\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 historyState: 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 === '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 appHistoryState: AppHistoryState | 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 historyState: appHistoryState,\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 // TODO: Warn when Navigation API is available (navigation.navigate() should be used)\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 // TODO: Warn when Navigation API is available (navigation.navigate() should be used)\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 const onPopState = (event: PopStateEvent) => handlePopState(event.state)\n\n window.addEventListener('popstate', onPopState)\n\n if (!checkedMissedTraversalBeforeReplay) {\n checkedMissedTraversalBeforeReplay = true\n if (hasMissedTraversal()) {\n handlePopState(window.history.state)\n }\n }\n\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, scrollRef, previousNextUrl } = 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 // Create instrumented promises for navigation hooks (dev-only)\n // These are specially instrumented promises to show in the Suspense DevTools\n // Promises are cached outside of render to survive suspense retries.\n let instrumentedNavigationPromises: NavigationPromises | null = null\n if (process.env.NODE_ENV !== 'production') {\n const { createRootNavigationPromises } =\n require('./navigation-devtools') as typeof import('./navigation-devtools')\n\n instrumentedNavigationPromises = createRootNavigationPromises(\n tree,\n pathname,\n searchParams,\n pathParams\n )\n }\n\n const layoutRouterContext = useMemo(() => {\n return {\n parentTree: tree,\n parentCacheNode: cache,\n parentSegmentPath: null,\n parentParams: {},\n parentLoadingData: null,\n // This is the <Activity> \"name\" that shows up in the Suspense DevTools.\n // It represents the root of the app.\n debugNameContext: '/',\n // Root node always has `url`\n // Provided in AppTreeContext to ensure it can be overwritten in layout-router\n url: canonicalUrl,\n // Root segment is always active\n isActive: true,\n }\n }, [tree, cache, canonicalUrl])\n\n const globalLayoutRouterContext = useMemo(() => {\n return {\n tree,\n scrollRef,\n nextUrl,\n previousNextUrl,\n }\n }, [tree, scrollRef, nextUrl, previousNextUrl])\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.__NEXT_DEV_SERVER) {\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 // TODO(browser-variant): migrate to a .ts/.browser.ts split so the browser bundle drops the server branch; see scripts/generate-browser-variant-aliases.mjs\n // ast-grep-ignore: no-typeof-window-require-tsx\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 if (process.env.__NEXT_USE_OFFLINE) {\n const { OfflineProvider } =\n require('./use-offline') as typeof import('./use-offline')\n content = <OfflineProvider>{content}</OfflineProvider>\n }\n\n return (\n <>\n <HistoryUpdater appRouterState={state} />\n {process.env.TURBOPACK ? null : <RuntimeStylesForWebpack />}\n <NavigationPromisesContext.Provider\n value={instrumentedNavigationPromises}\n >\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 </NavigationPromisesContext.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\nlet runtimeStyles: Set<string> | undefined\nlet runtimeStyleChanged: Set<() => void> | undefined\nif (!process.env.TURBOPACK && typeof window !== 'undefined') {\n runtimeStyles = new Set<string>()\n runtimeStyleChanged = new Set<() => void>()\n\n globalThis._N_E_STYLE_LOAD = function (href: string) {\n if (!runtimeStyles || !runtimeStyleChanged) return Promise.resolve()\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}\n\nfunction RuntimeStylesForWebpack() {\n const [, forceUpdate] = React.useState(0)\n const renderedStylesSize = runtimeStyles?.size ?? 0\n useEffect(() => {\n if (!runtimeStyles || !runtimeStyleChanged) return\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 query = getAssetTokenQuery()\n return [...(runtimeStyles || [])].map((href, i) => (\n <link\n key={i}\n rel=\"stylesheet\"\n href={`${href}${query}`}\n // @ts-ignore\n precedence=\"next\"\n // TODO figure out crossOrigin and nonce\n // crossOrigin={TODO}\n // nonce={TODO}\n />\n ))\n}\n"],"names":["AppRouter","globalMutable","hasMissedTraversal","window","navigation","activationEntry","activation","entry","currentEntry","key","history","state","__NA","checkedMissedTraversalBeforeHistoryWrite","checkedMissedTraversalBeforeReplay","handlePopState","location","reload","startTransition","dispatchTraverseAction","href","__PRIVATE_NEXTJS_INTERNALS_TREE","HistoryUpdater","appRouterState","useInsertionEffect","process","env","__NEXT_APP_NAV_FAIL_HANDLING","next","__pendingUrl","undefined","tree","pushRef","canonicalUrl","renderedSearch","setLastCommittedTree","appHistoryState","historyState","preserveCustomHistoryState","pendingPush","createHrefFromUrl","URL","pushState","replaceState","useEffect","pingVisibleLinks","nextUrl","copyNextJsInternalHistoryState","data","currentState","Head","headCacheNode","head","prefetchHead","resolvedPrefetchRsc","useDeferredValue","Router","actionQueue","globalError","webSocket","staticIndicatorState","useActionQueue","searchParams","pathname","useMemo","url","hasBasePath","removeBasePath","NODE_ENV","cache","nd","router","publicAppRouterInstance","sourcePage","extractSourcePageFromFlightRouterState","__internal_src_page","handlePageShow","event","persisted","pendingMpaPath","dispatchAppRouterAction","type","ACTION_RESTORE","addEventListener","removeEventListener","handleUnhandledRedirect","error","reason","isRedirectError","preventDefault","getURLFromRedirectError","redirectType","getRedirectTypeFromError","push","replace","mpaNavigation","assign","unresolvedThenable","originalPushState","bind","originalReplaceState","applyUrlFromHistoryPushReplace","_unused","_N","onPopState","scrollRef","previousNextUrl","matchingHead","findHeadInCache","pathParams","getSelectedParams","instrumentedNavigationPromises","createRootNavigationPromises","require","layoutRouterContext","parentTree","parentCacheNode","parentSegmentPath","parentParams","parentLoadingData","debugNameContext","isActive","globalLayoutRouterContext","headKey","headKeyWithoutSearchParams","content","RedirectBoundary","RootLayoutBoundary","rsc","AppRouterAnnouncer","__NEXT_DEV_SERVER","DevRootHTTPAccessFallbackBoundary","HotReloader","default","RootErrorBoundary","errorComponent","errorStyles","__NEXT_USE_OFFLINE","OfflineProvider","TURBOPACK","RuntimeStylesForWebpack","NavigationPromisesContext","Provider","value","PathParamsContext","PathnameContext","SearchParamsContext","GlobalLayoutRouterContext","AppRouterContext","LayoutRouterContext","globalErrorState","useNavFailureHandler","DefaultGlobalError","runtimeStyles","runtimeStyleChanged","Set","globalThis","_N_E_STYLE_LOAD","Promise","resolve","len","size","add","forEach","cb","forceUpdate","React","useState","renderedStylesSize","changed","c","delete","query","getAssetTokenQuery","map","i","link","rel","precedence"],"mappings":";;;;+BA+mBA;;;eAAwBA;;;;;;iEAzmBjB;+CAKA;oCAEwB;mCAKG;iDAO3B;gCACiD;gCACnB;oCACF;kCACF;iCACD;oCACG;gCACJ;6BACH;oCAIrB;mCAC8B;mCAM9B;0BAC2D;+BAClC;uBACC;4EACH;sEACC;oCACI;8BAEA;AAEnC,MAAMC,gBAEF,CAAC;AAEL,8EAA8E;AAC9E,+EAA+E;AAC/E,6EAA6E;AAC7E,8EAA8E;AAC9E,0EAA0E;AAC1E,6BAA6B;AAC7B,SAASC;IACP,IAAI,OAAOC,OAAOC,UAAU,KAAK,aAAa;QAC5C,OAAO;IACT;IACA,MAAMC,kBAAkBF,OAAOC,UAAU,CAACE,UAAU,EAAEC;IACtD,MAAMC,eAAeL,OAAOC,UAAU,CAACI,YAAY;IACnD,OACEH,mBAAmB,QACnBG,gBAAgB,QAChBH,gBAAgBI,GAAG,KAAKD,aAAaC,GAAG,IACxC,uEAAuE;IACvE,oDAAoD;IACpDN,OAAOO,OAAO,CAACC,KAAK,EAAEC,SAAS;AAEnC;AAEA,IAAIC,2CAA2C;AAC/C,IAAIC,qCAAqC;AAEzC;;;;;CAKC,GACD,SAASC,eAAeJ,KAA6B;IACnD,IAAI,CAACA,OAAO;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AAa;IAC3DsJ,gBAAgB,IAAIE;IACpBD,sBAAsB,IAAIC;IAE1BC,WAAWC,eAAe,GAAG,SAAUzI,IAAY;QACjD,IAAI,CAACqI,iBAAiB,CAACC,qBAAqB,OAAOI,QAAQC,OAAO;QAClE,IAAIC,MAAMP,cAAcQ,IAAI;QAC5BR,cAAcS,GAAG,CAAC9I;QAClB,IAAIqI,cAAcQ,IAAI,KAAKD,KAAK;YAC9BN,oBAAoBS,OAAO,CAAC,CAACC,KAAOA;QACtC;QACA,4CAA4C;QAC5C,gFAAgF;QAChF,OAAON,QAAQC,OAAO;IACxB;AACF;AAEA,SAASnB;IACP,MAAM,GAAGyB,YAAY,GAAGC,cAAK,CAACC,QAAQ,CAAC;IACvC,MAAMC,qBAAqBf,eAAeQ,QAAQ;IAClDrH,IAAAA,gBAAS,EAAC;QACR,IAAI,CAAC6G,iBAAiB,CAACC,qBAAqB;QAC5C,MAAMe,UAAU,IAAMJ,YAAY,CAACK,IAAMA,IAAI;QAC7ChB,oBAAoBQ,GAAG,CAACO;QACxB,IAAID,uBAAuBf,cAAcQ,IAAI,EAAE;YAC7CQ;QACF;QACA,OAAO;YACLf,oBAAoBiB,MAAM,CAACF;QAC7B;IACF,GAAG;QAACD;QAAoBH;KAAY;IAEpC,MAAMO,QAAQC,IAAAA,gCAAkB;IAChC,OAAO;WAAKpB,iBAAiB,EAAE;KAAE,CAACqB,GAAG,CAAC,CAAC1J,MAAM2J,kBAC3C,qBAACC;YAECC,KAAI;YACJ7J,MAAM,GAAGA,OAAOwJ,OAAO;YACvB,aAAa;YACbM,YAAW;WAJNH;AAUX","ignoreList":[0]} |
@@ -100,10 +100,10 @@ 'use client'; | ||
| * Does not focus the first host descendant. | ||
| */ function InnerScrollAndMaybeFocusHandler(props) { | ||
| */ function InnerScrollHandler(props) { | ||
| const childrenRef = _react.default.useRef(null); | ||
| (0, _react.useLayoutEffect)(()=>{ | ||
| const { focusAndScrollRef, cacheNode } = props; | ||
| const scrollRef = focusAndScrollRef.forceScroll ? focusAndScrollRef.scrollRef : cacheNode.scrollRef; | ||
| const { scrollRef: scrollHandlerRef, cacheNode } = props; | ||
| const scrollRef = scrollHandlerRef.forceScroll ? scrollHandlerRef.scrollRef : cacheNode.scrollRef; | ||
| if (scrollRef === null || !scrollRef.current) return; | ||
| let instance = null; | ||
| const hashFragment = focusAndScrollRef.hashFragment; | ||
| const hashFragment = scrollHandlerRef.hashFragment; | ||
| if (hashFragment) { | ||
@@ -115,4 +115,4 @@ instance = getHashFragmentDomNode(hashFragment); | ||
| scrollRef.current = false; | ||
| focusAndScrollRef.onlyHashChange = false; | ||
| focusAndScrollRef.hashFragment = null; | ||
| scrollHandlerRef.onlyHashChange = false; | ||
| scrollHandlerRef.hashFragment = null; | ||
| return; | ||
@@ -179,3 +179,3 @@ } | ||
| dontForceLayout: true, | ||
| onlyHashChange: focusAndScrollRef.onlyHashChange | ||
| onlyHashChange: scrollHandlerRef.onlyHashChange | ||
| }); | ||
@@ -186,4 +186,4 @@ if (!didHandleScroll) { | ||
| // Mutate after scrolling so that it can be read by `disableSmoothScrollDuringRouteTransition` | ||
| focusAndScrollRef.onlyHashChange = false; | ||
| focusAndScrollRef.hashFragment = null; | ||
| scrollHandlerRef.onlyHashChange = false; | ||
| scrollHandlerRef.hashFragment = null; | ||
| }, // Used to run on every commit. We may be able to be smarter about this | ||
@@ -197,3 +197,3 @@ // but be prepared for lots of manual testing. | ||
| } | ||
| function ScrollAndMaybeFocusHandler({ children, cacheNode }) { | ||
| function ScrollHandler({ children, cacheNode }) { | ||
| const context = (0, _react.useContext)(_approutercontextsharedruntime.GlobalLayoutRouterContext); | ||
@@ -207,4 +207,4 @@ if (!context) { | ||
| } | ||
| return /*#__PURE__*/ (0, _jsxruntime.jsx)(InnerScrollAndMaybeFocusHandler, { | ||
| focusAndScrollRef: context.focusAndScrollRef, | ||
| return /*#__PURE__*/ (0, _jsxruntime.jsx)(InnerScrollHandler, { | ||
| scrollRef: context.scrollRef, | ||
| cacheNode: cacheNode, | ||
@@ -478,3 +478,3 @@ children: children | ||
| const debugNameToDisplay = isVirtual ? undefined : debugNameContext; | ||
| let templateValue = /*#__PURE__*/ (0, _jsxruntime.jsxs)(ScrollAndMaybeFocusHandler, { | ||
| let templateValue = /*#__PURE__*/ (0, _jsxruntime.jsxs)(ScrollHandler, { | ||
| cacheNode: cacheNode, | ||
@@ -481,0 +481,0 @@ children: [ |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/client/components/layout-router.tsx"],"sourcesContent":["'use client'\n\nimport type { CacheNode } from '../../shared/lib/app-router-types'\nimport type { LoadingModuleData } from '../../shared/lib/app-router-types'\nimport type {\n FlightRouterState,\n FlightSegmentPath,\n Segment,\n} from '../../shared/lib/app-router-types'\nimport type { ErrorComponent } from './error-boundary'\nimport type { FocusAndScrollRef } from './router-reducer/router-reducer-types'\n\nimport React, {\n Activity,\n Fragment,\n useContext,\n use,\n Suspense,\n useDeferredValue,\n useLayoutEffect,\n type FragmentInstance,\n type JSX,\n type ActivityProps,\n} from 'react'\nimport {\n LayoutRouterContext,\n GlobalLayoutRouterContext,\n TemplateContext,\n} from '../../shared/lib/app-router-context.shared-runtime'\nimport { unresolvedThenable } from './unresolved-thenable'\nimport { ErrorBoundary } from './error-boundary'\nimport { disableSmoothScrollDuringRouteTransition } from '../../shared/lib/router/utils/disable-smooth-scroll'\nimport { RedirectBoundary } from './redirect-boundary'\nimport { HTTPAccessFallbackBoundary } from './http-access-fallback/error-boundary'\nimport {\n InstantValidationBoundaryContext,\n RenderValidationBoundaryAtThisLevel,\n} from './instant-validation/boundary'\nimport { createRouterCacheKey } from './router-reducer/create-router-cache-key'\nimport {\n useRouterBFCache,\n type RouterBFCacheEntry,\n} from './bfcache-state-manager'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport {\n NavigationPromisesContext,\n type NavigationPromises,\n} from '../../shared/lib/hooks-client-context.shared-runtime'\nimport { getParamValueFromCacheKey } from '../route-params'\nimport type { Params } from '../../server/request/params'\nimport { isDeferredRsc } from './router-reducer/ppr-navigations'\n\nconst enum ScrollTargetState {\n NoClientRects,\n InViewport,\n OutOfViewport,\n}\n\n/**\n * Resolve the root scroll padding used by the viewport check.\n *\n * Computed lengths serialize as pixels, but percentages remain relative to\n * the scrollport. Preserve the existing behavior for values that still\n * contain unresolved CSS math.\n */\nfunction getScrollPaddingTopInPixels(\n htmlElement: HTMLElement,\n viewportHeight: number\n): number {\n const scrollPaddingTop = getComputedStyle(htmlElement).scrollPaddingTop\n const value = Number.parseFloat(scrollPaddingTop)\n\n if (!Number.isFinite(value) || value < 0) {\n return 0\n }\n\n if (scrollPaddingTop.endsWith('px')) {\n return value\n }\n\n if (scrollPaddingTop.endsWith('%')) {\n return (value / 100) * viewportHeight\n }\n\n return 0\n}\n\n/**\n * Check where the top corner of the HTMLElement is relative to the usable\n * viewport.\n *\n * Scroll padding is resolved lazily so an empty Fragment does not trigger a\n * computed style read. The caller caches the value for the second check.\n */\nfunction getScrollTargetState(\n instance: HTMLElement | FragmentInstance,\n viewportHeight: number,\n getScrollPaddingTop: () => number\n): ScrollTargetState {\n const rects = instance.getClientRects()\n if (rects.length === 0) {\n return ScrollTargetState.NoClientRects\n }\n let elementTop = Number.POSITIVE_INFINITY\n for (let i = 0; i < rects.length; i++) {\n const rect = rects[i]\n if (rect.top < elementTop) {\n elementTop = rect.top\n }\n }\n return elementTop >= getScrollPaddingTop() && elementTop <= viewportHeight\n ? ScrollTargetState.InViewport\n : ScrollTargetState.OutOfViewport\n}\n\n/**\n * Find the DOM node for a hash fragment.\n * If `top` the page has to scroll to the top of the page. This mirrors the browser's behavior.\n * If the hash fragment is an id, the page has to scroll to the element with that id.\n * If the hash fragment is a name, the page has to scroll to the first element with that name.\n */\nfunction getHashFragmentDomNode(hashFragment: string) {\n // If the hash fragment is `top` the page has to scroll to the top of the page.\n if (hashFragment === 'top') {\n return document.body\n }\n\n // If the hash fragment is an id, the page has to scroll to the element with that id.\n return (\n document.getElementById(hashFragment) ??\n // If the hash fragment is a name, the page has to scroll to the first element with that name.\n document.getElementsByName(hashFragment)[0] ??\n null\n )\n}\ninterface ScrollAndMaybeFocusHandlerProps {\n focusAndScrollRef: FocusAndScrollRef\n children: React.ReactNode\n cacheNode: CacheNode\n}\n\n/**\n * Uses Fragment refs for scrolling.\n * Does not focus the first host descendant.\n */\nfunction InnerScrollAndMaybeFocusHandler(\n props: ScrollAndMaybeFocusHandlerProps\n) {\n const childrenRef = React.useRef<FragmentInstance>(null)\n\n useLayoutEffect(\n () => {\n const { focusAndScrollRef, cacheNode } = props\n\n const scrollRef = focusAndScrollRef.forceScroll\n ? focusAndScrollRef.scrollRef\n : cacheNode.scrollRef\n if (scrollRef === null || !scrollRef.current) return\n\n let instance: FragmentInstance | HTMLElement | null = null\n const hashFragment = focusAndScrollRef.hashFragment\n\n if (hashFragment) {\n instance = getHashFragmentDomNode(hashFragment)\n if (instance === null) {\n // A missing hash target is still a handled scroll intent. Do not\n // fall back to the route Fragment or leave the intent pending.\n scrollRef.current = false\n focusAndScrollRef.onlyHashChange = false\n focusAndScrollRef.hashFragment = null\n return\n }\n } else {\n instance = childrenRef.current\n }\n\n // If there is no DOM node this layout-router level is skipped. It'll be handled higher-up in the tree.\n if (instance === null) {\n return\n }\n\n let didHandleScroll = false\n\n disableSmoothScrollDuringRouteTransition(\n () => {\n const htmlElement = document.documentElement\n let viewportHeight: number | null = null\n let initialTargetState: ScrollTargetState | null = null\n let scrollPaddingTop: number | null = null\n const getScrollPaddingTop = () => {\n if (scrollPaddingTop === null) {\n // Reuse the style and layout update from the geometry read.\n scrollPaddingTop = getScrollPaddingTopInPixels(\n htmlElement,\n viewportHeight!\n )\n }\n return scrollPaddingTop\n }\n\n if (!hashFragment) {\n // Store the current viewport height because reading `clientHeight` causes a reflow,\n // and it won't change during this function.\n viewportHeight = htmlElement.clientHeight\n initialTargetState = getScrollTargetState(\n instance,\n viewportHeight,\n getScrollPaddingTop\n )\n\n // An empty Fragment is not a scroll target. In particular, avoid\n // React's sibling fallback and leave the scroll signal available\n // for another changed segment.\n if (initialTargetState === ScrollTargetState.NoClientRects) {\n return\n }\n }\n\n didHandleScroll = true\n\n // Mark as scrolled so no other segment scrolls for this navigation.\n scrollRef.current = false\n\n // This handler intentionally leaves focus untouched; resetting focus on\n // navigation is deferred.\n\n // In case of hash scroll, we only need to scroll the element into view\n if (hashFragment) {\n instance.scrollIntoView()\n\n return\n }\n\n // If the element's top edge is already in the viewport, exit early.\n if (initialTargetState === ScrollTargetState.InViewport) {\n return\n }\n\n // Otherwise, try scrolling go the top of the document to be backward compatible with pages\n // scrollIntoView() called on `<html/>` element scrolls horizontally on chrome and firefox (that shouldn't happen)\n // We could use it to scroll horizontally following RTL but that also seems to be broken - it will always scroll left\n // scrollLeft = 0 also seems to ignore RTL and manually checking for RTL is too much hassle so we will scroll just vertically\n htmlElement.scrollTop = 0\n\n // Scroll to domNode if domNode is not in viewport when scrolled to top of document\n if (\n getScrollTargetState(\n instance,\n viewportHeight!,\n getScrollPaddingTop\n ) === ScrollTargetState.OutOfViewport\n ) {\n // Scroll into view doesn't scroll horizontally by default when not needed\n instance.scrollIntoView()\n }\n },\n {\n // We will force layout by querying domNode position\n dontForceLayout: true,\n onlyHashChange: focusAndScrollRef.onlyHashChange,\n }\n )\n\n if (!didHandleScroll) {\n return\n }\n\n // Mutate after scrolling so that it can be read by `disableSmoothScrollDuringRouteTransition`\n focusAndScrollRef.onlyHashChange = false\n focusAndScrollRef.hashFragment = null\n },\n // Used to run on every commit. We may be able to be smarter about this\n // but be prepared for lots of manual testing.\n undefined\n )\n\n return <Fragment ref={childrenRef}>{props.children}</Fragment>\n}\n\nfunction ScrollAndMaybeFocusHandler({\n children,\n cacheNode,\n}: {\n children: React.ReactNode\n cacheNode: CacheNode\n}) {\n const context = useContext(GlobalLayoutRouterContext)\n if (!context) {\n throw new Error('invariant global layout router not mounted')\n }\n\n return (\n <InnerScrollAndMaybeFocusHandler\n focusAndScrollRef={context.focusAndScrollRef}\n cacheNode={cacheNode}\n >\n {children}\n </InnerScrollAndMaybeFocusHandler>\n )\n}\n\n/**\n * InnerLayoutRouter handles rendering the provided segment based on the cache.\n */\nfunction InnerLayoutRouter({\n tree,\n segmentPath,\n debugNameContext,\n cacheNode: maybeCacheNode,\n params,\n url,\n isActive,\n}: {\n tree: FlightRouterState\n segmentPath: FlightSegmentPath\n debugNameContext: string\n cacheNode: CacheNode | null\n params: Params\n url: string\n isActive: boolean\n}) {\n const context = useContext(GlobalLayoutRouterContext)\n const parentNavPromises = useContext(NavigationPromisesContext)\n\n if (!context) {\n throw new Error('invariant global layout router not mounted')\n }\n\n const cacheNode =\n maybeCacheNode !== null\n ? maybeCacheNode\n : // This segment is not in the cache. Suspend indefinitely.\n //\n // This should only be reachable for inactive/hidden segments, during\n // prerendering The active segment should always be consistent with the\n // CacheNode tree. Regardless, if we don't have a matching CacheNode, we\n // must suspend rather than render nothing, to prevent showing an\n // inconsistent route.\n\n (use(unresolvedThenable) as never)\n\n // `rsc` represents the renderable node for this segment.\n\n // If this segment has a `prefetchRsc`, it's the statically prefetched data.\n // We should use that on initial render instead of `rsc`. Then we'll switch\n // to `rsc` when the dynamic response streams in.\n //\n // If no prefetch data is available, then we go straight to rendering `rsc`.\n const resolvedPrefetchRsc =\n cacheNode.prefetchRsc !== null ? cacheNode.prefetchRsc : cacheNode.rsc\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 const rsc: any = useDeferredValue(cacheNode.rsc, resolvedPrefetchRsc)\n\n // `rsc` is either a React node or a promise for a React node, except we\n // special case `null` to represent that this segment's data is missing. If\n // it's a promise, we need to unwrap it so we can determine whether or not the\n // data is missing.\n let resolvedRsc: React.ReactNode\n if (isDeferredRsc(rsc)) {\n const unwrappedRsc = use(rsc)\n if (unwrappedRsc === null) {\n // If the promise was resolved to `null`, it means the data for this\n // segment was not returned by the server. Suspend indefinitely. When this\n // happens, the router is responsible for triggering a new state update to\n // un-suspend this segment.\n use(unresolvedThenable) as never\n }\n resolvedRsc = unwrappedRsc\n } else {\n // This is not a deferred RSC promise. Don't need to unwrap it.\n if (rsc === null) {\n use(unresolvedThenable) as never\n }\n resolvedRsc = rsc\n }\n\n // In dev, we create a NavigationPromisesContext containing the instrumented promises that provide\n // `useSelectedLayoutSegment` and `useSelectedLayoutSegments`.\n // Promises are cached outside of render to survive suspense retries.\n let navigationPromises: NavigationPromises | null = null\n if (process.env.NODE_ENV !== 'production') {\n const { createNestedLayoutNavigationPromises } =\n require('./navigation-devtools') as typeof import('./navigation-devtools')\n\n navigationPromises = createNestedLayoutNavigationPromises(\n tree,\n parentNavPromises\n )\n }\n\n let children = resolvedRsc\n\n if (navigationPromises) {\n children = (\n <NavigationPromisesContext.Provider value={navigationPromises}>\n {resolvedRsc}\n </NavigationPromisesContext.Provider>\n )\n }\n\n children = (\n // The layout router context narrows down tree and childNodes at each level.\n <LayoutRouterContext.Provider\n value={{\n parentTree: tree,\n parentCacheNode: cacheNode,\n parentSegmentPath: segmentPath,\n parentParams: params,\n // This is always set to null as we enter a child segment. It's\n // populated by LoadingBoundaryProvider the next time we reach a\n // loading boundary.\n parentLoadingData: null,\n debugNameContext: debugNameContext,\n\n // TODO-APP: overriding of url for parallel routes\n url: url,\n isActive: isActive,\n }}\n >\n {children}\n </LayoutRouterContext.Provider>\n )\n\n return children\n}\n\nexport function LoadingBoundaryProvider({\n loading,\n children,\n}: {\n loading: LoadingModuleData\n children: React.ReactNode\n}) {\n // Provides the data needed to render a loading.tsx boundary, via context.\n //\n // loading.tsx creates a Suspense boundary around each of a layout's child\n // slots. (Might be bit confusing to think about the data flow, but: if\n // loading.tsx and layout.tsx are in the same directory, they are assigned\n // to the same CacheNode.)\n //\n // This provider component does not render the Suspense boundary directly;\n // that's handled by LoadingBoundary.\n //\n // TODO: For simplicity, we should combine this provider with LoadingBoundary\n // and render the Suspense boundary directly. The only real benefit of doing\n // it separately is so that when there are multiple parallel routes, we only\n // send the boundary data once, rather than once per child. But that's a\n // negligible benefit and can be achieved via caching instead.\n const parentContext = use(LayoutRouterContext)\n if (parentContext === null) {\n return children\n }\n // All values except for parentLoadingData are the same as the parent context.\n return (\n <LayoutRouterContext.Provider\n value={{\n parentTree: parentContext.parentTree,\n parentCacheNode: parentContext.parentCacheNode,\n parentSegmentPath: parentContext.parentSegmentPath,\n parentParams: parentContext.parentParams,\n parentLoadingData: loading,\n debugNameContext: parentContext.debugNameContext,\n url: parentContext.url,\n isActive: parentContext.isActive,\n }}\n >\n {children}\n </LayoutRouterContext.Provider>\n )\n}\n\n/**\n * Renders suspense boundary with the provided \"loading\" property as the fallback.\n * If no loading property is provided it renders the children without a suspense boundary.\n */\nfunction LoadingBoundary({\n name,\n loading,\n children,\n}: {\n name: ActivityProps['name']\n loading: LoadingModuleData | null\n children: React.ReactNode\n}): JSX.Element {\n // TODO: For LoadingBoundary, and the other built-in boundary types, don't\n // wrap in an extra function component if no user-defined boundary is\n // provided. In other words, inline this conditional wrapping logic into\n // the parent component. More efficient and keeps unnecessary junk out of\n // the component stack.\n if (loading !== null) {\n const loadingRsc = loading[0]\n const loadingStyles = loading[1]\n const loadingScripts = loading[2]\n return (\n <Suspense\n name={name}\n fallback={\n <>\n {loadingStyles}\n {loadingScripts}\n {loadingRsc}\n </>\n }\n >\n {children}\n </Suspense>\n )\n }\n\n return <>{children}</>\n}\n\n/**\n * OuterLayoutRouter handles the current segment as well as <Offscreen> rendering of other segments.\n * It can be rendered next to each other with a different `parallelRouterKey`, allowing for Parallel routes.\n */\nexport default function OuterLayoutRouter({\n parallelRouterKey,\n error,\n errorStyles,\n errorScripts,\n templateStyles,\n templateScripts,\n template,\n notFound,\n forbidden,\n unauthorized,\n segmentViewBoundaries,\n}: {\n parallelRouterKey: string\n error: ErrorComponent | undefined\n errorStyles: React.ReactNode | undefined\n errorScripts: React.ReactNode | undefined\n templateStyles: React.ReactNode | undefined\n templateScripts: React.ReactNode | undefined\n template: React.ReactNode\n notFound: React.ReactNode | undefined\n forbidden: React.ReactNode | undefined\n unauthorized: React.ReactNode | undefined\n segmentViewBoundaries?: React.ReactNode\n}) {\n const context = useContext(LayoutRouterContext)\n if (!context) {\n throw new Error('invariant expected layout router to be mounted')\n }\n\n const {\n parentTree,\n parentCacheNode,\n parentSegmentPath,\n parentParams,\n parentLoadingData,\n url,\n isActive,\n debugNameContext,\n } = context\n\n // Get the CacheNode for this segment by reading it from the parent segment's\n // child map.\n const parentTreeSegment = parentTree[0]\n const segmentPath =\n parentSegmentPath === null\n ? // TODO: The root segment value is currently omitted from the segment\n // path. This has led to a bunch of special cases scattered throughout\n // the code. We should clean this up.\n [parallelRouterKey]\n : parentSegmentPath.concat([parentTreeSegment, parallelRouterKey])\n\n // The \"state\" key of a segment is the one passed to React — it represents the\n // identity of the UI tree. Whenever the state key changes, the tree is\n // recreated and the state is reset. In the App Router model, search params do\n // not cause state to be lost, so two segments with the same segment path but\n // different search params should have the same state key.\n //\n // The \"cache\" key of a segment, however, *does* include the search params, if\n // it's possible that the segment accessed the search params on the server.\n // (This only applies to page segments; layout segments cannot access search\n // params on the server.)\n const activeTree = parentTree[1][parallelRouterKey]\n const maybeParentSlots = parentCacheNode.slots\n if (activeTree === undefined || maybeParentSlots === null) {\n // Could not find a matching segment. The client tree is inconsistent with\n // the server tree. Suspend indefinitely; the router will have already\n // detected the inconsistency when handling the server response, and\n // triggered a refresh of the page to recover.\n use(unresolvedThenable) as never\n }\n\n let maybeValidationBoundaryId: string | null = null\n if (typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS) {\n maybeValidationBoundaryId = use(InstantValidationBoundaryContext)\n }\n\n const activeSegment = activeTree[0]\n const activeCacheNode = maybeParentSlots![parallelRouterKey] ?? null\n const activeStateKey = createRouterCacheKey(activeSegment, true) // no search params\n\n // At each level of the route tree, not only do we render the currently\n // active segment — we also render the last N segments that were active at\n // this level inside a hidden <Activity> boundary, to preserve their state\n // if or when the user navigates to them again.\n //\n // bfcacheEntry is a linked list of FlightRouterStates.\n let bfcacheEntry: RouterBFCacheEntry | null = useRouterBFCache(\n activeTree,\n activeCacheNode,\n activeStateKey\n )\n let children: Array<React.ReactNode> = []\n do {\n const tree = bfcacheEntry.tree\n const cacheNode = bfcacheEntry.cacheNode\n const stateKey = bfcacheEntry.stateKey\n const segment = tree[0]\n\n /*\n - Error boundary\n - Only renders error boundary if error component is provided.\n - Rendered for each segment to ensure they have their own error state.\n - When gracefully degrade for bots, skip rendering error boundary.\n - Loading boundary\n - Only renders suspense boundary if loading components is provided.\n - Rendered for each segment to ensure they have their own loading state.\n - Passed to the router during rendering to ensure it can be immediately rendered when suspending on a Flight fetch.\n */\n\n let segmentBoundaryTriggerNode: React.ReactNode = null\n let segmentViewStateNode: React.ReactNode = null\n if (process.env.NODE_ENV !== 'production') {\n const { SegmentBoundaryTriggerNode, SegmentViewStateNode } =\n require('../../next-devtools/userspace/app/segment-explorer-node') as typeof import('../../next-devtools/userspace/app/segment-explorer-node')\n\n const pagePrefix = normalizeAppPath(url)\n segmentViewStateNode = (\n <SegmentViewStateNode key={pagePrefix} page={pagePrefix} />\n )\n\n segmentBoundaryTriggerNode = (\n <>\n <SegmentBoundaryTriggerNode />\n </>\n )\n }\n\n let params = parentParams\n if (Array.isArray(segment)) {\n // This segment contains a route param. Accumulate these as we traverse\n // down the router tree. The result represents the set of params that\n // the layout/page components are permitted to access below this point.\n const paramName = segment[0]\n const paramCacheKey = segment[1]\n const paramType = segment[2]\n const paramValue = getParamValueFromCacheKey(paramCacheKey, paramType)\n if (paramValue !== null) {\n params = {\n ...parentParams,\n [paramName]: paramValue,\n }\n }\n }\n\n const debugName = getBoundaryDebugNameFromSegment(segment)\n // `debugNameContext` represents the nearest non-\"virtual\" parent segment.\n // `getBoundaryDebugNameFromSegment` returns undefined for virtual segments.\n // So if `debugName` is undefined, the context is passed through unchanged.\n const childDebugNameContext = debugName ?? debugNameContext\n\n // In practical terms, clicking this name in the Suspense DevTools\n // should select the child slots of that layout.\n //\n // So the name we apply to the Activity boundary is actually based on\n // the nearest parent segments.\n //\n // We skip over \"virtual\" parents, i.e. ones inserted by Next.js that\n // don't correspond to application-defined code.\n const isVirtual = debugName === undefined\n const debugNameToDisplay = isVirtual ? undefined : debugNameContext\n\n let templateValue = (\n <ScrollAndMaybeFocusHandler cacheNode={cacheNode}>\n <ErrorBoundary\n errorComponent={error}\n errorStyles={errorStyles}\n errorScripts={errorScripts}\n >\n <LoadingBoundary\n name={debugNameToDisplay}\n // TODO: The loading module data for a segment is stored on the\n // parent, then applied to each of that parent segment's\n // parallel route slots. In the simple case where there's only\n // one parallel route (the `children` slot), this is no\n // different from if the loading module data were stored on the\n // child directly. But I'm not sure this actually makes sense\n // when there are multiple parallel routes. It's not a huge\n // issue because you always have the option to define a narrower\n // loading boundary for a particular slot. But this sort of\n // smells like an implementation accident to me.\n loading={parentLoadingData}\n >\n <HTTPAccessFallbackBoundary\n notFound={notFound}\n forbidden={forbidden}\n unauthorized={unauthorized}\n >\n <RedirectBoundary>\n <InnerLayoutRouter\n url={url}\n tree={tree}\n params={params}\n cacheNode={cacheNode}\n segmentPath={segmentPath}\n debugNameContext={childDebugNameContext}\n isActive={isActive && stateKey === activeStateKey}\n />\n {segmentBoundaryTriggerNode}\n </RedirectBoundary>\n </HTTPAccessFallbackBoundary>\n </LoadingBoundary>\n </ErrorBoundary>\n {segmentViewStateNode}\n </ScrollAndMaybeFocusHandler>\n )\n\n if (\n typeof window === 'undefined' &&\n process.env.__NEXT_CACHE_COMPONENTS &&\n typeof maybeValidationBoundaryId === 'string'\n ) {\n templateValue = (\n <RenderValidationBoundaryAtThisLevel id={maybeValidationBoundaryId}>\n {templateValue}\n </RenderValidationBoundaryAtThisLevel>\n )\n }\n\n let child = (\n <TemplateContext.Provider key={stateKey} value={templateValue}>\n {templateStyles}\n {templateScripts}\n {template}\n </TemplateContext.Provider>\n )\n\n if (process.env.NODE_ENV !== 'production') {\n const { SegmentStateProvider } =\n require('../../next-devtools/userspace/app/segment-explorer-node') as typeof import('../../next-devtools/userspace/app/segment-explorer-node')\n\n child = (\n <SegmentStateProvider key={stateKey}>\n {child}\n {segmentViewBoundaries}\n </SegmentStateProvider>\n )\n }\n\n if (process.env.__NEXT_CACHE_COMPONENTS) {\n child = (\n <Activity\n name={debugNameToDisplay}\n key={stateKey}\n mode={stateKey === activeStateKey ? 'visible' : 'hidden'}\n >\n {child}\n </Activity>\n )\n }\n\n children.push(child)\n\n bfcacheEntry = bfcacheEntry.next\n } while (bfcacheEntry !== null)\n\n return children\n}\n\nfunction getBoundaryDebugNameFromSegment(segment: Segment): string | undefined {\n if (segment === '/') {\n // Reached the root\n return '/'\n }\n if (typeof segment === 'string') {\n if (isVirtualLayout(segment)) {\n return undefined\n } else {\n return segment + '/'\n }\n }\n const paramCacheKey = segment[1]\n return paramCacheKey + '/'\n}\n\nfunction isVirtualLayout(segment: string): boolean {\n return (\n // This is inserted by the loader. Uses double-underscore convention\n // (like __PAGE__ and __DEFAULT__) to avoid collisions with\n // user-defined route groups.\n segment === '(__SLOT__)'\n )\n}\n"],"names":["LoadingBoundaryProvider","OuterLayoutRouter","getScrollPaddingTopInPixels","htmlElement","viewportHeight","scrollPaddingTop","getComputedStyle","value","Number","parseFloat","isFinite","endsWith","getScrollTargetState","instance","getScrollPaddingTop","rects","getClientRects","length","elementTop","POSITIVE_INFINITY","i","rect","top","getHashFragmentDomNode","hashFragment","document","body","getElementById","getElementsByName","InnerScrollAndMaybeFocusHandler","props","childrenRef","React","useRef","useLayoutEffect","focusAndScrollRef","cacheNode","scrollRef","forceScroll","current","onlyHashChange","didHandleScroll","disableSmoothScrollDuringRouteTransition","documentElement","initialTargetState","clientHeight","scrollIntoView","scrollTop","dontForceLayout","undefined","Fragment","ref","children","ScrollAndMaybeFocusHandler","context","useContext","GlobalLayoutRouterContext","Error","InnerLayoutRouter","tree","segmentPath","debugNameContext","maybeCacheNode","params","url","isActive","parentNavPromises","NavigationPromisesContext","use","unresolvedThenable","resolvedPrefetchRsc","prefetchRsc","rsc","useDeferredValue","resolvedRsc","isDeferredRsc","unwrappedRsc","navigationPromises","process","env","NODE_ENV","createNestedLayoutNavigationPromises","require","Provider","LayoutRouterContext","parentTree","parentCacheNode","parentSegmentPath","parentParams","parentLoadingData","loading","parentContext","LoadingBoundary","name","loadingRsc","loadingStyles","loadingScripts","Suspense","fallback","parallelRouterKey","error","errorStyles","errorScripts","templateStyles","templateScripts","template","notFound","forbidden","unauthorized","segmentViewBoundaries","parentTreeSegment","concat","activeTree","maybeParentSlots","slots","maybeValidationBoundaryId","window","__NEXT_CACHE_COMPONENTS","InstantValidationBoundaryContext","activeSegment","activeCacheNode","activeStateKey","createRouterCacheKey","bfcacheEntry","useRouterBFCache","stateKey","segment","segmentBoundaryTriggerNode","segmentViewStateNode","SegmentBoundaryTriggerNode","SegmentViewStateNode","pagePrefix","normalizeAppPath","page","Array","isArray","paramName","paramCacheKey","paramType","paramValue","getParamValueFromCacheKey","debugName","getBoundaryDebugNameFromSegment","childDebugNameContext","isVirtual","debugNameToDisplay","templateValue","ErrorBoundary","errorComponent","HTTPAccessFallbackBoundary","RedirectBoundary","RenderValidationBoundaryAtThisLevel","id","child","TemplateContext","SegmentStateProvider","Activity","mode","push","next","isVirtualLayout"],"mappings":"AAAA;;;;;;;;;;;;;;;;IA6agBA,uBAAuB;eAAvBA;;IAsFhB;;;CAGC,GACD,OAiQC;eAjQuBC;;;;;iEAhfjB;+CAKA;oCAC4B;+BACL;qCAC2B;kCACxB;gCACU;0BAIpC;sCAC8B;qCAI9B;0BAC0B;iDAI1B;6BACmC;gCAEZ;AAQ9B;;;;;;CAMC,GACD,SAASC,4BACPC,WAAwB,EACxBC,cAAsB;IAEtB,MAAMC,mBAAmBC,iBAAiBH,aAAaE,gBAAgB;IACvE,MAAME,QAAQC,OAAOC,UAAU,CAACJ;IAEhC,IAAI,CAACG,OAAOE,QAAQ,CAACH,UAAUA,QAAQ,GAAG;QACxC,OAAO;IACT;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zE,SAAS0G,IAAI,CAACL;QAEd9B,eAAeA,aAAaoC,IAAI;IAClC,QAASpC,iBAAiB,MAAK;IAE/B,OAAOvE;AACT;AAEA,SAAS0F,gCAAgChB,OAAgB;IACvD,IAAIA,YAAY,KAAK;QACnB,mBAAmB;QACnB,OAAO;IACT;IACA,IAAI,OAAOA,YAAY,UAAU;QAC/B,IAAIkC,gBAAgBlC,UAAU;YAC5B,OAAO7E;QACT,OAAO;YACL,OAAO6E,UAAU;QACnB;IACF;IACA,MAAMW,gBAAgBX,OAAO,CAAC,EAAE;IAChC,OAAOW,gBAAgB;AACzB;AAEA,SAASuB,gBAAgBlC,OAAe;IACtC,OACE,oEAAoE;IACpE,2DAA2D;IAC3D,6BAA6B;IAC7BA,YAAY;AAEhB","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/client/components/layout-router.tsx"],"sourcesContent":["'use client'\n\nimport type { CacheNode } from '../../shared/lib/app-router-types'\nimport type { LoadingModuleData } from '../../shared/lib/app-router-types'\nimport type {\n FlightRouterState,\n FlightSegmentPath,\n Segment,\n} from '../../shared/lib/app-router-types'\nimport type { ErrorComponent } from './error-boundary'\nimport type { ScrollHandlerRef } from './router-reducer/router-reducer-types'\n\nimport React, {\n Activity,\n Fragment,\n useContext,\n use,\n Suspense,\n useDeferredValue,\n useLayoutEffect,\n type FragmentInstance,\n type JSX,\n type ActivityProps,\n} from 'react'\nimport {\n LayoutRouterContext,\n GlobalLayoutRouterContext,\n TemplateContext,\n} from '../../shared/lib/app-router-context.shared-runtime'\nimport { unresolvedThenable } from './unresolved-thenable'\nimport { ErrorBoundary } from './error-boundary'\nimport { disableSmoothScrollDuringRouteTransition } from '../../shared/lib/router/utils/disable-smooth-scroll'\nimport { RedirectBoundary } from './redirect-boundary'\nimport { HTTPAccessFallbackBoundary } from './http-access-fallback/error-boundary'\nimport {\n InstantValidationBoundaryContext,\n RenderValidationBoundaryAtThisLevel,\n} from './instant-validation/boundary'\nimport { createRouterCacheKey } from './router-reducer/create-router-cache-key'\nimport {\n useRouterBFCache,\n type RouterBFCacheEntry,\n} from './bfcache-state-manager'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport {\n NavigationPromisesContext,\n type NavigationPromises,\n} from '../../shared/lib/hooks-client-context.shared-runtime'\nimport { getParamValueFromCacheKey } from '../route-params'\nimport type { Params } from '../../server/request/params'\nimport { isDeferredRsc } from './router-reducer/ppr-navigations'\n\nconst enum ScrollTargetState {\n NoClientRects,\n InViewport,\n OutOfViewport,\n}\n\n/**\n * Resolve the root scroll padding used by the viewport check.\n *\n * Computed lengths serialize as pixels, but percentages remain relative to\n * the scrollport. Preserve the existing behavior for values that still\n * contain unresolved CSS math.\n */\nfunction getScrollPaddingTopInPixels(\n htmlElement: HTMLElement,\n viewportHeight: number\n): number {\n const scrollPaddingTop = getComputedStyle(htmlElement).scrollPaddingTop\n const value = Number.parseFloat(scrollPaddingTop)\n\n if (!Number.isFinite(value) || value < 0) {\n return 0\n }\n\n if (scrollPaddingTop.endsWith('px')) {\n return value\n }\n\n if (scrollPaddingTop.endsWith('%')) {\n return (value / 100) * viewportHeight\n }\n\n return 0\n}\n\n/**\n * Check where the top corner of the HTMLElement is relative to the usable\n * viewport.\n *\n * Scroll padding is resolved lazily so an empty Fragment does not trigger a\n * computed style read. The caller caches the value for the second check.\n */\nfunction getScrollTargetState(\n instance: HTMLElement | FragmentInstance,\n viewportHeight: number,\n getScrollPaddingTop: () => number\n): ScrollTargetState {\n const rects = instance.getClientRects()\n if (rects.length === 0) {\n return ScrollTargetState.NoClientRects\n }\n let elementTop = Number.POSITIVE_INFINITY\n for (let i = 0; i < rects.length; i++) {\n const rect = rects[i]\n if (rect.top < elementTop) {\n elementTop = rect.top\n }\n }\n return elementTop >= getScrollPaddingTop() && elementTop <= viewportHeight\n ? ScrollTargetState.InViewport\n : ScrollTargetState.OutOfViewport\n}\n\n/**\n * Find the DOM node for a hash fragment.\n * If `top` the page has to scroll to the top of the page. This mirrors the browser's behavior.\n * If the hash fragment is an id, the page has to scroll to the element with that id.\n * If the hash fragment is a name, the page has to scroll to the first element with that name.\n */\nfunction getHashFragmentDomNode(hashFragment: string) {\n // If the hash fragment is `top` the page has to scroll to the top of the page.\n if (hashFragment === 'top') {\n return document.body\n }\n\n // If the hash fragment is an id, the page has to scroll to the element with that id.\n return (\n document.getElementById(hashFragment) ??\n // If the hash fragment is a name, the page has to scroll to the first element with that name.\n document.getElementsByName(hashFragment)[0] ??\n null\n )\n}\ninterface ScrollHandlerProps {\n scrollRef: ScrollHandlerRef\n children: React.ReactNode\n cacheNode: CacheNode\n}\n\n/**\n * Uses Fragment refs for scrolling.\n * Does not focus the first host descendant.\n */\nfunction InnerScrollHandler(props: ScrollHandlerProps) {\n const childrenRef = React.useRef<FragmentInstance>(null)\n\n useLayoutEffect(\n () => {\n const { scrollRef: scrollHandlerRef, cacheNode } = props\n\n const scrollRef = scrollHandlerRef.forceScroll\n ? scrollHandlerRef.scrollRef\n : cacheNode.scrollRef\n if (scrollRef === null || !scrollRef.current) return\n\n let instance: FragmentInstance | HTMLElement | null = null\n const hashFragment = scrollHandlerRef.hashFragment\n\n if (hashFragment) {\n instance = getHashFragmentDomNode(hashFragment)\n if (instance === null) {\n // A missing hash target is still a handled scroll intent. Do not\n // fall back to the route Fragment or leave the intent pending.\n scrollRef.current = false\n scrollHandlerRef.onlyHashChange = false\n scrollHandlerRef.hashFragment = null\n return\n }\n } else {\n instance = childrenRef.current\n }\n\n // If there is no DOM node this layout-router level is skipped. It'll be handled higher-up in the tree.\n if (instance === null) {\n return\n }\n\n let didHandleScroll = false\n\n disableSmoothScrollDuringRouteTransition(\n () => {\n const htmlElement = document.documentElement\n let viewportHeight: number | null = null\n let initialTargetState: ScrollTargetState | null = null\n let scrollPaddingTop: number | null = null\n const getScrollPaddingTop = () => {\n if (scrollPaddingTop === null) {\n // Reuse the style and layout update from the geometry read.\n scrollPaddingTop = getScrollPaddingTopInPixels(\n htmlElement,\n viewportHeight!\n )\n }\n return scrollPaddingTop\n }\n\n if (!hashFragment) {\n // Store the current viewport height because reading `clientHeight` causes a reflow,\n // and it won't change during this function.\n viewportHeight = htmlElement.clientHeight\n initialTargetState = getScrollTargetState(\n instance,\n viewportHeight,\n getScrollPaddingTop\n )\n\n // An empty Fragment is not a scroll target. In particular, avoid\n // React's sibling fallback and leave the scroll signal available\n // for another changed segment.\n if (initialTargetState === ScrollTargetState.NoClientRects) {\n return\n }\n }\n\n didHandleScroll = true\n\n // Mark as scrolled so no other segment scrolls for this navigation.\n scrollRef.current = false\n\n // This handler intentionally leaves focus untouched; resetting focus on\n // navigation is deferred.\n\n // In case of hash scroll, we only need to scroll the element into view\n if (hashFragment) {\n instance.scrollIntoView()\n\n return\n }\n\n // If the element's top edge is already in the viewport, exit early.\n if (initialTargetState === ScrollTargetState.InViewport) {\n return\n }\n\n // Otherwise, try scrolling go the top of the document to be backward compatible with pages\n // scrollIntoView() called on `<html/>` element scrolls horizontally on chrome and firefox (that shouldn't happen)\n // We could use it to scroll horizontally following RTL but that also seems to be broken - it will always scroll left\n // scrollLeft = 0 also seems to ignore RTL and manually checking for RTL is too much hassle so we will scroll just vertically\n htmlElement.scrollTop = 0\n\n // Scroll to domNode if domNode is not in viewport when scrolled to top of document\n if (\n getScrollTargetState(\n instance,\n viewportHeight!,\n getScrollPaddingTop\n ) === ScrollTargetState.OutOfViewport\n ) {\n // Scroll into view doesn't scroll horizontally by default when not needed\n instance.scrollIntoView()\n }\n },\n {\n // We will force layout by querying domNode position\n dontForceLayout: true,\n onlyHashChange: scrollHandlerRef.onlyHashChange,\n }\n )\n\n if (!didHandleScroll) {\n return\n }\n\n // Mutate after scrolling so that it can be read by `disableSmoothScrollDuringRouteTransition`\n scrollHandlerRef.onlyHashChange = false\n scrollHandlerRef.hashFragment = null\n },\n // Used to run on every commit. We may be able to be smarter about this\n // but be prepared for lots of manual testing.\n undefined\n )\n\n return <Fragment ref={childrenRef}>{props.children}</Fragment>\n}\n\nfunction ScrollHandler({\n children,\n cacheNode,\n}: {\n children: React.ReactNode\n cacheNode: CacheNode\n}) {\n const context = useContext(GlobalLayoutRouterContext)\n if (!context) {\n throw new Error('invariant global layout router not mounted')\n }\n\n return (\n <InnerScrollHandler scrollRef={context.scrollRef} cacheNode={cacheNode}>\n {children}\n </InnerScrollHandler>\n )\n}\n\n/**\n * InnerLayoutRouter handles rendering the provided segment based on the cache.\n */\nfunction InnerLayoutRouter({\n tree,\n segmentPath,\n debugNameContext,\n cacheNode: maybeCacheNode,\n params,\n url,\n isActive,\n}: {\n tree: FlightRouterState\n segmentPath: FlightSegmentPath\n debugNameContext: string\n cacheNode: CacheNode | null\n params: Params\n url: string\n isActive: boolean\n}) {\n const context = useContext(GlobalLayoutRouterContext)\n const parentNavPromises = useContext(NavigationPromisesContext)\n\n if (!context) {\n throw new Error('invariant global layout router not mounted')\n }\n\n const cacheNode =\n maybeCacheNode !== null\n ? maybeCacheNode\n : // This segment is not in the cache. Suspend indefinitely.\n //\n // This should only be reachable for inactive/hidden segments, during\n // prerendering The active segment should always be consistent with the\n // CacheNode tree. Regardless, if we don't have a matching CacheNode, we\n // must suspend rather than render nothing, to prevent showing an\n // inconsistent route.\n\n (use(unresolvedThenable) as never)\n\n // `rsc` represents the renderable node for this segment.\n\n // If this segment has a `prefetchRsc`, it's the statically prefetched data.\n // We should use that on initial render instead of `rsc`. Then we'll switch\n // to `rsc` when the dynamic response streams in.\n //\n // If no prefetch data is available, then we go straight to rendering `rsc`.\n const resolvedPrefetchRsc =\n cacheNode.prefetchRsc !== null ? cacheNode.prefetchRsc : cacheNode.rsc\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 const rsc: any = useDeferredValue(cacheNode.rsc, resolvedPrefetchRsc)\n\n // `rsc` is either a React node or a promise for a React node, except we\n // special case `null` to represent that this segment's data is missing. If\n // it's a promise, we need to unwrap it so we can determine whether or not the\n // data is missing.\n let resolvedRsc: React.ReactNode\n if (isDeferredRsc(rsc)) {\n const unwrappedRsc = use(rsc)\n if (unwrappedRsc === null) {\n // If the promise was resolved to `null`, it means the data for this\n // segment was not returned by the server. Suspend indefinitely. When this\n // happens, the router is responsible for triggering a new state update to\n // un-suspend this segment.\n use(unresolvedThenable) as never\n }\n resolvedRsc = unwrappedRsc\n } else {\n // This is not a deferred RSC promise. Don't need to unwrap it.\n if (rsc === null) {\n use(unresolvedThenable) as never\n }\n resolvedRsc = rsc\n }\n\n // In dev, we create a NavigationPromisesContext containing the instrumented promises that provide\n // `useSelectedLayoutSegment` and `useSelectedLayoutSegments`.\n // Promises are cached outside of render to survive suspense retries.\n let navigationPromises: NavigationPromises | null = null\n if (process.env.NODE_ENV !== 'production') {\n const { createNestedLayoutNavigationPromises } =\n require('./navigation-devtools') as typeof import('./navigation-devtools')\n\n navigationPromises = createNestedLayoutNavigationPromises(\n tree,\n parentNavPromises\n )\n }\n\n let children = resolvedRsc\n\n if (navigationPromises) {\n children = (\n <NavigationPromisesContext.Provider value={navigationPromises}>\n {resolvedRsc}\n </NavigationPromisesContext.Provider>\n )\n }\n\n children = (\n // The layout router context narrows down tree and childNodes at each level.\n <LayoutRouterContext.Provider\n value={{\n parentTree: tree,\n parentCacheNode: cacheNode,\n parentSegmentPath: segmentPath,\n parentParams: params,\n // This is always set to null as we enter a child segment. It's\n // populated by LoadingBoundaryProvider the next time we reach a\n // loading boundary.\n parentLoadingData: null,\n debugNameContext: debugNameContext,\n\n // TODO-APP: overriding of url for parallel routes\n url: url,\n isActive: isActive,\n }}\n >\n {children}\n </LayoutRouterContext.Provider>\n )\n\n return children\n}\n\nexport function LoadingBoundaryProvider({\n loading,\n children,\n}: {\n loading: LoadingModuleData\n children: React.ReactNode\n}) {\n // Provides the data needed to render a loading.tsx boundary, via context.\n //\n // loading.tsx creates a Suspense boundary around each of a layout's child\n // slots. (Might be bit confusing to think about the data flow, but: if\n // loading.tsx and layout.tsx are in the same directory, they are assigned\n // to the same CacheNode.)\n //\n // This provider component does not render the Suspense boundary directly;\n // that's handled by LoadingBoundary.\n //\n // TODO: For simplicity, we should combine this provider with LoadingBoundary\n // and render the Suspense boundary directly. The only real benefit of doing\n // it separately is so that when there are multiple parallel routes, we only\n // send the boundary data once, rather than once per child. But that's a\n // negligible benefit and can be achieved via caching instead.\n const parentContext = use(LayoutRouterContext)\n if (parentContext === null) {\n return children\n }\n // All values except for parentLoadingData are the same as the parent context.\n return (\n <LayoutRouterContext.Provider\n value={{\n parentTree: parentContext.parentTree,\n parentCacheNode: parentContext.parentCacheNode,\n parentSegmentPath: parentContext.parentSegmentPath,\n parentParams: parentContext.parentParams,\n parentLoadingData: loading,\n debugNameContext: parentContext.debugNameContext,\n url: parentContext.url,\n isActive: parentContext.isActive,\n }}\n >\n {children}\n </LayoutRouterContext.Provider>\n )\n}\n\n/**\n * Renders suspense boundary with the provided \"loading\" property as the fallback.\n * If no loading property is provided it renders the children without a suspense boundary.\n */\nfunction LoadingBoundary({\n name,\n loading,\n children,\n}: {\n name: ActivityProps['name']\n loading: LoadingModuleData | null\n children: React.ReactNode\n}): JSX.Element {\n // TODO: For LoadingBoundary, and the other built-in boundary types, don't\n // wrap in an extra function component if no user-defined boundary is\n // provided. In other words, inline this conditional wrapping logic into\n // the parent component. More efficient and keeps unnecessary junk out of\n // the component stack.\n if (loading !== null) {\n const loadingRsc = loading[0]\n const loadingStyles = loading[1]\n const loadingScripts = loading[2]\n return (\n <Suspense\n name={name}\n fallback={\n <>\n {loadingStyles}\n {loadingScripts}\n {loadingRsc}\n </>\n }\n >\n {children}\n </Suspense>\n )\n }\n\n return <>{children}</>\n}\n\n/**\n * OuterLayoutRouter handles the current segment as well as <Offscreen> rendering of other segments.\n * It can be rendered next to each other with a different `parallelRouterKey`, allowing for Parallel routes.\n */\nexport default function OuterLayoutRouter({\n parallelRouterKey,\n error,\n errorStyles,\n errorScripts,\n templateStyles,\n templateScripts,\n template,\n notFound,\n forbidden,\n unauthorized,\n segmentViewBoundaries,\n}: {\n parallelRouterKey: string\n error: ErrorComponent | undefined\n errorStyles: React.ReactNode | undefined\n errorScripts: React.ReactNode | undefined\n templateStyles: React.ReactNode | undefined\n templateScripts: React.ReactNode | undefined\n template: React.ReactNode\n notFound: React.ReactNode | undefined\n forbidden: React.ReactNode | undefined\n unauthorized: React.ReactNode | undefined\n segmentViewBoundaries?: React.ReactNode\n}) {\n const context = useContext(LayoutRouterContext)\n if (!context) {\n throw new Error('invariant expected layout router to be mounted')\n }\n\n const {\n parentTree,\n parentCacheNode,\n parentSegmentPath,\n parentParams,\n parentLoadingData,\n url,\n isActive,\n debugNameContext,\n } = context\n\n // Get the CacheNode for this segment by reading it from the parent segment's\n // child map.\n const parentTreeSegment = parentTree[0]\n const segmentPath =\n parentSegmentPath === null\n ? // TODO: The root segment value is currently omitted from the segment\n // path. This has led to a bunch of special cases scattered throughout\n // the code. We should clean this up.\n [parallelRouterKey]\n : parentSegmentPath.concat([parentTreeSegment, parallelRouterKey])\n\n // The \"state\" key of a segment is the one passed to React — it represents the\n // identity of the UI tree. Whenever the state key changes, the tree is\n // recreated and the state is reset. In the App Router model, search params do\n // not cause state to be lost, so two segments with the same segment path but\n // different search params should have the same state key.\n //\n // The \"cache\" key of a segment, however, *does* include the search params, if\n // it's possible that the segment accessed the search params on the server.\n // (This only applies to page segments; layout segments cannot access search\n // params on the server.)\n const activeTree = parentTree[1][parallelRouterKey]\n const maybeParentSlots = parentCacheNode.slots\n if (activeTree === undefined || maybeParentSlots === null) {\n // Could not find a matching segment. The client tree is inconsistent with\n // the server tree. Suspend indefinitely; the router will have already\n // detected the inconsistency when handling the server response, and\n // triggered a refresh of the page to recover.\n use(unresolvedThenable) as never\n }\n\n let maybeValidationBoundaryId: string | null = null\n if (typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS) {\n maybeValidationBoundaryId = use(InstantValidationBoundaryContext)\n }\n\n const activeSegment = activeTree[0]\n const activeCacheNode = maybeParentSlots![parallelRouterKey] ?? null\n const activeStateKey = createRouterCacheKey(activeSegment, true) // no search params\n\n // At each level of the route tree, not only do we render the currently\n // active segment — we also render the last N segments that were active at\n // this level inside a hidden <Activity> boundary, to preserve their state\n // if or when the user navigates to them again.\n //\n // bfcacheEntry is a linked list of FlightRouterStates.\n let bfcacheEntry: RouterBFCacheEntry | null = useRouterBFCache(\n activeTree,\n activeCacheNode,\n activeStateKey\n )\n let children: Array<React.ReactNode> = []\n do {\n const tree = bfcacheEntry.tree\n const cacheNode = bfcacheEntry.cacheNode\n const stateKey = bfcacheEntry.stateKey\n const segment = tree[0]\n\n /*\n - Error boundary\n - Only renders error boundary if error component is provided.\n - Rendered for each segment to ensure they have their own error state.\n - When gracefully degrade for bots, skip rendering error boundary.\n - Loading boundary\n - Only renders suspense boundary if loading components is provided.\n - Rendered for each segment to ensure they have their own loading state.\n - Passed to the router during rendering to ensure it can be immediately rendered when suspending on a Flight fetch.\n */\n\n let segmentBoundaryTriggerNode: React.ReactNode = null\n let segmentViewStateNode: React.ReactNode = null\n if (process.env.NODE_ENV !== 'production') {\n const { SegmentBoundaryTriggerNode, SegmentViewStateNode } =\n require('../../next-devtools/userspace/app/segment-explorer-node') as typeof import('../../next-devtools/userspace/app/segment-explorer-node')\n\n const pagePrefix = normalizeAppPath(url)\n segmentViewStateNode = (\n <SegmentViewStateNode key={pagePrefix} page={pagePrefix} />\n )\n\n segmentBoundaryTriggerNode = (\n <>\n <SegmentBoundaryTriggerNode />\n </>\n )\n }\n\n let params = parentParams\n if (Array.isArray(segment)) {\n // This segment contains a route param. Accumulate these as we traverse\n // down the router tree. The result represents the set of params that\n // the layout/page components are permitted to access below this point.\n const paramName = segment[0]\n const paramCacheKey = segment[1]\n const paramType = segment[2]\n const paramValue = getParamValueFromCacheKey(paramCacheKey, paramType)\n if (paramValue !== null) {\n params = {\n ...parentParams,\n [paramName]: paramValue,\n }\n }\n }\n\n const debugName = getBoundaryDebugNameFromSegment(segment)\n // `debugNameContext` represents the nearest non-\"virtual\" parent segment.\n // `getBoundaryDebugNameFromSegment` returns undefined for virtual segments.\n // So if `debugName` is undefined, the context is passed through unchanged.\n const childDebugNameContext = debugName ?? debugNameContext\n\n // In practical terms, clicking this name in the Suspense DevTools\n // should select the child slots of that layout.\n //\n // So the name we apply to the Activity boundary is actually based on\n // the nearest parent segments.\n //\n // We skip over \"virtual\" parents, i.e. ones inserted by Next.js that\n // don't correspond to application-defined code.\n const isVirtual = debugName === undefined\n const debugNameToDisplay = isVirtual ? undefined : debugNameContext\n\n let templateValue = (\n <ScrollHandler cacheNode={cacheNode}>\n <ErrorBoundary\n errorComponent={error}\n errorStyles={errorStyles}\n errorScripts={errorScripts}\n >\n <LoadingBoundary\n name={debugNameToDisplay}\n // TODO: The loading module data for a segment is stored on the\n // parent, then applied to each of that parent segment's\n // parallel route slots. In the simple case where there's only\n // one parallel route (the `children` slot), this is no\n // different from if the loading module data were stored on the\n // child directly. But I'm not sure this actually makes sense\n // when there are multiple parallel routes. It's not a huge\n // issue because you always have the option to define a narrower\n // loading boundary for a particular slot. But this sort of\n // smells like an implementation accident to me.\n loading={parentLoadingData}\n >\n <HTTPAccessFallbackBoundary\n notFound={notFound}\n forbidden={forbidden}\n unauthorized={unauthorized}\n >\n <RedirectBoundary>\n <InnerLayoutRouter\n url={url}\n tree={tree}\n params={params}\n cacheNode={cacheNode}\n segmentPath={segmentPath}\n debugNameContext={childDebugNameContext}\n isActive={isActive && stateKey === activeStateKey}\n />\n {segmentBoundaryTriggerNode}\n </RedirectBoundary>\n </HTTPAccessFallbackBoundary>\n </LoadingBoundary>\n </ErrorBoundary>\n {segmentViewStateNode}\n </ScrollHandler>\n )\n\n if (\n typeof window === 'undefined' &&\n process.env.__NEXT_CACHE_COMPONENTS &&\n typeof maybeValidationBoundaryId === 'string'\n ) {\n templateValue = (\n <RenderValidationBoundaryAtThisLevel id={maybeValidationBoundaryId}>\n {templateValue}\n </RenderValidationBoundaryAtThisLevel>\n )\n }\n\n let child = (\n <TemplateContext.Provider key={stateKey} value={templateValue}>\n {templateStyles}\n {templateScripts}\n {template}\n </TemplateContext.Provider>\n )\n\n if (process.env.NODE_ENV !== 'production') {\n const { SegmentStateProvider } =\n require('../../next-devtools/userspace/app/segment-explorer-node') as typeof import('../../next-devtools/userspace/app/segment-explorer-node')\n\n child = (\n <SegmentStateProvider key={stateKey}>\n {child}\n {segmentViewBoundaries}\n </SegmentStateProvider>\n )\n }\n\n if (process.env.__NEXT_CACHE_COMPONENTS) {\n child = (\n <Activity\n name={debugNameToDisplay}\n key={stateKey}\n mode={stateKey === activeStateKey ? 'visible' : 'hidden'}\n >\n {child}\n </Activity>\n )\n }\n\n children.push(child)\n\n bfcacheEntry = bfcacheEntry.next\n } while (bfcacheEntry !== null)\n\n return children\n}\n\nfunction getBoundaryDebugNameFromSegment(segment: Segment): string | undefined {\n if (segment === '/') {\n // Reached the root\n return '/'\n }\n if (typeof segment === 'string') {\n if (isVirtualLayout(segment)) {\n return undefined\n } else {\n return segment + '/'\n }\n }\n const paramCacheKey = segment[1]\n return paramCacheKey + '/'\n}\n\nfunction isVirtualLayout(segment: string): boolean {\n return (\n // This is inserted by the loader. Uses double-underscore convention\n // (like __PAGE__ and __DEFAULT__) to avoid collisions with\n // user-defined route groups.\n segment === '(__SLOT__)'\n )\n}\n"],"names":["LoadingBoundaryProvider","OuterLayoutRouter","getScrollPaddingTopInPixels","htmlElement","viewportHeight","scrollPaddingTop","getComputedStyle","value","Number","parseFloat","isFinite","endsWith","getScrollTargetState","instance","getScrollPaddingTop","rects","getClientRects","length","elementTop","POSITIVE_INFINITY","i","rect","top","getHashFragmentDomNode","hashFragment","document","body","getElementById","getElementsByName","InnerScrollHandler","props","childrenRef","React","useRef","useLayoutEffect","scrollRef","scrollHandlerRef","cacheNode","forceScroll","current","onlyHashChange","didHandleScroll","disableSmoothScrollDuringRouteTransition","documentElement","initialTargetState","clientHeight","scrollIntoView","scrollTop","dontForceLayout","undefined","Fragment","ref","children","ScrollHandler","context","useContext","GlobalLayoutRouterContext","Error","InnerLayoutRouter","tree","segmentPath","debugNameContext","maybeCacheNode","params","url","isActive","parentNavPromises","NavigationPromisesContext","use","unresolvedThenable","resolvedPrefetchRsc","prefetchRsc","rsc","useDeferredValue","resolvedRsc","isDeferredRsc","unwrappedRsc","navigationPromises","process","env","NODE_ENV","createNestedLayoutNavigationPromises","require","Provider","LayoutRouterContext","parentTree","parentCacheNode","parentSegmentPath","parentParams","parentLoadingData","loading","parentContext","LoadingBoundary","name","loadingRsc","loadingStyles","loadingScripts","Suspense","fallback","parallelRouterKey","error","errorStyles","errorScripts","templateStyles","templateScripts","template","notFound","forbidden","unauthorized","segmentViewBoundaries","parentTreeSegment","concat","activeTree","maybeParentSlots","slots","maybeValidationBoundaryId","window","__NEXT_CACHE_COMPONENTS","InstantValidationBoundaryContext","activeSegment","activeCacheNode","activeStateKey","createRouterCacheKey","bfcacheEntry","useRouterBFCache","stateKey","segment","segmentBoundaryTriggerNode","segmentViewStateNode","SegmentBoundaryTriggerNode","SegmentViewStateNode","pagePrefix","normalizeAppPath","page","Array","isArray","paramName","paramCacheKey","paramType","paramValue","getParamValueFromCacheKey","debugName","getBoundaryDebugNameFromSegment","childDebugNameContext","isVirtual","debugNameToDisplay","templateValue","ErrorBoundary","errorComponent","HTTPAccessFallbackBoundary","RedirectBoundary","RenderValidationBoundaryAtThisLevel","id","child","TemplateContext","SegmentStateProvider","Activity","mode","push","next","isVirtualLayout"],"mappings":"AAAA;;;;;;;;;;;;;;;;IAwagBA,uBAAuB;eAAvBA;;IAsFhB;;;CAGC,GACD,OAiQC;eAjQuBC;;;;;iEA3ejB;+CAKA;oCAC4B;+BACL;qCAC2B;kCACxB;gCACU;0BAIpC;sCAC8B;qCAI9B;0BAC0B;iDAI1B;6BACmC;gCAEZ;AAQ9B;;;;;;CAMC,GACD,SAASC,4BACPC,WAAwB,EACxBC,cAAsB;IAEtB,MAAMC,mBAAmBC,iBAAiBH,aAAaE,gBAAgB;IACvE,MAAME,QAAQC,OAAOC,UAAU,C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ACP/D,MAAMoD;gBAENY,MAAMhC,aAAaJ,iBAAiB,YAAY;0BAE/CgC;eAHI5B;QAMX;QAEAzE,SAAS0G,IAAI,CAACL;QAEd9B,eAAeA,aAAaoC,IAAI;IAClC,QAASpC,iBAAiB,MAAK;IAE/B,OAAOvE;AACT;AAEA,SAAS0F,gCAAgChB,OAAgB;IACvD,IAAIA,YAAY,KAAK;QACnB,mBAAmB;QACnB,OAAO;IACT;IACA,IAAI,OAAOA,YAAY,UAAU;QAC/B,IAAIkC,gBAAgBlC,UAAU;YAC5B,OAAO7E;QACT,OAAO;YACL,OAAO6E,UAAU;QACnB;IACF;IACA,MAAMW,gBAAgBX,OAAO,CAAC,EAAE;IAChC,OAAOW,gBAAgB;AACzB;AAEA,SAASuB,gBAAgBlC,OAAe;IACtC,OACE,oEAAoE;IACpE,2DAA2D;IAC3D,6BAA6B;IAC7BA,YAAY;AAEhB","ignoreList":[0]} |
@@ -78,4 +78,4 @@ "use strict"; | ||
| const staleAt = await (0, _cache.resolveStaleAt)(now, staticStageResponse.s); | ||
| (0, _cache.writePrerenderResponseIntoCache)(now, _types.FetchStrategy.PPR, staticStageResponse.t, undefined, staticStageResponse.r ?? null, staleAt, initialTree, initialRenderedSearch, true // isResponsePartial | ||
| ); | ||
| (0, _cache.writePrerenderResponseIntoCache)(now, _types.FetchStrategy.PPR, staticStageResponse.t, undefined, staticStageResponse.r ?? null, staleAt, initialTree, initialRenderedSearch, true, _cache // hydration writes are bound to the shared map | ||
| .segmentCacheMap); | ||
| }).catch(()=>{ | ||
@@ -93,4 +93,4 @@ // The static stage processing failed. Not fatal — the page | ||
| (0, _cache.resolveStaleAt)(now, initialStaleTime).then((staleAt)=>{ | ||
| (0, _cache.writePrerenderResponseIntoCache)(now, _types.FetchStrategy.PPR, initialTransportData, undefined, initialRootVaryParams ?? null, staleAt, initialTree, initialRenderedSearch, false // isResponsePartial | ||
| ); | ||
| (0, _cache.writePrerenderResponseIntoCache)(now, _types.FetchStrategy.PPR, initialTransportData, undefined, initialRootVaryParams ?? null, staleAt, initialTree, initialRenderedSearch, false, _cache // hydration writes are bound to the shared map | ||
| .segmentCacheMap); | ||
| }).catch(()=>{ | ||
@@ -114,3 +114,4 @@ // The static stage processing failed. Not fatal — the page | ||
| if (processed !== null) { | ||
| (0, _cache.writeDynamicRenderResponseIntoCache)(Date.now(), _types.FetchStrategy.PPRRuntime, processed.buildId, processed.isResponsePartial, processed.headVaryParams, processed.rootVaryParamsIterable, processed.staleAt, processed.navigationSeed, null); | ||
| (0, _cache.writeDynamicRenderResponseIntoCache)(Date.now(), _types.FetchStrategy.PPRRuntime, processed.buildId, processed.isResponsePartial, processed.headVaryParams, processed.rootVaryParamsIterable, processed.staleAt, processed.navigationSeed, null, _cache // hydration writes are bound to the shared map | ||
| .segmentCacheMap); | ||
| } | ||
@@ -147,3 +148,3 @@ }).catch(()=>{ | ||
| }, | ||
| focusAndScrollRef: { | ||
| scrollRef: { | ||
| scrollRef: null, | ||
@@ -150,0 +151,0 @@ forceScroll: false, |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/client/components/router-reducer/create-initial-router-state.ts"],"sourcesContent":["import type { InitialRSCPayload } from '../../../shared/lib/app-router-types'\n\nimport { createHrefFromUrl } from './create-href-from-url'\nimport { extractPathFromFlightRouterState } from './compute-changed-path'\n\nimport type { AppRouterState } from './router-reducer-types'\nimport { transportNodeToFlightRouterState } from '../../../shared/lib/rsc-transport'\nimport { createInitialCacheNodeForHydration } from './ppr-navigations'\nimport {\n resolveStaleAt,\n processRuntimePrefetchStream,\n writeDynamicRenderResponseIntoCache,\n writePrerenderResponseIntoCache,\n} from '../segment-cache/cache'\nimport { decodeTransportTreeIntoRouteTree } from '../segment-cache/decode-server-response'\nimport { FetchStrategy } from '../segment-cache/types'\nimport {\n UnknownDynamicStaleTime,\n computeDynamicStaleAt,\n} from '../segment-cache/bfcache'\nimport { decodeStageUntilBoundary } from './fetch-server-response'\nimport { discoverKnownRoute } from '../segment-cache/optimistic-routes'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\n\nexport interface InitialRouterStateParameters {\n navigatedAt: number\n initialRSCPayload: InitialRSCPayload\n initialFlightStreamForCache?: ReadableStream<Uint8Array> | null\n location: Location | null\n}\n\nexport function createInitialRouterState({\n navigatedAt,\n initialRSCPayload,\n initialFlightStreamForCache,\n location,\n}: InitialRouterStateParameters): AppRouterState {\n const {\n c: initialCanonicalUrlParts,\n t: initialTransportData,\n q: initialRenderedSearch,\n i: initialCouldBeIntercepted,\n S: initialSupportsPerSegmentPrefetching,\n s: initialStaleTime,\n l: initialStaticStageByteLength,\n r: initialRootVaryParams,\n p: initialRuntimePrefetchStream,\n d: initialDynamicStaleTimeSeconds,\n } = initialRSCPayload\n\n // When initialized on the server, the canonical URL is provided as an array of parts.\n // This is to ensure that when the RSC payload streamed to the client, crawlers don't interpret it\n // as a URL that should be crawled.\n const initialCanonicalUrl = initialCanonicalUrlParts.join('/')\n\n const initialHead = initialTransportData.h.r\n\n // The initial router state tree, derived from the transport tree. Page\n // segments keep their search params, which travel inside the segment\n // string.\n const initialTree = transportNodeToFlightRouterState(initialTransportData.t)\n\n const canonicalUrl =\n // location.href is read as the initial value for canonicalUrl in the browser\n // This is safe to do as canonicalUrl can't be rendered, it's only used to control the history updates in the useEffect further down in this file.\n location\n ? // window.location does not have the same type as URL but has all the fields createHrefFromUrl needs.\n createHrefFromUrl(location)\n : initialCanonicalUrl\n\n // Decode the initial transport tree into the RouteTree type, with the\n // payload's render output embedded on each node. (discoverKnownRoute below\n // stores this tree in the route cache, which strips the data on write —\n // see stripDataFromRouteTree.)\n // NOTE: The metadataVaryPath isn't used for anything currently because the\n // head is embedded into the CacheNode tree, but eventually we'll lift it out\n // and store it on the top-level state object.\n //\n // For statically-generated-at-build-time HTML pages, the tree baked into\n // the initial RSC payload won't have the correct segment inlining hints\n // because those are computed after the pre-render. The server marks these\n // trees with InliningHintsStale, which causes the route cache entry to be\n // immediately expired. The next prefetch will re-fetch the tree with\n // correct hints from the /_tree response.\n const acc = { metadataVaryPath: null }\n const initialRouteTree = decodeTransportTreeIntoRouteTree(\n initialTransportData.t,\n // There's no base tree to overlay onto; the initial payload is a full\n // render from the root.\n null,\n initialRenderedSearch as NormalizedSearch,\n acc\n )\n const metadataVaryPath = acc.metadataVaryPath\n const initialTask = createInitialCacheNodeForHydration(\n navigatedAt,\n initialRouteTree,\n initialHead,\n computeDynamicStaleAt(\n navigatedAt,\n initialDynamicStaleTimeSeconds ?? UnknownDynamicStaleTime\n )\n )\n\n // The following only applies in the browser (location !== null) since neither\n // route learning nor segment cache state persists from SSR to client.\n if (location !== null && metadataVaryPath !== null) {\n // Learn the route pattern so we can predict it for future navigations.\n discoverKnownRoute(\n Date.now(),\n location.pathname,\n location.search as NormalizedSearch,\n null, // nextUrl — initial render is never an interception\n null, // No pending entry\n initialRouteTree,\n metadataVaryPath,\n initialCouldBeIntercepted,\n canonicalUrl,\n initialSupportsPerSegmentPrefetching,\n false // hasDynamicRewrite\n )\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the Cached\n // Navigations behavior should work in combination with App Shells.\n\n // Write the initial seed data into the segment cache so subsequent\n // navigations to the initial page can serve cached segments instantly.\n if (initialStaleTime !== undefined) {\n if (\n initialStaticStageByteLength !== undefined &&\n initialFlightStreamForCache != null\n ) {\n // Partially static page — truncate the cloned Flight stream at the\n // static stage byte boundary, decode, and cache the static subset.\n // Promise.resolve wraps the Flight-deserialized thenable into a\n // native Promise so we can chain `.then` on it safely.\n Promise.resolve(initialStaticStageByteLength)\n .then(async (byteLength) => {\n const staticStageResponse =\n await decodeStageUntilBoundary<InitialRSCPayload>(\n initialFlightStreamForCache,\n byteLength,\n undefined\n )\n const now = Date.now()\n const staleAt = await resolveStaleAt(now, staticStageResponse.s)\n\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.t,\n undefined, // no build ID mismatch check for initial HTML\n staticStageResponse.r ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n true // isResponsePartial\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n } else {\n // Fully static page — cache the entire decoded seed data as-is. We're\n // not using the initial response here (which would allow us to combine\n // the two branches) to avoid unnecessary decoding of the Flight data,\n // since we can just take the seed data that we already decoded during\n // hydration and write it into the cache directly.\n const now = Date.now()\n\n resolveStaleAt(now, initialStaleTime)\n .then((staleAt) => {\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n initialTransportData,\n undefined, // buildId — not applicable for initial HTML\n initialRootVaryParams ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n false // isResponsePartial\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n\n // Cancel the stream clone — fully static path doesn't need it.\n initialFlightStreamForCache?.cancel()\n }\n } else {\n // No caching — cancel the unused stream clone.\n initialFlightStreamForCache?.cancel()\n }\n\n // If the initial RSC payload includes an embedded runtime prefetch stream,\n // decode it and write the runtime data into the segment cache. This allows\n // subsequent navigations to serve runtime-prefetchable content from cache\n // without a separate prefetch request.\n if (initialRuntimePrefetchStream != null) {\n processRuntimePrefetchStream(\n Date.now(),\n initialRuntimePrefetchStream,\n initialTree,\n initialRenderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n Date.now(),\n FetchStrategy.PPRRuntime,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null\n )\n }\n })\n .catch(() => {\n // Runtime prefetch cache write failed. Not fatal — the page rendered\n // normally, we just won't cache runtime data.\n })\n }\n }\n\n // NOTE: We intentionally don't check if any data needs to be fetched from the\n // server. We assume the initial hydration payload is sufficient to render\n // the page.\n //\n // The completeness of the initial data is an important property that we rely\n // on as a last-ditch mechanism for recovering the app; we must always be able\n // to reload a fresh HTML document to get to a consistent state.\n //\n // In the future, there may be cases where the server intentionally sends\n // partial data and expects the client to fill in the rest, in which case this\n // logic may change. (There already is a similar case where the server sends\n // _no_ hydration data in the HTML document at all, and the client fetches it\n // separately, but that's different because we still end up hydrating with a\n // complete tree.)\n\n const initialState = {\n tree: initialTask.route,\n cache: initialTask.node,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // First render needs to preserve the previous window.history.state\n // to avoid it being overwritten on navigation back/forward with MPA Navigation.\n preserveCustomHistoryState: true,\n },\n focusAndScrollRef: {\n scrollRef: null,\n forceScroll: false,\n onlyHashChange: false,\n hashFragment: null,\n },\n canonicalUrl,\n renderedSearch: initialRenderedSearch,\n // the || operator is intentional, the pathname can be an empty string\n nextUrl:\n (extractPathFromFlightRouterState(initialTree) || location?.pathname) ??\n null,\n previousNextUrl: null,\n debugInfo: null,\n }\n\n return initialState\n}\n"],"names":["createInitialRouterState","navigatedAt","initialRSCPayload","initialFlightStreamForCache","location","c","initialCanonicalUrlParts","t","initialTransportData","q","initialRenderedSearch","i","initialCouldBeIntercepted","S","initialSupportsPerSegmentPrefetching","s","initialStaleTime","l","initialStaticStageByteLength","r","initialRootVaryParams","p","initialRuntimePrefetchStream","d","initialDynamicStaleTimeSeconds","initialCanonicalUrl","join","initialHead","h","initialTree","transportNodeToFlightRouterState","canonicalUrl","createHrefFromUrl","acc","metadataVaryPath","initialRouteTree","decodeTransportTreeIntoRouteTree","initialTask","createInitialCacheNodeForHydration","computeDynamicStaleAt","UnknownDynamicStaleTime","discoverKnownRoute","Date","now","pathname","search","undefined","Promise","resolve","then","byteLength","staticStageResponse","decodeStageUntilBoundary","staleAt","resolveStaleAt","writePrerenderResponseIntoCache","FetchStrategy","PPR","catch","cancel","processRuntimePrefetchStream","processed","writeDynamicRenderResponseIntoCache","PPRRuntime","buildId","isResponsePartial","headVaryParams","rootVaryParamsIterable","navigationSeed","initialState","tree","route","cache","node","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","scrollRef","forceScroll","onlyHashChange","hashFragment","renderedSearch","nextUrl","extractPathFromFlightRouterState","previousNextUrl","debugInfo"],"mappings":";;;;+BA+BgBA;;;eAAAA;;;mCA7BkB;oCACe;8BAGA;gCACE;uBAM5C;sCAC0C;uBACnB;yBAIvB;qCACkC;kCACN;AAU5B,SAASA,yBAAyB,EACvCC,WAAW,EACXC,iBAAiB,EACjBC,2BAA2B,EAC3BC,QAAQ,EACqB;IAC7B,MAAM,EACJC,GAAGC,wBAAwB,EAC3BC,GAAGC,oBAAoB,EACvBC,GAAGC,qBAAqB,EACxBC,GAAGC,yBAAyB,EAC5BC,GAAGC,oCAAoC,EACvCC,GAAGC,gBAAgB,EACnBC,GAAGC,4BAA4B,EAC/BC,GAAGC,qBAAqB,EACxBC,GAAGC,4BAA4B,EAC/BC,GAAGC,8BAA8B,EAClC,GAAGtB;IAEJ,sFAAsF;IACtF,kGAAkG;IAClG,mCAAmC;IACnC,MAAMuB,sBAAsBnB,yBAAyBoB,IAAI,CAAC;IAE1D,MAAMC,cAAcnB,qBAAqBoB,CAAC,CAACT,CAAC;IAE5C,uEAAuE;IACvE,qEAAqE;IACrE,UAAU;IACV,MAAMU,cAAcC,IAAAA,8CAAgC,EAACtB,qBAAqBD,CAAC;IAE3E,MAAMwB,eACJ,6EAA6E;IAC7E,kJAAkJ;IAClJ3B,WAEI4B,IAAAA,oCAAiB,EAAC5B,YAClBqB;IAEN,sEAAsE;IACtE,2EAA2E;IAC3E,wEAAwE;IACxE,+BAA+B;IAC/B,2EAA2E;IAC3E,6EAA6E;IAC7E,8CAA8C;IAC9C,EAAE;IACF,yEAAyE;IACzE,wEAAwE;IACxE,0EAA0E;IAC1E,0EAA0E;IAC1E,qEAAqE;IACrE,0CAA0C;IAC1C,MAAMQ,MAAM;QAAEC,kBAAkB;IAAK;IACrC,MAAMC,mBAAmBC,IAAAA,sDAAgC,EACvD5B,qBAAqBD,CAAC,EACtB,sEAAsE;IACtE,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9B;QACAC,mBAAmB;YACjBC,WAAW;YACXC,aAAa;YACbC,gBAAgB;YAChBC,cAAc;QAChB;QACAnD;QACAoD,gBAAgBzE;QAChB,sEAAsE;QACtE0E,SACE,AAACC,CAAAA,IAAAA,oDAAgC,EAACxD,gBAAgBzB,UAAUwC,QAAO,KACnE;QACF0C,iBAAiB;QACjBC,WAAW;IACb;IAEA,OAAOlB;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/client/components/router-reducer/create-initial-router-state.ts"],"sourcesContent":["import type { InitialRSCPayload } from '../../../shared/lib/app-router-types'\n\nimport { createHrefFromUrl } from './create-href-from-url'\nimport { extractPathFromFlightRouterState } from './compute-changed-path'\n\nimport type { AppRouterState } from './router-reducer-types'\nimport { transportNodeToFlightRouterState } from '../../../shared/lib/rsc-transport'\nimport { createInitialCacheNodeForHydration } from './ppr-navigations'\nimport {\n resolveStaleAt,\n processRuntimePrefetchStream,\n segmentCacheMap,\n writeDynamicRenderResponseIntoCache,\n writePrerenderResponseIntoCache,\n} from '../segment-cache/cache'\nimport { decodeTransportTreeIntoRouteTree } from '../segment-cache/decode-server-response'\nimport { FetchStrategy } from '../segment-cache/types'\nimport {\n UnknownDynamicStaleTime,\n computeDynamicStaleAt,\n} from '../segment-cache/bfcache'\nimport { decodeStageUntilBoundary } from './fetch-server-response'\nimport { discoverKnownRoute } from '../segment-cache/optimistic-routes'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\n\nexport interface InitialRouterStateParameters {\n navigatedAt: number\n initialRSCPayload: InitialRSCPayload\n initialFlightStreamForCache?: ReadableStream<Uint8Array> | null\n location: Location | null\n}\n\nexport function createInitialRouterState({\n navigatedAt,\n initialRSCPayload,\n initialFlightStreamForCache,\n location,\n}: InitialRouterStateParameters): AppRouterState {\n const {\n c: initialCanonicalUrlParts,\n t: initialTransportData,\n q: initialRenderedSearch,\n i: initialCouldBeIntercepted,\n S: initialSupportsPerSegmentPrefetching,\n s: initialStaleTime,\n l: initialStaticStageByteLength,\n r: initialRootVaryParams,\n p: initialRuntimePrefetchStream,\n d: initialDynamicStaleTimeSeconds,\n } = initialRSCPayload\n\n // When initialized on the server, the canonical URL is provided as an array of parts.\n // This is to ensure that when the RSC payload streamed to the client, crawlers don't interpret it\n // as a URL that should be crawled.\n const initialCanonicalUrl = initialCanonicalUrlParts.join('/')\n\n const initialHead = initialTransportData.h.r\n\n // The initial router state tree, derived from the transport tree. Page\n // segments keep their search params, which travel inside the segment\n // string.\n const initialTree = transportNodeToFlightRouterState(initialTransportData.t)\n\n const canonicalUrl =\n // location.href is read as the initial value for canonicalUrl in the browser\n // This is safe to do as canonicalUrl can't be rendered, it's only used to control the history updates in the useEffect further down in this file.\n location\n ? // window.location does not have the same type as URL but has all the fields createHrefFromUrl needs.\n createHrefFromUrl(location)\n : initialCanonicalUrl\n\n // Decode the initial transport tree into the RouteTree type, with the\n // payload's render output embedded on each node. (discoverKnownRoute below\n // stores this tree in the route cache, which strips the data on write —\n // see stripDataFromRouteTree.)\n // NOTE: The metadataVaryPath isn't used for anything currently because the\n // head is embedded into the CacheNode tree, but eventually we'll lift it out\n // and store it on the top-level state object.\n //\n // For statically-generated-at-build-time HTML pages, the tree baked into\n // the initial RSC payload won't have the correct segment inlining hints\n // because those are computed after the pre-render. The server marks these\n // trees with InliningHintsStale, which causes the route cache entry to be\n // immediately expired. The next prefetch will re-fetch the tree with\n // correct hints from the /_tree response.\n const acc = { metadataVaryPath: null }\n const initialRouteTree = decodeTransportTreeIntoRouteTree(\n initialTransportData.t,\n // There's no base tree to overlay onto; the initial payload is a full\n // render from the root.\n null,\n initialRenderedSearch as NormalizedSearch,\n acc\n )\n const metadataVaryPath = acc.metadataVaryPath\n const initialTask = createInitialCacheNodeForHydration(\n navigatedAt,\n initialRouteTree,\n initialHead,\n computeDynamicStaleAt(\n navigatedAt,\n initialDynamicStaleTimeSeconds ?? UnknownDynamicStaleTime\n )\n )\n\n // The following only applies in the browser (location !== null) since neither\n // route learning nor segment cache state persists from SSR to client.\n if (location !== null && metadataVaryPath !== null) {\n // Learn the route pattern so we can predict it for future navigations.\n discoverKnownRoute(\n Date.now(),\n location.pathname,\n location.search as NormalizedSearch,\n null, // nextUrl — initial render is never an interception\n null, // No pending entry\n initialRouteTree,\n metadataVaryPath,\n initialCouldBeIntercepted,\n canonicalUrl,\n initialSupportsPerSegmentPrefetching,\n false // hasDynamicRewrite\n )\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the Cached\n // Navigations behavior should work in combination with App Shells.\n\n // Write the initial seed data into the segment cache so subsequent\n // navigations to the initial page can serve cached segments instantly.\n if (initialStaleTime !== undefined) {\n if (\n initialStaticStageByteLength !== undefined &&\n initialFlightStreamForCache != null\n ) {\n // Partially static page — truncate the cloned Flight stream at the\n // static stage byte boundary, decode, and cache the static subset.\n // Promise.resolve wraps the Flight-deserialized thenable into a\n // native Promise so we can chain `.then` on it safely.\n Promise.resolve(initialStaticStageByteLength)\n .then(async (byteLength) => {\n const staticStageResponse =\n await decodeStageUntilBoundary<InitialRSCPayload>(\n initialFlightStreamForCache,\n byteLength,\n undefined\n )\n const now = Date.now()\n const staleAt = await resolveStaleAt(now, staticStageResponse.s)\n\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.t,\n undefined, // no build ID mismatch check for initial HTML\n staticStageResponse.r ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n true, // isResponsePartial\n segmentCacheMap // hydration writes are bound to the shared map\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n } else {\n // Fully static page — cache the entire decoded seed data as-is. We're\n // not using the initial response here (which would allow us to combine\n // the two branches) to avoid unnecessary decoding of the Flight data,\n // since we can just take the seed data that we already decoded during\n // hydration and write it into the cache directly.\n const now = Date.now()\n\n resolveStaleAt(now, initialStaleTime)\n .then((staleAt) => {\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n initialTransportData,\n undefined, // buildId — not applicable for initial HTML\n initialRootVaryParams ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n false, // isResponsePartial\n segmentCacheMap // hydration writes are bound to the shared map\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n\n // Cancel the stream clone — fully static path doesn't need it.\n initialFlightStreamForCache?.cancel()\n }\n } else {\n // No caching — cancel the unused stream clone.\n initialFlightStreamForCache?.cancel()\n }\n\n // If the initial RSC payload includes an embedded runtime prefetch stream,\n // decode it and write the runtime data into the segment cache. This allows\n // subsequent navigations to serve runtime-prefetchable content from cache\n // without a separate prefetch request.\n if (initialRuntimePrefetchStream != null) {\n processRuntimePrefetchStream(\n Date.now(),\n initialRuntimePrefetchStream,\n initialTree,\n initialRenderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n Date.now(),\n FetchStrategy.PPRRuntime,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null,\n segmentCacheMap // hydration writes are bound to the shared map\n )\n }\n })\n .catch(() => {\n // Runtime prefetch cache write failed. Not fatal — the page rendered\n // normally, we just won't cache runtime data.\n })\n }\n }\n\n // NOTE: We intentionally don't check if any data needs to be fetched from the\n // server. We assume the initial hydration payload is sufficient to render\n // the page.\n //\n // The completeness of the initial data is an important property that we rely\n // on as a last-ditch mechanism for recovering the app; we must always be able\n // to reload a fresh HTML document to get to a consistent state.\n //\n // In the future, there may be cases where the server intentionally sends\n // partial data and expects the client to fill in the rest, in which case this\n // logic may change. (There already is a similar case where the server sends\n // _no_ hydration data in the HTML document at all, and the client fetches it\n // separately, but that's different because we still end up hydrating with a\n // complete tree.)\n\n const initialState = {\n tree: initialTask.route,\n cache: initialTask.node,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // First render needs to preserve the previous window.history.state\n // to avoid it being overwritten on navigation back/forward with MPA Navigation.\n preserveCustomHistoryState: true,\n },\n scrollRef: {\n scrollRef: null,\n forceScroll: false,\n onlyHashChange: false,\n hashFragment: null,\n },\n canonicalUrl,\n renderedSearch: initialRenderedSearch,\n // the || operator is intentional, the pathname can be an empty string\n nextUrl:\n (extractPathFromFlightRouterState(initialTree) || location?.pathname) ??\n null,\n previousNextUrl: null,\n debugInfo: null,\n }\n\n return initialState\n}\n"],"names":["createInitialRouterState","navigatedAt","initialRSCPayload","initialFlightStreamForCache","location","c","initialCanonicalUrlParts","t","initialTransportData","q","initialRenderedSearch","i","initialCouldBeIntercepted","S","initialSupportsPerSegmentPrefetching","s","initialStaleTime","l","initialStaticStageByteLength","r","initialRootVaryParams","p","initialRuntimePrefetchStream","d","initialDynamicStaleTimeSeconds","initialCanonicalUrl","join","initialHead","h","initialTree","transportNodeToFlightRouterState","canonicalUrl","createHrefFromUrl","acc","metadataVaryPath","initialRouteTree","decodeTransportTreeIntoRouteTree","initialTask","createInitialCacheNodeForHydration","computeDynamicStaleAt","UnknownDynamicStaleTime","discoverKnownRoute","Date","now","pathname","search","undefined","Promise","resolve","then","byteLength","staticStageResponse","decodeStageUntilBoundary","staleAt","resolveStaleAt","writePrerenderResponseIntoCache","FetchStrategy","PPR","segmentCacheMap","catch","cancel","processRuntimePrefetchStream","processed","writeDynamicRenderResponseIntoCache","PPRRuntime","buildId","isResponsePartial","headVaryParams","rootVaryParamsIterable","navigationSeed","initialState","tree","route","cache","node","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","scrollRef","forceScroll","onlyHashChange","hashFragment","renderedSearch","nextUrl","extractPathFromFlightRouterState","previousNextUrl","debugInfo"],"mappings":";;;;+BAgCgBA;;;eAAAA;;;mCA9BkB;oCACe;8BAGA;gCACE;uBAO5C;sCAC0C;uBACnB;yBAIvB;qCACkC;kCACN;AAU5B,SAASA,yBAAyB,EACvCC,WAAW,EACXC,iBAAiB,EACjBC,2BAA2B,EAC3BC,QAAQ,EACqB;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jB;AACT","ignoreList":[0]} |
| import type { FlightRouterState } from '../../../shared/lib/app-router-types'; | ||
| import type { CacheNode } from '../../../shared/lib/app-router-types'; | ||
| import type { HeadData, ScrollRef } from '../../../shared/lib/app-router-types'; | ||
| import { type RouteTree, type RSCSegmentData, type RefreshState, type FulfilledRouteCacheEntry } from '../segment-cache/cache'; | ||
| import { type SegmentCacheEntry, type RouteTree, type RSCSegmentData, type RefreshState, type FulfilledRouteCacheEntry } from '../segment-cache/cache'; | ||
| import type { CacheMap } from '../segment-cache/cache-map'; | ||
| import { type PageVaryPath } from '../segment-cache/vary-path'; | ||
@@ -49,4 +50,4 @@ export type NavigationTask = { | ||
| export declare function createInitialCacheNodeForHydration(navigatedAt: number, initialTree: RouteTree<RSCSegmentData | null>, seedHead: HeadData, seedDynamicStaleAt: number): NavigationTask; | ||
| export declare function startPPRNavigation(navigatedAt: number, oldUrl: URL, oldRenderedSearch: string, oldCacheNode: CacheNode | null, oldRouterState: FlightRouterState, newRouteTree: RouteTree<RSCSegmentData | null>, newMetadataVaryPath: PageVaryPath | null, freshness: FreshnessPolicy, seedHead: HeadData | null, seedDynamicStaleAt: number, isSamePageNavigation: boolean, accumulation: NavigationRequestAccumulation, restrictToShell: boolean): NavigationTask | null; | ||
| export declare function spawnDynamicRequests(task: NavigationTask, primaryUrl: URL, nextUrl: string | null, freshnessPolicy: FreshnessPolicy, accumulation: NavigationRequestAccumulation, routeCacheEntry: FulfilledRouteCacheEntry | null, navigateType: 'push' | 'replace', navigationLock: NavigationLock | null, signal: AbortSignal | undefined): void; | ||
| export declare function startPPRNavigation(navigatedAt: number, oldUrl: URL, oldRenderedSearch: string, oldCacheNode: CacheNode | null, oldRouterState: FlightRouterState, newRouteTree: RouteTree<RSCSegmentData | null>, newMetadataVaryPath: PageVaryPath | null, freshness: FreshnessPolicy, seedHead: HeadData | null, seedDynamicStaleAt: number, isSamePageNavigation: boolean, accumulation: NavigationRequestAccumulation, map: CacheMap<SegmentCacheEntry>, restrictToShell: boolean): NavigationTask | null; | ||
| export declare function spawnDynamicRequests(task: NavigationTask, primaryUrl: URL, nextUrl: string | null, freshnessPolicy: FreshnessPolicy, accumulation: NavigationRequestAccumulation, routeCacheEntry: FulfilledRouteCacheEntry | null, navigateType: 'push' | 'replace', navigationLock: NavigationLock | null, map: CacheMap<SegmentCacheEntry>, signal: AbortSignal | undefined): void; | ||
| type PendingDeferredRsc<T> = Promise<T> & { | ||
@@ -53,0 +54,0 @@ status: 'pending'; |
@@ -77,3 +77,4 @@ "use strict"; | ||
| const navigateType = state.pushRef.pendingPush ? 'push' : 'replace'; | ||
| return (0, _navigation.navigateToKnownRoute)(now, state, currentUrl, currentCanonicalUrl, refreshSeed, currentUrl, currentRenderedSearch, state.cache, currentFlightRouterState, freshnessPolicy, nextUrlForRefresh, scrollBehavior, navigateType, navigationLock, null, // Refresh navigations don't use route prediction, so there's no route | ||
| return (0, _navigation.navigateToKnownRoute)(now, state, currentUrl, currentCanonicalUrl, refreshSeed, currentUrl, currentRenderedSearch, state.cache, currentFlightRouterState, freshnessPolicy, nextUrlForRefresh, scrollBehavior, navigateType, navigationLock, // A refresh is bound to the shared map. | ||
| _cache.segmentCacheMap, null, // Refresh navigations don't use route prediction, so there's no route | ||
| // cache entry to mark as having a dynamic rewrite on mismatch. If a | ||
@@ -80,0 +81,0 @@ // mismatch occurs, the retry handler will traverse the known route tree |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/refresh-reducer.ts"],"sourcesContent":["import type {\n ReadonlyReducerState,\n ReducerState,\n RefreshAction,\n} from '../router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer-types'\nimport { navigateToKnownRoute } from '../../segment-cache/navigation'\nimport { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response'\nimport { invalidateSegmentCacheEntries } from '../../segment-cache/cache'\nimport { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'\nimport { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations'\nimport {\n invalidateBfCache,\n UnknownDynamicStaleTime,\n} from '../../segment-cache/bfcache'\n\nexport function refreshReducer(\n state: ReadonlyReducerState,\n action: RefreshAction\n): ReducerState {\n // During a refresh, we invalidate the segment cache but not the route cache.\n // The route cache contains the tree structure (which segments exist at a\n // given URL) which doesn't change during a refresh. The segment cache\n // contains the actual RSC data which needs to be re-fetched.\n //\n // The Instant Navigation Testing API can bypass cache invalidation to\n // preserve prefetched data when refreshing after an MPA navigation. This is\n // only used for testing and is not exposed in production builds by default.\n const bypassCacheInvalidation =\n process.env.__NEXT_EXPOSE_TESTING_API && action.bypassCacheInvalidation\n if (!bypassCacheInvalidation) {\n const currentNextUrl = state.nextUrl\n const currentRouterState = state.tree\n invalidateSegmentCacheEntries(currentNextUrl, currentRouterState)\n }\n // A full refresh has no HMR generation to cancel.\n return refreshDynamicData(state, FreshnessPolicy.RefreshAll, undefined)\n}\n\nexport function refreshDynamicData(\n state: ReadonlyReducerState,\n freshnessPolicy: FreshnessPolicy.RefreshAll | FreshnessPolicy.HMRRefresh,\n signal: AbortSignal | undefined\n): ReducerState {\n // During a refresh, invalidate the BFCache, which may contain dynamic data.\n invalidateBfCache()\n\n const currentNextUrl = state.nextUrl\n\n // We always send the last next-url, not the current when performing a dynamic\n // request. This is because we update the next-url after a navigation, but we\n // want the same interception route to be matched that used the last next-url.\n const nextUrlForRefresh = hasInterceptionRouteInCurrentTree(state.tree)\n ? state.previousNextUrl || currentNextUrl\n : null\n\n // A refresh is modeled as a navigation to the current URL, but where any\n // existing dynamic data (including in shared layouts) is re-fetched.\n const currentCanonicalUrl = state.canonicalUrl\n const currentUrl = new URL(currentCanonicalUrl, location.origin)\n const currentRenderedSearch = state.renderedSearch\n const currentFlightRouterState = state.tree\n const scrollBehavior = ScrollBehavior.NoScroll\n const navigationLock = getCurrentNavigationLock()\n\n // Create a NavigationSeed from the current FlightRouterState.\n // TODO: Eventually we will store this type directly on the state object\n // instead of reconstructing it on demand. Part of a larger series of\n // refactors to unify the various tree types that the client deals with.\n const now = Date.now()\n // TODO: Store the dynamic stale time on the top-level state so it's known\n // during restores and refreshes.\n const refreshSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n null,\n currentRenderedSearch,\n UnknownDynamicStaleTime\n )\n\n // If the previous navigation hasn't pushed its history entry yet (React\n // hasn't committed its state), this refresh may commit in its place, so it\n // takes over the push. If the navigation does commit first, HistoryUpdater\n // sees that the URL already matches and replaces instead.\n const navigateType = state.pushRef.pendingPush ? 'push' : 'replace'\n return navigateToKnownRoute(\n now,\n state,\n currentUrl,\n currentCanonicalUrl,\n refreshSeed,\n currentUrl,\n currentRenderedSearch,\n state.cache,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrlForRefresh,\n scrollBehavior,\n navigateType,\n navigationLock,\n null,\n // Refresh navigations don't use route prediction, so there's no route\n // cache entry to mark as having a dynamic rewrite on mismatch. If a\n // mismatch occurs, the retry handler will traverse the known route tree\n // to find and mark the entry.\n null,\n signal\n )\n}\n"],"names":["refreshDynamicData","refreshReducer","state","action","bypassCacheInvalidation","process","env","__NEXT_EXPOSE_TESTING_API","currentNextUrl","nextUrl","currentRouterState","tree","invalidateSegmentCacheEntries","FreshnessPolicy","RefreshAll","undefined","freshnessPolicy","signal","invalidateBfCache","nextUrlForRefresh","hasInterceptionRouteInCurrentTree","previousNextUrl","currentCanonicalUrl","canonicalUrl","currentUrl","URL","location","origin","currentRenderedSearch","renderedSearch","currentFlightRouterState","scrollBehavior","ScrollBehavior","NoScroll","navigationLock","getCurrentNavigationLock","now","Date","refreshSeed","convertServerPatchToFullTree","UnknownDynamicStaleTime","navigateType","pushRef","pendingPush","navigateToKnownRoute","cache"],"mappings":";;;;;;;;;;;;;;;IAuCgBA,kBAAkB;eAAlBA;;IAvBAC,cAAc;eAAdA;;;oCAXe;4BACM;sCACQ;uBACC;mDACI;gCACQ;yBAInD;AAEA,SAASA,eACdC,KAA2B,EAC3BC,MAAqB;IAErB,6EAA6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,MAAMC,eAAevC,MAAMwC,OAAO,CAACC,WAAW,GAAG,SAAS;IAC1D,OAAOC,IAAAA,gCAAoB,EACzBR,KACAlC,OACAsB,YACAF,qBACAgB,aACAd,YACAI,uBACA1B,MAAM2C,KAAK,EACXf,0BACAd,iBACAG,mBACAY,gBACAU,cACAP,gBACA,MACA,sEAAsE;IACtE,oEAAoE;IACpE,wEAAwE;IACxE,8BAA8B;IAC9B,MACAjB;AAEJ","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/refresh-reducer.ts"],"sourcesContent":["import type {\n ReadonlyReducerState,\n ReducerState,\n RefreshAction,\n} from '../router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer-types'\nimport { navigateToKnownRoute } from '../../segment-cache/navigation'\nimport { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response'\nimport {\n invalidateSegmentCacheEntries,\n segmentCacheMap,\n} from '../../segment-cache/cache'\nimport { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'\nimport { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations'\nimport {\n invalidateBfCache,\n UnknownDynamicStaleTime,\n} from '../../segment-cache/bfcache'\n\nexport function refreshReducer(\n state: ReadonlyReducerState,\n action: RefreshAction\n): ReducerState {\n // During a refresh, we invalidate the segment cache but not the route cache.\n // The route cache contains the tree structure (which segments exist at a\n // given URL) which doesn't change during a refresh. The segment cache\n // contains the actual RSC data which needs to be re-fetched.\n //\n // The Instant Navigation Testing API can bypass cache invalidation to\n // preserve prefetched data when refreshing after an MPA navigation. This is\n // only used for testing and is not exposed in production builds by default.\n const bypassCacheInvalidation =\n process.env.__NEXT_EXPOSE_TESTING_API && action.bypassCacheInvalidation\n if (!bypassCacheInvalidation) {\n const currentNextUrl = state.nextUrl\n const currentRouterState = state.tree\n invalidateSegmentCacheEntries(currentNextUrl, currentRouterState)\n }\n // A full refresh has no HMR generation to cancel.\n return refreshDynamicData(state, FreshnessPolicy.RefreshAll, undefined)\n}\n\nexport function refreshDynamicData(\n state: ReadonlyReducerState,\n freshnessPolicy: FreshnessPolicy.RefreshAll | FreshnessPolicy.HMRRefresh,\n signal: AbortSignal | undefined\n): ReducerState {\n // During a refresh, invalidate the BFCache, which may contain dynamic data.\n invalidateBfCache()\n\n const currentNextUrl = state.nextUrl\n\n // We always send the last next-url, not the current when performing a dynamic\n // request. This is because we update the next-url after a navigation, but we\n // want the same interception route to be matched that used the last next-url.\n const nextUrlForRefresh = hasInterceptionRouteInCurrentTree(state.tree)\n ? state.previousNextUrl || currentNextUrl\n : null\n\n // A refresh is modeled as a navigation to the current URL, but where any\n // existing dynamic data (including in shared layouts) is re-fetched.\n const currentCanonicalUrl = state.canonicalUrl\n const currentUrl = new URL(currentCanonicalUrl, location.origin)\n const currentRenderedSearch = state.renderedSearch\n const currentFlightRouterState = state.tree\n const scrollBehavior = ScrollBehavior.NoScroll\n const navigationLock = getCurrentNavigationLock()\n\n // Create a NavigationSeed from the current FlightRouterState.\n // TODO: Eventually we will store this type directly on the state object\n // instead of reconstructing it on demand. Part of a larger series of\n // refactors to unify the various tree types that the client deals with.\n const now = Date.now()\n // TODO: Store the dynamic stale time on the top-level state so it's known\n // during restores and refreshes.\n const refreshSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n null,\n currentRenderedSearch,\n UnknownDynamicStaleTime\n )\n\n // If the previous navigation hasn't pushed its history entry yet (React\n // hasn't committed its state), this refresh may commit in its place, so it\n // takes over the push. If the navigation does commit first, HistoryUpdater\n // sees that the URL already matches and replaces instead.\n const navigateType = state.pushRef.pendingPush ? 'push' : 'replace'\n return navigateToKnownRoute(\n now,\n state,\n currentUrl,\n currentCanonicalUrl,\n refreshSeed,\n currentUrl,\n currentRenderedSearch,\n state.cache,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrlForRefresh,\n scrollBehavior,\n navigateType,\n navigationLock,\n // A refresh is bound to the shared map.\n segmentCacheMap,\n null,\n // Refresh navigations don't use route prediction, so there's no route\n // cache entry to mark as having a dynamic rewrite on mismatch. If a\n // mismatch occurs, the retry handler will traverse the known route tree\n // to find and mark the entry.\n null,\n signal\n )\n}\n"],"names":["refreshDynamicData","refreshReducer","state","action","bypassCacheInvalidation","process","env","__NEXT_EXPOSE_TESTING_API","currentNextUrl","nextUrl","currentRouterState","tree","invalidateSegmentCacheEntries","FreshnessPolicy","RefreshAll","undefined","freshnessPolicy","signal","invalidateBfCache","nextUrlForRefresh","hasInterceptionRouteInCurrentTree","previousNextUrl","currentCanonicalUrl","canonicalUrl","currentUrl","URL","location","origin","currentRenderedSearch","renderedSearch","currentFlightRouterState","scrollBehavior","ScrollBehavior","NoScroll","navigationLock","getCurrentNavigationLock","now","Date","refreshSeed","convertServerPatchToFullTree","UnknownDynamicStaleTime","navigateType","pushRef","pendingPush","navigateToKnownRoute","cache","segmentCacheMap"],"mappings":";;;;;;;;;;;;;;;IA0CgBA,kBAAkB;eAAlBA;;IAvBAC,cAAc;eAAdA;;;oCAde;4BACM;sCACQ;uBAItC;mDAC2C;gCACQ;yBAInD;AAEA,SAASA,eACdC,KAA2B,EAC3BC,MAAqB;IAErB,6EAA6E;IAC7E,yEAAyE;IACzE,sEAAsE;IACtE,6DAA6D;IAC7D,EAAE;IACF,sEAAsE;IACtE,4EAA4E;IAC5E,4EAA4E;IAC5E,MAAMC,0BACJC,QAAQC,GAAG,CAACC,yBAAyB,IAAIJ,OAAOC,uBAAuB;IACzE,IAAI,CAACA,yBAAyB;QAC5B,MAAMI,iBAAiBN,MAAMO,OAAO;QACpC,MAAMC,qBAAqBR,MAAMS,IAAI;QACrCC,IAAAA,oCAA6B,EAACJ,gBAAgBE;IAChD;IACA,kDAAkD;IAClD,OAAOV,mBAAmBE,OAAOW,+BAAe,CAACC,UAAU,EAAEC;AAC/D;AAEO,SAASf,mBACdE,KAA2B,EAC3Bc,eAAwE,EACxEC,MAA+B;IAE/B,4EAA4E;IAC5EC,IAAAA,0BAAiB;IAEjB,MAAMV,iBAAiBN,MAAMO,OAAO;IAEpC,8EAA8E;IAC9E,6EAA6E;IAC7E,8EAA8E;IAC9E,MAAMU,oBAAoBC,IAAAA,oEAAiC,EAAClB,MAAMS,IAAI,IAClET,MAAMmB,eAAe,IAAIb,iBACzB;IAEJ,yEAAyE;IACzE,qEAAqE;IACrE,MAAMc,sBAAsBpB,MAAMqB,YAAY;IAC9C,MAAMC,aAAa,IAAIC,IAAIH,qBAAqBI,SAASC,MAAM;IAC/D,MAAMC,wBAAwB1B,MAAM2B,cAAc;IAClD,MAAMC,2BAA2B5B,MAAMS,IAAI;IAC3C,MAAMoB,iBAAiBC,kCAAc,CAACC,QAAQ;IAC9C,MAAMC,iBAAiBC,IAAAA,wCAAwB;IAE/C,8DAA8D;IAC9D,wEAAwE;IACxE,qEAAqE;IACrE,wEAAwE;IACxE,MAAMC,MAAMC,KAAKD,GAAG;IACpB,0EAA0E;IAC1E,iCAAiC;IACjC,MAAME,cAAcC,IAAAA,kDAA4B,EAC9CH,KACAN,0BACA,MACAF,uBACAY,gCAAuB;IAGzB,wEAAwE;IACxE,2EAA2E;IAC3E,2EAA2E;IAC3E,0DAA0D;IAC1D,MAAMC,eAAevC,MAAMwC,OAAO,CAACC,WAAW,GAAG,SAAS;IAC1D,OAAOC,IAAAA,gCAAoB,EACzBR,KACAlC,OACAsB,YACAF,qBACAgB,aACAd,YACAI,uBACA1B,MAAM2C,KAAK,EACXf,0BACAd,iBACAG,mBACAY,gBACAU,cACAP,gBACA,wCAAwC;IACxCY,sBAAe,EACf,MACA,sEAAsE;IACtE,oEAAoE;IACpE,wEAAwE;IACxE,8BAA8B;IAC9B,MACA7B;AAEJ","ignoreList":[0]} |
@@ -15,2 +15,3 @@ "use strict"; | ||
| const _decodeserverresponse = require("../../segment-cache/decode-server-response"); | ||
| const _cache = require("../../segment-cache/cache"); | ||
| const _bfcache = require("../../segment-cache/bfcache"); | ||
@@ -45,3 +46,4 @@ function restoreReducer(state, action) { | ||
| const restoreSeed = (0, _decodeserverresponse.convertServerPatchToFullTree)(now, treeToRestore, null, renderedSearch, _bfcache.UnknownDynamicStaleTime); | ||
| const task = (0, _pprnavigations.startPPRNavigation)(now, currentUrl, state.renderedSearch, state.cache, state.tree, restoreSeed.routeTree, restoreSeed.metadataVaryPath, _pprnavigations.FreshnessPolicy.HistoryTraversal, null, restoreSeed.dynamicStaleAt, false, accumulation, // A history-traversal restore never restricts to the shell. | ||
| const task = (0, _pprnavigations.startPPRNavigation)(now, currentUrl, state.renderedSearch, state.cache, state.tree, restoreSeed.routeTree, restoreSeed.metadataVaryPath, _pprnavigations.FreshnessPolicy.HistoryTraversal, null, restoreSeed.dynamicStaleAt, false, accumulation, // A history-traversal restore is bound to the shared map. | ||
| _cache.segmentCacheMap, // A history-traversal restore never restricts to the shell. | ||
| false); | ||
@@ -59,3 +61,4 @@ if (task === null) { | ||
| // normally rather than being withheld behind the lock. | ||
| null, // Not an HMR refresh, so there's no request generation to cancel. | ||
| null, // A history-traversal restore is bound to the shared map. | ||
| _cache.segmentCacheMap, // Not an HMR refresh, so there's no request generation to cancel. | ||
| undefined); | ||
@@ -62,0 +65,0 @@ // Instant Navigation Testing API: a traversal resets the lock to a fresh |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/restore-reducer.ts"],"sourcesContent":["import type {\n ReadonlyReducerState,\n ReducerState,\n RestoreAction,\n} from '../router-reducer-types'\nimport { extractPathFromFlightRouterState } from '../compute-changed-path'\nimport {\n FreshnessPolicy,\n resetNavigationLockToPending,\n spawnDynamicRequests,\n startPPRNavigation,\n type NavigationRequestAccumulation,\n} from '../ppr-navigations'\nimport type { FlightRouterState } from '../../../../shared/lib/app-router-types'\nimport {\n completeHardNavigation,\n completeTraverseNavigation,\n} from '../../segment-cache/navigation'\nimport { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response'\nimport { UnknownDynamicStaleTime } from '../../segment-cache/bfcache'\n\nexport function restoreReducer(\n state: ReadonlyReducerState,\n action: RestoreAction\n): ReducerState {\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 let treeToRestore: FlightRouterState | undefined\n let renderedSearch: string | undefined\n const historyState = action.historyState\n if (historyState) {\n treeToRestore = historyState.tree\n renderedSearch = historyState.renderedSearch\n } else {\n treeToRestore = state.tree\n renderedSearch = state.renderedSearch\n }\n\n const currentUrl = new URL(state.canonicalUrl, location.origin)\n const restoredUrl = action.url\n const restoredNextUrl =\n extractPathFromFlightRouterState(treeToRestore) ?? restoredUrl.pathname\n\n const now = Date.now()\n // TODO: Store the dynamic stale time on the top-level state so it's known\n // during restores and refreshes.\n const accumulation: NavigationRequestAccumulation = {\n separateRefreshUrls: null,\n scrollRef: null,\n }\n const restoreSeed = convertServerPatchToFullTree(\n now,\n treeToRestore,\n null,\n renderedSearch,\n UnknownDynamicStaleTime\n )\n const task = startPPRNavigation(\n now,\n currentUrl,\n state.renderedSearch,\n state.cache,\n state.tree,\n restoreSeed.routeTree,\n restoreSeed.metadataVaryPath,\n FreshnessPolicy.HistoryTraversal,\n null,\n restoreSeed.dynamicStaleAt,\n false,\n accumulation,\n // A history-traversal restore never restricts to the shell.\n false\n )\n\n if (task === null) {\n return completeHardNavigation(state, restoredUrl, 'replace')\n }\n spawnDynamicRequests(\n task,\n restoredUrl,\n restoredNextUrl,\n FreshnessPolicy.HistoryTraversal,\n accumulation,\n // History traversal doesn't use route prediction, so there's no route\n // cache entry to mark as having a dynamic rewrite on mismatch. If a\n // mismatch occurs, the retry handler will traverse the known route tree\n // to find and mark the entry.\n null,\n // History traversal always uses 'replace'.\n 'replace',\n // Instant Navigation Testing API: a traversal is not a capture. Spawn its\n // dynamic requests ungated (null lock) so they render from cache or fetch\n // normally rather than being withheld behind the lock.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n // Instant Navigation Testing API: a traversal resets the lock to a fresh\n // pending scope — releasing any data withheld by prior forward navigations and\n // returning the panel to \"awaiting\" — without ending the testing session.\n // No-op when the testing API is disabled or no lock is held.\n resetNavigationLockToPending()\n return completeTraverseNavigation(\n state,\n restoredUrl,\n renderedSearch,\n task.node,\n task.route,\n restoredNextUrl\n )\n}\n"],"names":["restoreReducer","state","action","treeToRestore","renderedSearch","historyState","tree","currentUrl","URL","canonicalUrl","location","origin","restoredUrl","url","restoredNextUrl","extractPathFromFlightRouterState","pathname","now","Date","accumulation","separateRefreshUrls","scrollRef","restoreSeed","convertServerPatchToFullTree","UnknownDynamicStaleTime","task","startPPRNavigation","cache","routeTree","metadataVaryPath","FreshnessPolicy","HistoryTraversal","dynamicStaleAt","completeHardNavigation","spawnDynamicRequests","undefined","resetNavigationLockToPending","completeTraverseNavigation","node","route"],"mappings":";;;;+BAqBgBA;;;eAAAA;;;oCAhBiC;gCAO1C;4BAKA;sCACsC;yBACL;AAEjC,SAASA,eACdC,KAA2B,EAC3BC,MAAqB;IAErB,0EAA0E;IAC1E,4FAA4F;IAC5F,gGAAgG;IAChG,6FAA6F;IAC7F,8DAA8D;IAC9D,yGAAyG;IACzG,IAAIC;IACJ,IAAIC;IACJ,MAAMC,eAAeH,OAAOG,YAAY;IACxC,IAAIA,cAAc;QAChBF,gBAAgBE,aAAaC,IAAI;QACjCF,iBAAiBC,aAAaD,cAAc;IAC9C,OAAO;QACLD,gBAAgBF,MAAMK,IAAI;QAC1BF,iBAAiBH,MAAMG,cAAc;IACvC;IAEA,MAAMG,aAAa,IAAIC,IAAIP,MAAMQ,YAAY,EAAEC,SAASC,MAAM;IAC9D,MAAMC,cAAcV,OAAOW,GAAG;IAC9B,MAAMC,kBACJC,IAAAA,oDAAgC,EAACZ,kBAAkBS,YAAYI,QAAQ;IAEzE,MAAMC,MAAMC,KAAKD,GAAG;IACpB,0EAA0E;IAC1E,iCAAiC;IACjC,MAAME,eAA8C;QAClDC,qBAAqB;QACrBC,WAAW;IACb;IACA,MAAMC,cAAcC,IAAAA,kDAA4B,EAC9CN,KACAd,eACA,MACAC,gBACAoB,gCAAuB;IAEzB,MAAMC,OAAOC,IAAAA,kCAAkB,EAC7BT,KACAV,YACAN,MAAMG,cAAc,EACpBH,MAAM0B,KAAK,EACX1B,MAAMK,IAAI,EACVgB,YAAYM,SAAS,EACrBN,YAAYO,gBAAgB,EAC5BC,+BAAe,CAACC,gBAAgB,EAChC,MACAT,YAAYU,cAAc,EAC1B,OACAb,cACA,4DAA4D;IAC5D;IAGF,IAAIM,SAAS,MAAM;QACjB,OAAOQ,IAAAA,kCAAsB,EAAChC,OAAOW,aAAa;IACpD;IACAsB,IAAAA,oCAAoB,EAClBT,MACAb,aACAE,iBACAgB,+BAAe,CAACC,gBAAgB,EAChCZ,cACA,sEAAsE;IACtE,oEAAoE;IACpE,wEAAwE;IACxE,8BAA8B;IAC9B,MACA,2CAA2C;IAC3C,WACA,0EAA0E;IAC1E,0EAA0E;IAC1E,uDAAuD;IACvD,MACA,kEAAkE;IAClEgB;IAEF,yEAAyE;IACzE,+EAA+E;IAC/E,0EAA0E;IAC1E,6DAA6D;IAC7DC,IAAAA,4CAA4B;IAC5B,OAAOC,IAAAA,sCAA0B,EAC/BpC,OACAW,aACAR,gBACAqB,KAAKa,IAAI,EACTb,KAAKc,KAAK,EACVzB;AAEJ","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/restore-reducer.ts"],"sourcesContent":["import type {\n ReadonlyReducerState,\n ReducerState,\n RestoreAction,\n} from '../router-reducer-types'\nimport { extractPathFromFlightRouterState } from '../compute-changed-path'\nimport {\n FreshnessPolicy,\n resetNavigationLockToPending,\n spawnDynamicRequests,\n startPPRNavigation,\n type NavigationRequestAccumulation,\n} from '../ppr-navigations'\nimport type { FlightRouterState } from '../../../../shared/lib/app-router-types'\nimport {\n completeHardNavigation,\n completeTraverseNavigation,\n} from '../../segment-cache/navigation'\nimport { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response'\nimport { segmentCacheMap } from '../../segment-cache/cache'\nimport { UnknownDynamicStaleTime } from '../../segment-cache/bfcache'\n\nexport function restoreReducer(\n state: ReadonlyReducerState,\n action: RestoreAction\n): ReducerState {\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 let treeToRestore: FlightRouterState | undefined\n let renderedSearch: string | undefined\n const historyState = action.historyState\n if (historyState) {\n treeToRestore = historyState.tree\n renderedSearch = historyState.renderedSearch\n } else {\n treeToRestore = state.tree\n renderedSearch = state.renderedSearch\n }\n\n const currentUrl = new URL(state.canonicalUrl, location.origin)\n const restoredUrl = action.url\n const restoredNextUrl =\n extractPathFromFlightRouterState(treeToRestore) ?? restoredUrl.pathname\n\n const now = Date.now()\n // TODO: Store the dynamic stale time on the top-level state so it's known\n // during restores and refreshes.\n const accumulation: NavigationRequestAccumulation = {\n separateRefreshUrls: null,\n scrollRef: null,\n }\n const restoreSeed = convertServerPatchToFullTree(\n now,\n treeToRestore,\n null,\n renderedSearch,\n UnknownDynamicStaleTime\n )\n const task = startPPRNavigation(\n now,\n currentUrl,\n state.renderedSearch,\n state.cache,\n state.tree,\n restoreSeed.routeTree,\n restoreSeed.metadataVaryPath,\n FreshnessPolicy.HistoryTraversal,\n null,\n restoreSeed.dynamicStaleAt,\n false,\n accumulation,\n // A history-traversal restore is bound to the shared map.\n segmentCacheMap,\n // A history-traversal restore never restricts to the shell.\n false\n )\n\n if (task === null) {\n return completeHardNavigation(state, restoredUrl, 'replace')\n }\n spawnDynamicRequests(\n task,\n restoredUrl,\n restoredNextUrl,\n FreshnessPolicy.HistoryTraversal,\n accumulation,\n // History traversal doesn't use route prediction, so there's no route\n // cache entry to mark as having a dynamic rewrite on mismatch. If a\n // mismatch occurs, the retry handler will traverse the known route tree\n // to find and mark the entry.\n null,\n // History traversal always uses 'replace'.\n 'replace',\n // Instant Navigation Testing API: a traversal is not a capture. Spawn its\n // dynamic requests ungated (null lock) so they render from cache or fetch\n // normally rather than being withheld behind the lock.\n null,\n // A history-traversal restore is bound to the shared map.\n segmentCacheMap,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n // Instant Navigation Testing API: a traversal resets the lock to a fresh\n // pending scope — releasing any data withheld by prior forward navigations and\n // returning the panel to \"awaiting\" — without ending the testing session.\n // No-op when the testing API is disabled or no lock is held.\n resetNavigationLockToPending()\n return completeTraverseNavigation(\n state,\n restoredUrl,\n renderedSearch,\n task.node,\n task.route,\n restoredNextUrl\n )\n}\n"],"names":["restoreReducer","state","action","treeToRestore","renderedSearch","historyState","tree","currentUrl","URL","canonicalUrl","location","origin","restoredUrl","url","restoredNextUrl","extractPathFromFlightRouterState","pathname","now","Date","accumulation","separateRefreshUrls","scrollRef","restoreSeed","convertServerPatchToFullTree","UnknownDynamicStaleTime","task","startPPRNavigation","cache","routeTree","metadataVaryPath","FreshnessPolicy","HistoryTraversal","dynamicStaleAt","segmentCacheMap","completeHardNavigation","spawnDynamicRequests","undefined","resetNavigationLockToPending","completeTraverseNavigation","node","route"],"mappings":";;;;+BAsBgBA;;;eAAAA;;;oCAjBiC;gCAO1C;4BAKA;sCACsC;uBACb;yBACQ;AAEjC,SAASA,eACdC,KAA2B,EAC3BC,MAAqB;IAErB,0EAA0E;IAC1E,4FAA4F;IAC5F,gGAAgG;IAChG,6FAA6F;IAC7F,8DAA8D;IAC9D,yGAAyG;IACzG,IAAIC;IACJ,IAAIC;IACJ,MAAMC,eAAeH,OAAOG,YAAY;IACxC,IAAIA,cAAc;QAChBF,gBAAgBE,aAAaC,IAAI;QACjCF,iBAAiBC,aAAaD,cAAc;IAC9C,OAAO;QACLD,gBAA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","ignoreList":[0]} |
@@ -323,3 +323,4 @@ "use strict"; | ||
| const navigationLock = (0, _pprnavigations.getCurrentNavigationLock)(); | ||
| return (0, _navigation.navigateToKnownRoute)(now, state, redirectUrl, redirectCanonicalUrl, redirectSeed, currentUrl, currentRenderedSearch, state.cache, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, null, // Server action redirects don't use route prediction - we already | ||
| return (0, _navigation.navigateToKnownRoute)(now, state, redirectUrl, redirectCanonicalUrl, redirectSeed, currentUrl, currentRenderedSearch, state.cache, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, // A server-action redirect navigation is bound to the shared map. | ||
| _cache.segmentCacheMap, null, // Server action redirects don't use route prediction - we already | ||
| // have the route tree from the server response. If a mismatch occurs | ||
@@ -326,0 +327,0 @@ // during dynamic data fetch, the retry handler will traverse the |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/server-action-reducer.ts"],"sourcesContent":["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 NEXT_REQUEST_ID_HEADER,\n} from '../../app-router-headers'\nimport { UnrecognizedActionError } from '../../unrecognized-action-error'\nimport { fetch } from '../../segment-cache/fetch'\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 type {\n ReadonlyReducerState,\n ReducerState,\n ServerActionAction,\n} from '../router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer-types'\nimport { assignLocation } from '../../../assign-location'\nimport { createHrefFromUrl } from '../create-href-from-url'\nimport type { PartialTransportData } from '../../../../shared/lib/rsc-transport'\nimport { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'\nimport { prepareFlightRouterStateForRequest } from '../../../flight-data-helpers'\nimport { getRedirectError } from '../../redirect'\nimport type { RedirectType } from '../../redirect-error'\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 { invalidateEntirePrefetchCache } from '../../segment-cache/cache'\nimport { startRevalidationCooldown } from '../../segment-cache/scheduler'\nimport { getDeploymentId } from '../../../../shared/lib/deployment-id'\nimport { getNavigationBuildId } from '../../../navigation-build-id'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../../lib/constants'\nimport {\n completeHardNavigation,\n navigateToKnownRoute,\n navigate,\n} from '../../segment-cache/navigation'\nimport { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response'\nimport { discoverKnownRoute } from '../../segment-cache/optimistic-routes'\nimport type { NormalizedSearch } from '../../segment-cache/cache-key'\nimport {\n ActionDidNotRevalidate,\n ActionDidRevalidateDynamicOnly,\n ActionDidRevalidateStaticAndDynamic,\n type ActionRevalidationKind,\n} from '../../../../shared/lib/action-revalidation-kind'\nimport { isExternalURL } from '../../app-router-utils'\nimport { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations'\nimport { processFetch } from '../fetch-server-response'\nimport {\n invalidateBfCache,\n UnknownDynamicStaleTime,\n} from '../../segment-cache/bfcache'\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.__NEXT_DEV_SERVER && process.env.__NEXT_REACT_DEBUG_CHANNEL) {\n createDebugChannel = (\n require('../../../dev/debug-channel') as typeof import('../../../dev/debug-channel')\n ).createDebugChannel\n}\n\n// TODO: Refactor to be a discriminated union. Or just get rid of it;\n// fetchServerAction only has one caller, no reason this intermediate type has\n// to exist.\ntype FetchServerActionResult = {\n redirectLocation: URL | undefined\n redirectType: RedirectType | undefined\n revalidationKind: ActionRevalidationKind\n actionResult: ActionResult | undefined\n /**\n * The transport data from the action response, or a URL string when the\n * response handling triggered an external (MPA) redirect.\n */\n actionFlightData: PartialTransportData | string | undefined\n actionFlightDataRenderedSearch: NormalizedSearch | undefined\n isPrerender: boolean\n couldBeIntercepted: boolean\n}\n\nasync function fetchServerAction(\n state: ReadonlyReducerState,\n nextUrl: ReadonlyReducerState['nextUrl'],\n action: ServerActionAction\n): Promise<FetchServerActionResult> {\n const { actionId, actionArgs } = action\n const temporaryReferences = createTemporaryReferenceSet()\n const info = extractInfoFromServerReferenceId(actionId)\n const usedArgs = omitUnusedArgs(actionArgs, info)\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 const deploymentId = getDeploymentId()\n if (deploymentId) {\n headers['x-deployment-id'] = deploymentId\n }\n\n if (nextUrl) {\n headers[NEXT_URL] = nextUrl\n }\n\n if (process.env.__NEXT_DEV_SERVER) {\n if (self.__next_r) {\n headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r\n }\n\n // Create a new request ID for the server action request. The server uses\n // this to tag debug information sent via WebSocket to the client, which\n // then routes those chunks to the debug channel associated with this ID.\n headers[NEXT_REQUEST_ID_HEADER] = crypto\n .getRandomValues(new Uint32Array(1))[0]\n .toString(16)\n }\n\n let res: Response\n try {\n res = await fetch(state.canonicalUrl, { method: 'POST', headers, body })\n // If the fetch succeeds while we're in the offline state, notify the\n // offline module so it can short-circuit the polling loop.\n if (process.env.__NEXT_USE_OFFLINE) {\n const { notifyOnline } =\n require('../../offline') as typeof import('../../offline')\n notifyOnline()\n }\n } catch (err) {\n if (process.env.__NEXT_USE_OFFLINE) {\n const { checkOfflineError, getOffline, waitForConnection } =\n require('../../offline') as typeof import('../../offline')\n if (checkOfflineError(err)) {\n // It's safe to replay the action because the fetch rejection\n // means the request never reached the server — there are no\n // side effects to duplicate.\n const offline = getOffline()\n if (offline !== null) {\n await waitForConnection(offline)\n }\n return fetchServerAction(state, nextUrl, action)\n }\n }\n throw err\n }\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 = 'push'\n break\n case 'replace':\n redirectType = 'replace'\n break\n default:\n redirectType = undefined\n }\n\n const isPrerender = !!res.headers.get(NEXT_IS_PRERENDER_HEADER)\n\n let revalidationKind: ActionRevalidationKind = ActionDidNotRevalidate\n try {\n const revalidationHeader = res.headers.get('x-action-revalidated')\n if (revalidationHeader) {\n const parsedKind = JSON.parse(revalidationHeader)\n if (\n parsedKind === ActionDidRevalidateStaticAndDynamic ||\n parsedKind === ActionDidRevalidateDynamicOnly\n ) {\n revalidationKind = parsedKind\n }\n }\n } catch {}\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 let actionFlightDataRenderedSearch: FetchServerActionResult['actionFlightDataRenderedSearch']\n let couldBeIntercepted: boolean = false\n\n if (isRscResponse) {\n // Server action redirect responses carry the Flight data of the redirect\n // target, which may be prerendered with a completeness marker byte\n // prepended. Strip it before passing to Flight.\n const responsePromise = redirectLocation\n ? processFetch(res).then(({ response: r }) => r)\n : Promise.resolve(res)\n\n const response: ActionFlightResponse = await createFromFetch(\n responsePromise,\n {\n callServer,\n findSourceMapURL,\n temporaryReferences,\n debugChannel: createDebugChannel && createDebugChannel(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 couldBeIntercepted = response.i\n\n // Check if the response build ID matches the client build ID.\n // In a multi-zone setup, when a server action triggers a redirect,\n // the server pre-fetches the redirect target as RSC. If the redirect\n // target is served by a different Next.js zone (different build), the\n // pre-fetched RSC data will have a foreign build ID. We must discard\n // the flight data in that case so the redirect triggers an MPA\n // navigation (full page load) instead of trying to apply the foreign\n // RSC payload — which would result in a blank page.\n const responseBuildId =\n res.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? response.b\n if (\n responseBuildId !== undefined &&\n responseBuildId !== getNavigationBuildId()\n ) {\n // Build ID mismatch — discard the flight data. The redirect will\n // still be processed, and the absence of flight data will cause an\n // MPA navigation via completeHardNavigation().\n } else {\n if (response.t !== undefined) {\n actionFlightData = response.t\n actionFlightDataRenderedSearch = response.q as NormalizedSearch\n } else if (response.n !== undefined) {\n // The server responded with an MPA navigation URL.\n actionFlightData = response.n\n }\n }\n } else {\n // An external redirect doesn't contain RSC data.\n actionResult = undefined\n actionFlightData = undefined\n actionFlightDataRenderedSearch = undefined\n }\n\n return {\n actionResult,\n actionFlightData,\n actionFlightDataRenderedSearch,\n redirectLocation,\n redirectType,\n revalidationKind,\n isPrerender,\n couldBeIntercepted,\n }\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\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 // We always send the last next-url, not the current when\n // performing a dynamic request. This is because we update\n // the next-url after a navigation, but we want the same\n // interception route to be matched that used the last\n // next-url.\n (state.previousNextUrl || state.nextUrl) &&\n hasInterceptionRouteInCurrentTree(state.tree)\n ? state.previousNextUrl || state.nextUrl\n : null\n\n return fetchServerAction(state, nextUrl, action).then(\n async ({\n revalidationKind,\n actionResult,\n actionFlightData: flightData,\n actionFlightDataRenderedSearch: flightDataRenderedSearch,\n redirectLocation,\n redirectType,\n isPrerender,\n couldBeIntercepted,\n }) => {\n if (revalidationKind !== ActionDidNotRevalidate) {\n // There was either a revalidation or a refresh, or maybe both.\n\n // Evict the BFCache, which may contain dynamic data.\n invalidateBfCache()\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 action.didRevalidate = true\n\n // If there was a revalidation, evict the prefetch cache.\n // TODO: Evict only segments with matching tags and/or paths.\n // TODO: We should only invalidate the route cache if cookies were\n // mutated, since route trees may vary based on cookies. For now we\n // invalidate both caches until we have a way to detect cookie\n // mutations on the client.\n if (revalidationKind === ActionDidRevalidateStaticAndDynamic) {\n invalidateEntirePrefetchCache(nextUrl, state.tree)\n }\n\n // Start a cooldown before re-prefetching to allow CDN cache\n // propagation.\n startRevalidationCooldown()\n }\n\n const navigateType = redirectType || 'push'\n\n if (redirectLocation !== undefined) {\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\n if (isExternalURL(redirectLocation)) {\n // External redirect. Triggers an MPA navigation.\n const redirectHref = redirectLocation.href\n const redirectError = createRedirectErrorForAction(\n redirectHref,\n navigateType\n )\n reject(redirectError)\n return completeHardNavigation(state, redirectLocation, navigateType)\n } else {\n // Internal redirect. Triggers an SPA navigation.\n const redirectWithBasepath = createHrefFromUrl(\n redirectLocation,\n false\n )\n const redirectHref = hasBasePath(redirectWithBasepath)\n ? removeBasePath(redirectWithBasepath)\n : redirectWithBasepath\n const redirectError = createRedirectErrorForAction(\n redirectHref,\n navigateType\n )\n reject(redirectError)\n }\n } else {\n // If there's no redirect, resolve the action with the result.\n resolve(actionResult)\n }\n\n // Check if we can bail out without updating any state.\n if (\n // Did the action trigger a redirect?\n redirectLocation === undefined &&\n // Did the action revalidate any data?\n revalidationKind === ActionDidNotRevalidate &&\n // Did the server render new data?\n flightData === undefined\n ) {\n // The action did not trigger any revalidations or redirects. No\n // navigation is required.\n return state\n }\n\n if (flightData === undefined && redirectLocation !== undefined) {\n // The server redirected, but did not send any Flight data. This implies\n // an external redirect.\n // TODO: We should refactor the action response type to be more explicit\n // about the various response types.\n return completeHardNavigation(state, redirectLocation, navigateType)\n }\n\n if (typeof flightData === 'string') {\n // If the flight data is just a string, something earlier in the\n // response handling triggered an external redirect.\n return completeHardNavigation(\n state,\n new URL(flightData, location.origin),\n navigateType\n )\n }\n\n // The action triggered a navigation — either a redirect, a revalidation,\n // or both.\n\n // If there was no redirect, then the target URL is the same as the\n // current URL.\n const currentUrl = new URL(state.canonicalUrl, location.origin)\n const currentRenderedSearch = state.renderedSearch\n const redirectUrl =\n redirectLocation !== undefined ? redirectLocation : currentUrl\n const currentFlightRouterState = state.tree\n const scrollBehavior = ScrollBehavior.Default\n\n // If the action triggered a revalidation of the cache, we should also\n // refresh all the dynamic data.\n const freshnessPolicy =\n revalidationKind === ActionDidNotRevalidate\n ? FreshnessPolicy.Default\n : FreshnessPolicy.RefreshAll\n\n // The server may have sent back new data. If so, we will perform a\n // \"seeded\" navigation that uses the data from the response.\n // TODO: Currently the server always renders from the root in\n // response to a Server Action. In the case of a normal redirect\n // with no revalidation, it should skip over the shared layouts.\n if (flightData !== undefined && flightDataRenderedSearch !== undefined) {\n // The server sent back new route data as part of the response. We\n // will use this to render the new page. If this happens to be only a\n // subset of the data needed to render the new page, we'll initiate a\n // new fetch, like we would for a normal navigation.\n const redirectCanonicalUrl = createHrefFromUrl(redirectUrl)\n const now = Date.now()\n // TODO: Store the dynamic stale time on the top-level state so it's\n // known during restores and refreshes.\n const redirectSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n flightData,\n flightDataRenderedSearch,\n UnknownDynamicStaleTime\n )\n\n // Learn the route pattern so we can predict it for future navigations.\n const metadataVaryPath = redirectSeed.metadataVaryPath\n if (metadataVaryPath !== null) {\n discoverKnownRoute(\n now,\n redirectUrl.pathname,\n redirectUrl.search as NormalizedSearch,\n nextUrl,\n null, // No pending entry\n redirectSeed.routeTree,\n metadataVaryPath,\n couldBeIntercepted,\n redirectCanonicalUrl,\n isPrerender,\n false // hasDynamicRewrite\n )\n }\n const navigationLock = getCurrentNavigationLock()\n\n return navigateToKnownRoute(\n now,\n state,\n redirectUrl,\n redirectCanonicalUrl,\n redirectSeed,\n currentUrl,\n currentRenderedSearch,\n state.cache,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n null,\n // Server action redirects don't use route prediction - we already\n // have the route tree from the server response. If a mismatch occurs\n // during dynamic data fetch, the retry handler will traverse the\n // known route tree to mark the entry as having a dynamic rewrite.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n }\n\n // The server did not send back new data. We'll perform a regular, non-\n // seeded navigation — effectively the same as <Link> or router.push().\n return navigate(\n state,\n redirectUrl,\n currentUrl,\n currentRenderedSearch,\n state.cache,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType\n )\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\nfunction createRedirectErrorForAction(\n redirectHref: string,\n resolvedRedirectType: RedirectType\n) {\n const redirectError = getRedirectError(redirectHref, resolvedRedirectType)\n // We mark the error as handled because we don't want the redirect to be tried later by\n // the RedirectBoundary, in case the user goes back and `Activity` triggers the redirect\n // again, as it's run within an effect.\n // We don't actually need the RedirectBoundary to do a router.push because we already\n // have all the necessary RSC data to render the new page within a single roundtrip.\n ;(redirectError as any).handled = true\n return redirectError\n}\n"],"names":["serverActionReducer","createFromFetch","createFromFetchBrowser","createDebugChannel","process","env","__NEXT_DEV_SERVER","__NEXT_REACT_DEBUG_CHANNEL","require","fetchServerAction","state","nextUrl","action","actionId","actionArgs","temporaryReferences","createTemporaryReferenceSet","info","extractInfoFromServerReferenceId","usedArgs","omitUnusedArgs","body","encodeReply","headers","Accept","RSC_CONTENT_TYPE_HEADER","ACTION_HEADER","NEXT_ROUTER_STATE_TREE_HEADER","prepareFlightRouterStateForRequest","tree","deploymentId","getDeploymentId","NEXT_URL","self","__next_r","NEXT_HTML_REQUEST_ID_HEADER","NEXT_REQUEST_ID_HEADER","crypto","getRandomValues","Uint32Array","toString","res","fetch","canonicalUrl","method","__NEXT_USE_OFFLINE","notifyOnline","err","checkOfflineError","getOffline","waitForConnection","offline","unrecognizedActionHeader","get","NEXT_ACTION_NOT_FOUND_HEADER","UnrecognizedActionError","redirectHeader","location","_redirectType","split","redirectType","undefined","isPrerender","NEXT_IS_PRERENDER_HEADER","revalidationKind","ActionDidNotRevalidate","revalidationHeader","parsedKind","JSON","parse","ActionDidRevalidateStaticAndDynamic","ActionDidRevalidateDynamicOnly","redirectLocation","assignLocation","URL","window","href","contentType","isRscResponse","startsWith","message","status","text","Error","actionResult","actionFlightData","actionFlightDataRenderedSearch","couldBeIntercepted","responsePromise","processFetch","then","response","r","Promise","resolve","callServer","findSourceMapURL","debugChannel","a","i","responseBuildId","NEXT_NAV_DEPLOYMENT_ID_HEADER","b","getNavigationBuildId","t","q","n","reject","previousNextUrl","hasInterceptionRouteInCurrentTree","flightData","flightDataRenderedSearch","invalidateBfCache","didRevalidate","invalidateEntirePrefetchCache","startRevalidationCooldown","navigateType","isExternalURL","redirectHref","redirectError","createRedirectErrorForAction","completeHardNavigation","redirectWithBasepath","createHrefFromUrl","hasBasePath","removeBasePath","origin","currentUrl","currentRenderedSearch","renderedSearch","redirectUrl","currentFlightRouterState","scrollBehavior","ScrollBehavior","Default","freshnessPolicy","FreshnessPolicy","RefreshAll","redirectCanonicalUrl","now","Date","redirectSeed","convertServerPatchToFullTree","UnknownDynamicStaleTime","metadataVaryPath","discoverKnownRoute","pathname","search","routeTree","navigationLock","getCurrentNavigationLock","navigateToKnownRoute","cache","navigate","e","resolvedRedirectType","getRedirectError","handled"],"mappings":";;;;+BAyTgBA;;;eAAAA;;;+BArTW;qCACM;kCAU1B;yCACiC;uBAClB;wBAQf;oCAOwB;gCACA;mCACG;mDAEgB;mCACC;0BAClB;gCAEF;6BACH;qCAIrB;uBACuC;2BACJ;8BACV;mCACK;2BACS;4BAKvC;sCACsC;kCACV;wCAO5B;gCACuB;gCAC4B;qCAC7B;yBAItB;AAEP,MAAMC,kBACJC,uBAAsB;AAExB,IAAIC;AAIJ,IAAIC,QAAQC,GAAG,CAACC,iBAAiB,IAAIF,QAAQC,GAAG,CAACE,0BAA0B,EAAE;IAC3EJ,qBAAqB,AACnBK,QAAQ,8BACRL,kBAAkB;AACtB;AAoBA,eAAeM,kBACbC,K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AE/C,OAAOC,IAAAA,gCAAoB,EACzBZ,KACAjI,OACAwH,aACAQ,sBACAG,cACAd,YACAC,uBACAtH,MAAM8I,KAAK,EACXrB,0BACAI,iBACA5H,SACAyH,gBACAhB,cACAiC,gBACA,MACA,kEAAkE;YAClE,qEAAqE;YACrE,iEAAiE;YACjE,kEAAkE;YAClE,MACA,kEAAkE;YAClExF;QAEJ;QAEA,uEAAuE;QACvE,uEAAuE;QACvE,OAAO4F,IAAAA,oBAAQ,EACb/I,OACAwH,aACAH,YACAC,uBACAtH,MAAM8I,KAAK,EACXrB,0BACAxH,SACA4H,iBACAH,gBACAhB;IAEJ,GACA,CAACsC;QACC,mHAAmH;QACnH/C,OAAO+C;QAEP,OAAOhJ;IACT;AAEJ;AAEA,SAAS8G,6BACPF,YAAoB,EACpBqC,oBAAkC;IAElC,MAAMpC,gBAAgBqC,IAAAA,0BAAgB,EAACtC,cAAcqC;IAMnDpC,cAAsBsC,OAAO,GAAG;IAClC,OAAOtC;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/server-action-reducer.ts"],"sourcesContent":["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 NEXT_REQUEST_ID_HEADER,\n} from '../../app-router-headers'\nimport { UnrecognizedActionError } from '../../unrecognized-action-error'\nimport { fetch } from '../../segment-cache/fetch'\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 type {\n ReadonlyReducerState,\n ReducerState,\n ServerActionAction,\n} from '../router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer-types'\nimport { assignLocation } from '../../../assign-location'\nimport { createHrefFromUrl } from '../create-href-from-url'\nimport type { PartialTransportData } from '../../../../shared/lib/rsc-transport'\nimport { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'\nimport { prepareFlightRouterStateForRequest } from '../../../flight-data-helpers'\nimport { getRedirectError } from '../../redirect'\nimport type { RedirectType } from '../../redirect-error'\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 {\n invalidateEntirePrefetchCache,\n segmentCacheMap,\n} from '../../segment-cache/cache'\nimport { startRevalidationCooldown } from '../../segment-cache/scheduler'\nimport { getDeploymentId } from '../../../../shared/lib/deployment-id'\nimport { getNavigationBuildId } from '../../../navigation-build-id'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../../lib/constants'\nimport {\n completeHardNavigation,\n navigateToKnownRoute,\n navigate,\n} from '../../segment-cache/navigation'\nimport { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response'\nimport { discoverKnownRoute } from '../../segment-cache/optimistic-routes'\nimport type { NormalizedSearch } from '../../segment-cache/cache-key'\nimport {\n ActionDidNotRevalidate,\n ActionDidRevalidateDynamicOnly,\n ActionDidRevalidateStaticAndDynamic,\n type ActionRevalidationKind,\n} from '../../../../shared/lib/action-revalidation-kind'\nimport { isExternalURL } from '../../app-router-utils'\nimport { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations'\nimport { processFetch } from '../fetch-server-response'\nimport {\n invalidateBfCache,\n UnknownDynamicStaleTime,\n} from '../../segment-cache/bfcache'\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.__NEXT_DEV_SERVER && process.env.__NEXT_REACT_DEBUG_CHANNEL) {\n createDebugChannel = (\n require('../../../dev/debug-channel') as typeof import('../../../dev/debug-channel')\n ).createDebugChannel\n}\n\n// TODO: Refactor to be a discriminated union. Or just get rid of it;\n// fetchServerAction only has one caller, no reason this intermediate type has\n// to exist.\ntype FetchServerActionResult = {\n redirectLocation: URL | undefined\n redirectType: RedirectType | undefined\n revalidationKind: ActionRevalidationKind\n actionResult: ActionResult | undefined\n /**\n * The transport data from the action response, or a URL string when the\n * response handling triggered an external (MPA) redirect.\n */\n actionFlightData: PartialTransportData | string | undefined\n actionFlightDataRenderedSearch: NormalizedSearch | undefined\n isPrerender: boolean\n couldBeIntercepted: boolean\n}\n\nasync function fetchServerAction(\n state: ReadonlyReducerState,\n nextUrl: ReadonlyReducerState['nextUrl'],\n action: ServerActionAction\n): Promise<FetchServerActionResult> {\n const { actionId, actionArgs } = action\n const temporaryReferences = createTemporaryReferenceSet()\n const info = extractInfoFromServerReferenceId(actionId)\n const usedArgs = omitUnusedArgs(actionArgs, info)\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 const deploymentId = getDeploymentId()\n if (deploymentId) {\n headers['x-deployment-id'] = deploymentId\n }\n\n if (nextUrl) {\n headers[NEXT_URL] = nextUrl\n }\n\n if (process.env.__NEXT_DEV_SERVER) {\n if (self.__next_r) {\n headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r\n }\n\n // Create a new request ID for the server action request. The server uses\n // this to tag debug information sent via WebSocket to the client, which\n // then routes those chunks to the debug channel associated with this ID.\n headers[NEXT_REQUEST_ID_HEADER] = crypto\n .getRandomValues(new Uint32Array(1))[0]\n .toString(16)\n }\n\n let res: Response\n try {\n res = await fetch(state.canonicalUrl, { method: 'POST', headers, body })\n // If the fetch succeeds while we're in the offline state, notify the\n // offline module so it can short-circuit the polling loop.\n if (process.env.__NEXT_USE_OFFLINE) {\n const { notifyOnline } =\n require('../../offline') as typeof import('../../offline')\n notifyOnline()\n }\n } catch (err) {\n if (process.env.__NEXT_USE_OFFLINE) {\n const { checkOfflineError, getOffline, waitForConnection } =\n require('../../offline') as typeof import('../../offline')\n if (checkOfflineError(err)) {\n // It's safe to replay the action because the fetch rejection\n // means the request never reached the server — there are no\n // side effects to duplicate.\n const offline = getOffline()\n if (offline !== null) {\n await waitForConnection(offline)\n }\n return fetchServerAction(state, nextUrl, action)\n }\n }\n throw err\n }\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 = 'push'\n break\n case 'replace':\n redirectType = 'replace'\n break\n default:\n redirectType = undefined\n }\n\n const isPrerender = !!res.headers.get(NEXT_IS_PRERENDER_HEADER)\n\n let revalidationKind: ActionRevalidationKind = ActionDidNotRevalidate\n try {\n const revalidationHeader = res.headers.get('x-action-revalidated')\n if (revalidationHeader) {\n const parsedKind = JSON.parse(revalidationHeader)\n if (\n parsedKind === ActionDidRevalidateStaticAndDynamic ||\n parsedKind === ActionDidRevalidateDynamicOnly\n ) {\n revalidationKind = parsedKind\n }\n }\n } catch {}\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 let actionFlightDataRenderedSearch: FetchServerActionResult['actionFlightDataRenderedSearch']\n let couldBeIntercepted: boolean = false\n\n if (isRscResponse) {\n // Server action redirect responses carry the Flight data of the redirect\n // target, which may be prerendered with a completeness marker byte\n // prepended. Strip it before passing to Flight.\n const responsePromise = redirectLocation\n ? processFetch(res).then(({ response: r }) => r)\n : Promise.resolve(res)\n\n const response: ActionFlightResponse = await createFromFetch(\n responsePromise,\n {\n callServer,\n findSourceMapURL,\n temporaryReferences,\n debugChannel: createDebugChannel && createDebugChannel(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 couldBeIntercepted = response.i\n\n // Check if the response build ID matches the client build ID.\n // In a multi-zone setup, when a server action triggers a redirect,\n // the server pre-fetches the redirect target as RSC. If the redirect\n // target is served by a different Next.js zone (different build), the\n // pre-fetched RSC data will have a foreign build ID. We must discard\n // the flight data in that case so the redirect triggers an MPA\n // navigation (full page load) instead of trying to apply the foreign\n // RSC payload — which would result in a blank page.\n const responseBuildId =\n res.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? response.b\n if (\n responseBuildId !== undefined &&\n responseBuildId !== getNavigationBuildId()\n ) {\n // Build ID mismatch — discard the flight data. The redirect will\n // still be processed, and the absence of flight data will cause an\n // MPA navigation via completeHardNavigation().\n } else {\n if (response.t !== undefined) {\n actionFlightData = response.t\n actionFlightDataRenderedSearch = response.q as NormalizedSearch\n } else if (response.n !== undefined) {\n // The server responded with an MPA navigation URL.\n actionFlightData = response.n\n }\n }\n } else {\n // An external redirect doesn't contain RSC data.\n actionResult = undefined\n actionFlightData = undefined\n actionFlightDataRenderedSearch = undefined\n }\n\n return {\n actionResult,\n actionFlightData,\n actionFlightDataRenderedSearch,\n redirectLocation,\n redirectType,\n revalidationKind,\n isPrerender,\n couldBeIntercepted,\n }\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\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 // We always send the last next-url, not the current when\n // performing a dynamic request. This is because we update\n // the next-url after a navigation, but we want the same\n // interception route to be matched that used the last\n // next-url.\n (state.previousNextUrl || state.nextUrl) &&\n hasInterceptionRouteInCurrentTree(state.tree)\n ? state.previousNextUrl || state.nextUrl\n : null\n\n return fetchServerAction(state, nextUrl, action).then(\n async ({\n revalidationKind,\n actionResult,\n actionFlightData: flightData,\n actionFlightDataRenderedSearch: flightDataRenderedSearch,\n redirectLocation,\n redirectType,\n isPrerender,\n couldBeIntercepted,\n }) => {\n if (revalidationKind !== ActionDidNotRevalidate) {\n // There was either a revalidation or a refresh, or maybe both.\n\n // Evict the BFCache, which may contain dynamic data.\n invalidateBfCache()\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 action.didRevalidate = true\n\n // If there was a revalidation, evict the prefetch cache.\n // TODO: Evict only segments with matching tags and/or paths.\n // TODO: We should only invalidate the route cache if cookies were\n // mutated, since route trees may vary based on cookies. For now we\n // invalidate both caches until we have a way to detect cookie\n // mutations on the client.\n if (revalidationKind === ActionDidRevalidateStaticAndDynamic) {\n invalidateEntirePrefetchCache(nextUrl, state.tree)\n }\n\n // Start a cooldown before re-prefetching to allow CDN cache\n // propagation.\n startRevalidationCooldown()\n }\n\n const navigateType = redirectType || 'push'\n\n if (redirectLocation !== undefined) {\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\n if (isExternalURL(redirectLocation)) {\n // External redirect. Triggers an MPA navigation.\n const redirectHref = redirectLocation.href\n const redirectError = createRedirectErrorForAction(\n redirectHref,\n navigateType\n )\n reject(redirectError)\n return completeHardNavigation(state, redirectLocation, navigateType)\n } else {\n // Internal redirect. Triggers an SPA navigation.\n const redirectWithBasepath = createHrefFromUrl(\n redirectLocation,\n false\n )\n const redirectHref = hasBasePath(redirectWithBasepath)\n ? removeBasePath(redirectWithBasepath)\n : redirectWithBasepath\n const redirectError = createRedirectErrorForAction(\n redirectHref,\n navigateType\n )\n reject(redirectError)\n }\n } else {\n // If there's no redirect, resolve the action with the result.\n resolve(actionResult)\n }\n\n // Check if we can bail out without updating any state.\n if (\n // Did the action trigger a redirect?\n redirectLocation === undefined &&\n // Did the action revalidate any data?\n revalidationKind === ActionDidNotRevalidate &&\n // Did the server render new data?\n flightData === undefined\n ) {\n // The action did not trigger any revalidations or redirects. No\n // navigation is required.\n return state\n }\n\n if (flightData === undefined && redirectLocation !== undefined) {\n // The server redirected, but did not send any Flight data. This implies\n // an external redirect.\n // TODO: We should refactor the action response type to be more explicit\n // about the various response types.\n return completeHardNavigation(state, redirectLocation, navigateType)\n }\n\n if (typeof flightData === 'string') {\n // If the flight data is just a string, something earlier in the\n // response handling triggered an external redirect.\n return completeHardNavigation(\n state,\n new URL(flightData, location.origin),\n navigateType\n )\n }\n\n // The action triggered a navigation — either a redirect, a revalidation,\n // or both.\n\n // If there was no redirect, then the target URL is the same as the\n // current URL.\n const currentUrl = new URL(state.canonicalUrl, location.origin)\n const currentRenderedSearch = state.renderedSearch\n const redirectUrl =\n redirectLocation !== undefined ? redirectLocation : currentUrl\n const currentFlightRouterState = state.tree\n const scrollBehavior = ScrollBehavior.Default\n\n // If the action triggered a revalidation of the cache, we should also\n // refresh all the dynamic data.\n const freshnessPolicy =\n revalidationKind === ActionDidNotRevalidate\n ? FreshnessPolicy.Default\n : FreshnessPolicy.RefreshAll\n\n // The server may have sent back new data. If so, we will perform a\n // \"seeded\" navigation that uses the data from the response.\n // TODO: Currently the server always renders from the root in\n // response to a Server Action. In the case of a normal redirect\n // with no revalidation, it should skip over the shared layouts.\n if (flightData !== undefined && flightDataRenderedSearch !== undefined) {\n // The server sent back new route data as part of the response. We\n // will use this to render the new page. If this happens to be only a\n // subset of the data needed to render the new page, we'll initiate a\n // new fetch, like we would for a normal navigation.\n const redirectCanonicalUrl = createHrefFromUrl(redirectUrl)\n const now = Date.now()\n // TODO: Store the dynamic stale time on the top-level state so it's\n // known during restores and refreshes.\n const redirectSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n flightData,\n flightDataRenderedSearch,\n UnknownDynamicStaleTime\n )\n\n // Learn the route pattern so we can predict it for future navigations.\n const metadataVaryPath = redirectSeed.metadataVaryPath\n if (metadataVaryPath !== null) {\n discoverKnownRoute(\n now,\n redirectUrl.pathname,\n redirectUrl.search as NormalizedSearch,\n nextUrl,\n null, // No pending entry\n redirectSeed.routeTree,\n metadataVaryPath,\n couldBeIntercepted,\n redirectCanonicalUrl,\n isPrerender,\n false // hasDynamicRewrite\n )\n }\n const navigationLock = getCurrentNavigationLock()\n\n return navigateToKnownRoute(\n now,\n state,\n redirectUrl,\n redirectCanonicalUrl,\n redirectSeed,\n currentUrl,\n currentRenderedSearch,\n state.cache,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n // A server-action redirect navigation is bound to the shared map.\n segmentCacheMap,\n null,\n // Server action redirects don't use route prediction - we already\n // have the route tree from the server response. If a mismatch occurs\n // during dynamic data fetch, the retry handler will traverse the\n // known route tree to mark the entry as having a dynamic rewrite.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n }\n\n // The server did not send back new data. We'll perform a regular, non-\n // seeded navigation — effectively the same as <Link> or router.push().\n return navigate(\n state,\n redirectUrl,\n currentUrl,\n currentRenderedSearch,\n state.cache,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType\n )\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\nfunction createRedirectErrorForAction(\n redirectHref: string,\n resolvedRedirectType: RedirectType\n) {\n const redirectError = getRedirectError(redirectHref, resolvedRedirectType)\n // We mark the error as handled because we don't want the redirect to be tried later by\n // the RedirectBoundary, in case the user goes back and `Activity` triggers the redirect\n // again, as it's run within an effect.\n // We don't actually need the RedirectBoundary to do a router.push because we already\n // have all the necessary RSC data to render the new page within a single roundtrip.\n ;(redirectError as any).handled = true\n return redirectError\n}\n"],"names":["serverActionReducer","createFromFetch","createFromFetchBrowser","createDebugChannel","process","env","__NEXT_DEV_SERVER","__NEXT_REACT_DEBUG_CHANNEL","require","fetchServerAction","state","nextUrl","action","actionId","actionArgs","temporaryReferences","createTemporaryReferenceSet","info","extractInfoFromServerReferenceId","usedArgs","omitUnusedArgs","body","encodeReply","headers","Accept","RSC_CONTENT_TYPE_HEADER","ACTION_HEADER","NEXT_ROUTER_STATE_TREE_HEADER","prepareFlightRouterStateForRequest","tree","deploymentId","getDeploymentId","NEXT_URL","self","__next_r","NEXT_HTML_REQUEST_ID_HEADER","NEXT_REQUEST_ID_HEADER","crypto","getRandomValues","Uint32Array","toString","res","fetch","canonicalUrl","method","__NEXT_USE_OFFLINE","notifyOnline","err","checkOfflineError","getOffline","waitForConnection","offline","unrecognizedActionHeader","get","NEXT_ACTION_NOT_FOUND_HEADER","UnrecognizedActionError","redirectHeader","location","_redirectType","split","redirectType","undefined","isPrerender","NEXT_IS_PRERENDER_HEADER","revalidationKind","ActionDidNotRevalidate","revalidationHeader","parsedKind","JSON","parse","ActionDidRevalidateStaticAndDynamic","ActionDidRevalidateDynamicOnly","redirectLocation","assignLocation","URL","window","href","contentType","isRscResponse","startsWith","message","status","text","Error","actionResult","actionFlightData","actionFlightDataRenderedSearch","couldBeIntercepted","responsePromise","processFetch","then","response","r","Promise","resolve","callServer","findSourceMapURL","debugChannel","a","i","responseBuildId","NEXT_NAV_DEPLOYMENT_ID_HEADER","b","getNavigationBuildId","t","q","n","reject","previousNextUrl","hasInterceptionRouteInCurrentTree","flightData","flightDataRenderedSearch","invalidateBfCache","didRevalidate","invalidateEntirePrefetchCache","startRevalidationCooldown","navigateType","isExternalURL","redirectHref","redirectError","createRedirectErrorForAction","completeHardNavigation","redirectWithBasepath","createHrefFromUrl","hasBasePath","removeBasePath","origin","currentUrl","currentRenderedSearch","renderedSearch","redirectUrl","currentFlightRouterState","scrollBehavior","ScrollBehavior","Default","freshnessPolicy","FreshnessPolicy","RefreshAll","redirectCanonicalUrl","now","Date","redirectSeed","convertServerPatchToFullTree","UnknownDynamicStaleTime","metadataVaryPath","discoverKnownRoute","pathname","search","routeTree","navigationLock","getCurrentNavigationLock","navigateToKnownRoute","cache","segmentCacheMap","navigate","e","resolvedRedirectType","getRedirectError","handled"],"mappings":";;;;+BA4TgBA;;;eAAAA;;;+BAxTW;qCACM;kCAU1B;yCACiC;uBAClB;wBAQf;oCAOwB;gCACA;mCACG;mDAEgB;mCACC;0BAClB;gCAEF;6BACH;qCAIrB;uBAIA;2BACmC;8BACV;mCACK;2BACS;4BAKvC;sCACsC;kCACV;wCAO5B;gCACuB;gCAC4B;qCAC7B;yBAItB;AAEP,MAAMC,kBACJC,uBAAsB;AAExB,IAAIC;AAIJ,IAAIC,QAAQC,GAAG,C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BxI,SACA,MACAkI,aAAaO,SAAS,EACtBJ,kBACAzD,oBACAmD,sBACA5E,aACA,MAAM,oBAAoB;;YAE9B;YACA,MAAMuF,iBAAiBC,IAAAA,wCAAwB;YAE/C,OAAOC,IAAAA,gCAAoB,EACzBZ,KACAjI,OACAwH,aACAQ,sBACAG,cACAd,YACAC,uBACAtH,MAAM8I,KAAK,EACXrB,0BACAI,iBACA5H,SACAyH,gBACAhB,cACAiC,gBACA,kEAAkE;YAClEI,sBAAe,EACf,MACA,kEAAkE;YAClE,qEAAqE;YACrE,iEAAiE;YACjE,kEAAkE;YAClE,MACA,kEAAkE;YAClE5F;QAEJ;QAEA,uEAAuE;QACvE,uEAAuE;QACvE,OAAO6F,IAAAA,oBAAQ,EACbhJ,OACAwH,aACAH,YACAC,uBACAtH,MAAM8I,KAAK,EACXrB,0BACAxH,SACA4H,iBACAH,gBACAhB;IAEJ,GACA,CAACuC;QACC,mHAAmH;QACnHhD,OAAOgD;QAEP,OAAOjJ;IACT;AAEJ;AAEA,SAAS8G,6BACPF,YAAoB,EACpBsC,oBAAkC;IAElC,MAAMrC,gBAAgBsC,IAAAA,0BAAgB,EAACvC,cAAcsC;IAMnDrC,cAAsBuC,OAAO,GAAG;IAClC,OAAOvC;AACT","ignoreList":[0]} |
@@ -14,2 +14,3 @@ "use strict"; | ||
| const _navigation = require("../../segment-cache/navigation"); | ||
| const _cache = require("../../segment-cache/cache"); | ||
| const _refreshreducer = require("./refresh-reducer"); | ||
@@ -53,3 +54,4 @@ const _pprnavigations = require("../ppr-navigations"); | ||
| const now = Date.now(); | ||
| return (0, _navigation.navigateToKnownRoute)(now, state, retryUrl, retryCanonicalUrl, retrySeed, currentUrl, currentRenderedSearch, state.cache, state.tree, action.freshnessPolicy, retryNextUrl, scrollBehavior, navigateType, navigationLock, null, // Server patch (retry) navigations don't use route prediction. This is | ||
| return (0, _navigation.navigateToKnownRoute)(now, state, retryUrl, retryCanonicalUrl, retrySeed, currentUrl, currentRenderedSearch, state.cache, state.tree, action.freshnessPolicy, retryNextUrl, scrollBehavior, navigateType, navigationLock, // A server-patch retry navigation is bound to the shared map. | ||
| _cache.segmentCacheMap, null, // Server patch (retry) navigations don't use route prediction. This is | ||
| // typically a retry after a previous mismatch, so the route was already | ||
@@ -56,0 +58,0 @@ // marked as having a dynamic rewrite when the mismatch was detected. |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/server-patch-reducer.ts"],"sourcesContent":["import { createHrefFromUrl } from '../create-href-from-url'\nimport {\n ACTION_REFRESH,\n type ServerPatchAction,\n type ReducerState,\n type ReadonlyReducerState,\n ScrollBehavior,\n} from '../router-reducer-types'\nimport {\n completeHardNavigation,\n navigateToKnownRoute,\n} from '../../segment-cache/navigation'\nimport { refreshReducer } from './refresh-reducer'\nimport { getCurrentNavigationLock } from '../ppr-navigations'\n\nexport function serverPatchReducer(\n state: ReadonlyReducerState,\n action: ServerPatchAction\n): ReducerState {\n // A \"retry\" is a navigation that happens due to a route mismatch. It's\n // similar to a refresh, because we will omit any existing dynamic data on\n // the page. But we seed the retry navigation with the exact tree that the\n // server just responded with.\n const retryMpa = action.mpa\n const retryUrl = new URL(action.url, location.origin)\n const retrySeed = action.seed\n const navigateType = action.navigateType\n if (retryMpa || retrySeed === null) {\n // If the server did not send back data during the mismatch, fall back to\n // an MPA navigation.\n return completeHardNavigation(state, retryUrl, navigateType)\n }\n const currentUrl = new URL(state.canonicalUrl, location.origin)\n const currentRenderedSearch = state.renderedSearch\n if (action.previousTree !== state.tree) {\n // There was another, more recent navigation since the once that\n // mismatched. We can abort the retry, but we still need to refresh the\n // page to evict any stale dynamic data.\n return refreshReducer(state, { type: ACTION_REFRESH })\n }\n // There have been no new navigations since the mismatched one. Refresh,\n // using the tree we just received from the server.\n //\n // The freshness policy comes from the action: a genuine tree mismatch\n // re-fetches the dynamic data (`RefreshAll`), whereas a redirect that only\n // changed the canonical URL reuses the data already in the tree\n // (`HistoryTraversal`), since the data we received is correct.\n const retryCanonicalUrl = createHrefFromUrl(retryUrl)\n const retryNextUrl = action.nextUrl\n const scrollBehavior = ScrollBehavior.Default\n const navigationLock = getCurrentNavigationLock()\n const now = Date.now()\n return navigateToKnownRoute(\n now,\n state,\n retryUrl,\n retryCanonicalUrl,\n retrySeed,\n currentUrl,\n currentRenderedSearch,\n state.cache,\n state.tree,\n action.freshnessPolicy,\n retryNextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n null,\n // Server patch (retry) navigations don't use route prediction. This is\n // typically a retry after a previous mismatch, so the route was already\n // marked as having a dynamic rewrite when the mismatch was detected.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n"],"names":["serverPatchReducer","state","action","retryMpa","mpa","retryUrl","URL","url","location","origin","retrySeed","seed","navigateType","completeHardNavigation","currentUrl","canonicalUrl","currentRenderedSearch","renderedSearch","previousTree","tree","refreshReducer","type","ACTION_REFRESH","retryCanonicalUrl","createHrefFromUrl","retryNextUrl","nextUrl","scrollBehavior","ScrollBehavior","Default","navigationLock","getCurrentNavigationLock","now","Date","navigateToKnownRoute","cache","freshnessPolicy","undefined"],"mappings":";;;;+BAegBA;;;eAAAA;;;mCAfkB;oCAO3B;4BAIA;gCACwB;gCACU;AAElC,SAASA,mBACdC,KAA2B,EAC3BC,MAAyB;IAEzB,uEAAuE;IACvE,0EAA0E;IAC1E,0EAA0E;IAC1E,8BAA8B;IAC9B,MAAMC,WAAWD,OAAOE,GAAG;IAC3B,MAAMC,WAAW,IAAIC,IAAIJ,OAAOK,GAAG,EAAEC,SAASC,MAAM;IACpD,MAAMC,YAAYR,OAAOS,IAAI;IAC7B,MAAMC,eAAeV,OAAOU,YAAY;IACxC,IAAIT,YAAYO,cAAc,MAAM;QAClC,yEAAyE;QACzE,qBAAqB;QACrB,OAAOG,IAAAA,kCAAsB,EAACZ,OAAOI,UAAUO;IACjD;IACA,MAAME,aAAa,IAAIR,IAAIL,MAAMc,YAAY,EAAEP,SAASC,MAAM;IAC9D,MAAMO,wBAAwBf,MAAMgB,cAAc;IAClD,IAAIf,OAAOgB,YAAY,KAAKjB,MAAMkB,IAAI,EAAE;QACtC,gEAAgE;QAChE,uEAAuE;QACvE,wCAAwC;QACxC,OAAOC,IAAAA,8BAAc,EAACnB,OAAO;YAAEoB,MAAMC,kCAAc;QAAC;IACtD;IACA,wEAAwE;IACxE,mDAAmD;IACnD,EAAE;IACF,sEAAsE;IACtE,2EAA2E;IAC3E,gEAAgE;IAChE,+DAA+D;IAC/D,MAAMC,oBAAoBC,IAAAA,oCAAiB,EAACnB;IAC5C,MAAMoB,eAAevB,OAAOwB,OAAO;IACnC,MAAMC,iBAAiBC,kCAAc,CAACC,OAAO;IAC7C,MAAMC,iBAAiBC,IAAAA,wCAAwB;IAC/C,MAAMC,MAAMC,KAAKD,GAAG;IACpB,OAAOE,IAAAA,gCAAoB,EACzBF,KACA/B,OACAI,UACAkB,mBACAb,WACAI,YACAE,uBACAf,MAAMkC,KAAK,EACXlC,MAAMkB,IAAI,EACVjB,OAAOkC,eAAe,EACtBX,cACAE,gBACAf,cACAkB,gBACA,MACA,uEAAuE;IACvE,wEAAwE;IACxE,qEAAqE;IACrE,MACA,kEAAkE;IAClEO;AAEJ","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/client/components/router-reducer/reducers/server-patch-reducer.ts"],"sourcesContent":["import { createHrefFromUrl } from '../create-href-from-url'\nimport {\n ACTION_REFRESH,\n type ServerPatchAction,\n type ReducerState,\n type ReadonlyReducerState,\n ScrollBehavior,\n} from '../router-reducer-types'\nimport {\n completeHardNavigation,\n navigateToKnownRoute,\n} from '../../segment-cache/navigation'\nimport { segmentCacheMap } from '../../segment-cache/cache'\nimport { refreshReducer } from './refresh-reducer'\nimport { getCurrentNavigationLock } from '../ppr-navigations'\n\nexport function serverPatchReducer(\n state: ReadonlyReducerState,\n action: ServerPatchAction\n): ReducerState {\n // A \"retry\" is a navigation that happens due to a route mismatch. It's\n // similar to a refresh, because we will omit any existing dynamic data on\n // the page. But we seed the retry navigation with the exact tree that the\n // server just responded with.\n const retryMpa = action.mpa\n const retryUrl = new URL(action.url, location.origin)\n const retrySeed = action.seed\n const navigateType = action.navigateType\n if (retryMpa || retrySeed === null) {\n // If the server did not send back data during the mismatch, fall back to\n // an MPA navigation.\n return completeHardNavigation(state, retryUrl, navigateType)\n }\n const currentUrl = new URL(state.canonicalUrl, location.origin)\n const currentRenderedSearch = state.renderedSearch\n if (action.previousTree !== state.tree) {\n // There was another, more recent navigation since the once that\n // mismatched. We can abort the retry, but we still need to refresh the\n // page to evict any stale dynamic data.\n return refreshReducer(state, { type: ACTION_REFRESH })\n }\n // There have been no new navigations since the mismatched one. Refresh,\n // using the tree we just received from the server.\n //\n // The freshness policy comes from the action: a genuine tree mismatch\n // re-fetches the dynamic data (`RefreshAll`), whereas a redirect that only\n // changed the canonical URL reuses the data already in the tree\n // (`HistoryTraversal`), since the data we received is correct.\n const retryCanonicalUrl = createHrefFromUrl(retryUrl)\n const retryNextUrl = action.nextUrl\n const scrollBehavior = ScrollBehavior.Default\n const navigationLock = getCurrentNavigationLock()\n const now = Date.now()\n return navigateToKnownRoute(\n now,\n state,\n retryUrl,\n retryCanonicalUrl,\n retrySeed,\n currentUrl,\n currentRenderedSearch,\n state.cache,\n state.tree,\n action.freshnessPolicy,\n retryNextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n // A server-patch retry navigation is bound to the shared map.\n segmentCacheMap,\n null,\n // Server patch (retry) navigations don't use route prediction. This is\n // typically a retry after a previous mismatch, so the route was already\n // marked as having a dynamic rewrite when the mismatch was detected.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n"],"names":["serverPatchReducer","state","action","retryMpa","mpa","retryUrl","URL","url","location","origin","retrySeed","seed","navigateType","completeHardNavigation","currentUrl","canonicalUrl","currentRenderedSearch","renderedSearch","previousTree","tree","refreshReducer","type","ACTION_REFRESH","retryCanonicalUrl","createHrefFromUrl","retryNextUrl","nextUrl","scrollBehavior","ScrollBehavior","Default","navigationLock","getCurrentNavigationLock","now","Date","navigateToKnownRoute","cache","freshnessPolicy","segmentCacheMap","undefined"],"mappings":";;;;+BAgBgBA;;;eAAAA;;;mCAhBkB;oCAO3B;4BAIA;uBACyB;gCACD;gCACU;AAElC,SAASA,mBACdC,KAA2B,EAC3BC,MAAyB;IAEzB,uEAAuE;IACvE,0EAA0E;IAC1E,0EAA0E;IAC1E,8BAA8B;IAC9B,MAAMC,WAAWD,OAAOE,GAAG;IAC3B,MAAMC,WAAW,IAAIC,IAAIJ,OAAOK,GAAG,EAAEC,SAASC,MAAM;IACpD,MAAMC,YAAYR,OAAOS,IAAI;IAC7B,MAAMC,eAAeV,OAAOU,YAAY;IACxC,IAAIT,YAAYO,cAAc,MAAM;QAClC,yEAAyE;QACzE,qBAAqB;QACrB,OAAOG,IAAAA,kCAAsB,EAACZ,OAAOI,UAAUO;IACjD;IACA,MAAME,aAAa,IAAIR,IAAIL,MAAMc,YAAY,EAAEP,SAASC,MAAM;IAC9D,MAAMO,wBAAwBf,MAAMgB,cAAc;IAClD,IAAIf,OAAOgB,YAAY,KAAKjB,MAAMkB,IAAI,EAAE;QACtC,gEAAgE;QAChE,uEAAuE;QACvE,wCAAwC;QACxC,OAAOC,IAAAA,8BAAc,EAACnB,OAAO;YAAEoB,MAAMC,kCAAc;QAAC;IACtD;IACA,wEAAwE;IACxE,mDAAmD;IACnD,EAAE;IACF,sEAAsE;IACtE,2EAA2E;IAC3E,gEAAgE;IAChE,+DAA+D;IAC/D,MAAMC,oBAAoBC,IAAAA,oCAAiB,EAACnB;IAC5C,MAAMoB,eAAevB,OAAOwB,OAAO;IACnC,MAAMC,iBAAiBC,kCAAc,CAACC,OAAO;IAC7C,MAAMC,iBAAiBC,IAAAA,wCAAwB;IAC/C,MAAMC,MAAMC,KAAKD,GAAG;IACpB,OAAOE,IAAAA,gCAAoB,EACzBF,KACA/B,OACAI,UACAkB,mBACAb,WACAI,YACAE,uBACAf,MAAMkC,KAAK,EACXlC,MAAMkB,IAAI,EACVjB,OAAOkC,eAAe,EACtBX,cACAE,gBACAf,cACAkB,gBACA,8DAA8D;IAC9DO,sBAAe,EACf,MACA,uEAAuE;IACvE,wEAAwE;IACxE,qEAAqE;IACrE,MACA,kEAAkE;IAClEC;AAEJ","ignoreList":[0]} |
@@ -151,3 +151,3 @@ import type { CacheNode, ScrollRef } from '../../../shared/lib/app-router-types'; | ||
| } | ||
| export type FocusAndScrollRef = { | ||
| export type ScrollHandlerRef = { | ||
| /** | ||
@@ -162,3 +162,3 @@ * The scroll ref from the most recent navigation. Set to whatever was | ||
| /** | ||
| * When true, the scroll handler uses `focusAndScrollRef.scrollRef` | ||
| * When true, the scroll handler uses the navigation-level `scrollRef` | ||
| * for every segment regardless of per-node state. Used for hash-only | ||
@@ -199,5 +199,5 @@ * navigations where every segment should be treated as a scroll | ||
| /** | ||
| * Decides if the update should apply scroll and focus management. | ||
| * Decides if the update should apply scroll management. | ||
| */ | ||
| focusAndScrollRef: FocusAndScrollRef; | ||
| scrollRef: ScrollHandlerRef; | ||
| /** | ||
@@ -204,0 +204,0 @@ * The canonical url that is pushed/replaced. |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/client/components/router-reducer/router-reducer-types.ts"],"sourcesContent":["import type { CacheNode, ScrollRef } from '../../../shared/lib/app-router-types'\nimport type { FlightRouterState } from '../../../shared/lib/app-router-types'\nimport type { NavigationSeed } from '../segment-cache/decode-server-response'\nimport type { FetchServerResponseResult } from './fetch-server-response'\nimport type { FreshnessPolicy } from './ppr-navigations'\n\nexport const ACTION_REFRESH = 'refresh'\nexport const ACTION_NAVIGATE = 'navigate'\nexport const ACTION_RESTORE = 'restore'\nexport const ACTION_SERVER_PATCH = 'server-patch'\nexport const ACTION_HMR_REFRESH = 'hmr-refresh'\nexport const ACTION_SERVER_ACTION = 'server-action'\n\nexport type RouterChangeByServerResponse = ({\n navigatedAt,\n previousTree,\n serverResponse,\n}: {\n navigatedAt: number\n previousTree: FlightRouterState\n serverResponse: FetchServerResponseResult\n}) => void\n\n/**\n * Refresh triggers a refresh of the full page data.\n * - fetches the Flight data and fills rsc at the root of the cache.\n * - The router state is updated at the root.\n */\nexport interface RefreshAction {\n type: typeof ACTION_REFRESH\n /**\n * Bypass invalidating the segment cache. Used by the Instant Navigation\n * Testing API to preserve prefetched data when refreshing after an MPA\n * navigation. Not exposed in production builds by default.\n */\n bypassCacheInvalidation?: boolean\n}\n\nexport interface HmrRefreshAction {\n type: typeof ACTION_HMR_REFRESH\n signal?: AbortSignal\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 scrollBehavior: ScrollBehavior\n}\n\n/**\n * Restore applies the provided router state.\n * - Used for `popstate` (back/forward navigation) where a known router state has to be applied.\n * - Also used when syncing the router state with `pushState`/`replaceState` calls.\n * - Router state is applied as-is from the history state, if available.\n * - If the history state does not contain the router state, the existing router state is used.\n * - If any cache node is missing it will be fetched in layout-router during rendering and the server-patch case.\n * - If existing cache nodes match these are used.\n */\nexport interface RestoreAction {\n type: typeof ACTION_RESTORE\n url: URL\n historyState: AppHistoryState | undefined\n}\n\nexport type AppHistoryState = {\n tree: FlightRouterState\n renderedSearch: string\n}\n\n/**\n * Server-patch applies the provided Flight data to the cache and router tree.\n */\nexport interface ServerPatchAction {\n type: typeof ACTION_SERVER_PATCH\n previousTree: FlightRouterState\n url: URL\n nextUrl: string | null\n seed: NavigationSeed | null\n mpa: boolean\n navigateType: 'push' | 'replace'\n /**\n * Freshness policy for the retry navigation. `RefreshAll` re-fetches the\n * tree's dynamic data (genuine tree mismatch). `HistoryTraversal` reuses the\n * data already in the tree (when only the URL needs correcting after a\n * redirect).\n */\n freshnessPolicy: FreshnessPolicy.RefreshAll | FreshnessPolicy.HistoryTraversal\n}\n\n/**\n * PrefetchKind defines the type of prefetching that should be done.\n * - `auto` - if the page is dynamic, prefetch the page data partially, if static prefetch the page data fully.\n * - `full` - prefetch the page data fully.\n */\n\nexport enum PrefetchKind {\n AUTO = 'auto',\n FULL = 'full',\n}\n\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\n/**\n * Controls the scroll behavior for a navigation.\n */\nexport const enum ScrollBehavior {\n /** Use per-node ScrollRef to decide whether to scroll. */\n Default = 0,\n /** Suppress scroll entirely (e.g. scroll={false} on Link or router.push). */\n NoScroll = 1,\n}\n\nexport type FocusAndScrollRef = {\n /**\n * The scroll ref from the most recent navigation. Set to whatever was\n * accumulated during tree construction (or null if nothing was\n * accumulated). On the next navigation, if new scroll targets are\n * created, the previous scrollRef is invalidated by setting\n * `current = false`.\n */\n scrollRef: ScrollRef | null\n /**\n * When true, the scroll handler uses `focusAndScrollRef.scrollRef`\n * for every segment regardless of per-node state. Used for hash-only\n * navigations where every segment should be treated as a scroll\n * target. When false, the handler checks `cacheNode.scrollRef`\n * instead (per-node), so only segments that actually navigated scroll.\n */\n forceScroll: boolean\n /**\n * The hash fragment that should be scrolled to.\n */\n hashFragment: string | null\n /**\n * If only the URLs hash fragment changed\n */\n onlyHashChange: boolean\n}\n\n/**\n * Handles keeping the state of app-router.\n */\nexport type AppRouterState = {\n /**\n * The router state, this is written into the history state in app-router using replaceState/pushState.\n * - Has to be serializable as it is written into the history state.\n * - Holds which segments and parallel routes are shown on the screen.\n */\n tree: FlightRouterState\n /**\n * The cache holds React nodes for every segment that is shown on screen as well as previously shown segments.\n * It also holds in-progress data requests.\n */\n cache: CacheNode\n /**\n * Decides if the update should create a new history entry and if the navigation has to trigger a browser navigation.\n */\n pushRef: PushRef\n /**\n * Decides if the update should apply scroll and focus management.\n */\n focusAndScrollRef: FocusAndScrollRef\n /**\n * The canonical url that is pushed/replaced.\n * - This is the url you see in the browser.\n */\n canonicalUrl: string\n\n /**\n * The search query observed by the server during rendering. This may be\n * different from the canonical URL's search query if the server performed\n * a rewrite. Even though a client component won't observe this (unless it\n * were passed from a Server component), the client router needs to know this\n * so it can properly cache segment data; it'ss part of a page segment's\n * cache key.\n */\n renderedSearch: string\n\n /**\n * The underlying \"url\" representing the UI state, which is used for intercepting routes.\n */\n nextUrl: string | null\n\n /**\n * The previous next-url that was used previous to a dynamic navigation.\n */\n previousNextUrl: string | null\n\n debugInfo: Array<unknown> | null\n}\n\nexport type ReadonlyReducerState = Readonly<AppRouterState>\nexport type ReducerState =\n | (Promise<AppRouterState> & { _debugInfo?: Array<unknown> })\n | AppRouterState\nexport type ReducerActions = Readonly<\n | RefreshAction\n | NavigateAction\n | RestoreAction\n | ServerPatchAction\n | HmrRefreshAction\n | ServerActionAction\n>\n"],"names":["ACTION_HMR_REFRESH","ACTION_NAVIGATE","ACTION_REFRESH","ACTION_RESTORE","ACTION_SERVER_ACTION","ACTION_SERVER_PATCH","PrefetchKind","ScrollBehavior"],"mappings":";;;;;;;;;;;;;;;;;;;;;IAUaA,kBAAkB;eAAlBA;;IAHAC,eAAe;eAAfA;;IADAC,cAAc;eAAdA;;IAEAC,cAAc;eAAdA;;IAGAC,oBAAoB;eAApBA;;IAFAC,mBAAmB;eAAnBA;;IAuIDC,YAAY;eAAZA;;IAuBMC,cAAc;eAAdA;;;AAjKX,MAAML,iBAAiB;AACvB,MAAMD,kBAAkB;AACxB,MAAME,iBAAiB;AACvB,MAAME,sBAAsB;AAC5B,MAAML,qBAAqB;AAC3B,MAAMI,uBAAuB;AAqI7B,IAAA,AAAKE,sCAAAA;;;WAAAA;;AAuBL,IAAA,AAAWC,wCAAAA;IAChB,wDAAwD;IAExD,2EAA2E;WAH3DA","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/client/components/router-reducer/router-reducer-types.ts"],"sourcesContent":["import type { CacheNode, ScrollRef } from '../../../shared/lib/app-router-types'\nimport type { FlightRouterState } from '../../../shared/lib/app-router-types'\nimport type { NavigationSeed } from '../segment-cache/decode-server-response'\nimport type { FetchServerResponseResult } from './fetch-server-response'\nimport type { FreshnessPolicy } from './ppr-navigations'\n\nexport const ACTION_REFRESH = 'refresh'\nexport const ACTION_NAVIGATE = 'navigate'\nexport const ACTION_RESTORE = 'restore'\nexport const ACTION_SERVER_PATCH = 'server-patch'\nexport const ACTION_HMR_REFRESH = 'hmr-refresh'\nexport const ACTION_SERVER_ACTION = 'server-action'\n\nexport type RouterChangeByServerResponse = ({\n navigatedAt,\n previousTree,\n serverResponse,\n}: {\n navigatedAt: number\n previousTree: FlightRouterState\n serverResponse: FetchServerResponseResult\n}) => void\n\n/**\n * Refresh triggers a refresh of the full page data.\n * - fetches the Flight data and fills rsc at the root of the cache.\n * - The router state is updated at the root.\n */\nexport interface RefreshAction {\n type: typeof ACTION_REFRESH\n /**\n * Bypass invalidating the segment cache. Used by the Instant Navigation\n * Testing API to preserve prefetched data when refreshing after an MPA\n * navigation. Not exposed in production builds by default.\n */\n bypassCacheInvalidation?: boolean\n}\n\nexport interface HmrRefreshAction {\n type: typeof ACTION_HMR_REFRESH\n signal?: AbortSignal\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 scrollBehavior: ScrollBehavior\n}\n\n/**\n * Restore applies the provided router state.\n * - Used for `popstate` (back/forward navigation) where a known router state has to be applied.\n * - Also used when syncing the router state with `pushState`/`replaceState` calls.\n * - Router state is applied as-is from the history state, if available.\n * - If the history state does not contain the router state, the existing router state is used.\n * - If any cache node is missing it will be fetched in layout-router during rendering and the server-patch case.\n * - If existing cache nodes match these are used.\n */\nexport interface RestoreAction {\n type: typeof ACTION_RESTORE\n url: URL\n historyState: AppHistoryState | undefined\n}\n\nexport type AppHistoryState = {\n tree: FlightRouterState\n renderedSearch: string\n}\n\n/**\n * Server-patch applies the provided Flight data to the cache and router tree.\n */\nexport interface ServerPatchAction {\n type: typeof ACTION_SERVER_PATCH\n previousTree: FlightRouterState\n url: URL\n nextUrl: string | null\n seed: NavigationSeed | null\n mpa: boolean\n navigateType: 'push' | 'replace'\n /**\n * Freshness policy for the retry navigation. `RefreshAll` re-fetches the\n * tree's dynamic data (genuine tree mismatch). `HistoryTraversal` reuses the\n * data already in the tree (when only the URL needs correcting after a\n * redirect).\n */\n freshnessPolicy: FreshnessPolicy.RefreshAll | FreshnessPolicy.HistoryTraversal\n}\n\n/**\n * PrefetchKind defines the type of prefetching that should be done.\n * - `auto` - if the page is dynamic, prefetch the page data partially, if static prefetch the page data fully.\n * - `full` - prefetch the page data fully.\n */\n\nexport enum PrefetchKind {\n AUTO = 'auto',\n FULL = 'full',\n}\n\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\n/**\n * Controls the scroll behavior for a navigation.\n */\nexport const enum ScrollBehavior {\n /** Use per-node ScrollRef to decide whether to scroll. */\n Default = 0,\n /** Suppress scroll entirely (e.g. scroll={false} on Link or router.push). */\n NoScroll = 1,\n}\n\nexport type ScrollHandlerRef = {\n /**\n * The scroll ref from the most recent navigation. Set to whatever was\n * accumulated during tree construction (or null if nothing was\n * accumulated). On the next navigation, if new scroll targets are\n * created, the previous scrollRef is invalidated by setting\n * `current = false`.\n */\n scrollRef: ScrollRef | null\n /**\n * When true, the scroll handler uses the navigation-level `scrollRef`\n * for every segment regardless of per-node state. Used for hash-only\n * navigations where every segment should be treated as a scroll\n * target. When false, the handler checks `cacheNode.scrollRef`\n * instead (per-node), so only segments that actually navigated scroll.\n */\n forceScroll: boolean\n /**\n * The hash fragment that should be scrolled to.\n */\n hashFragment: string | null\n /**\n * If only the URLs hash fragment changed\n */\n onlyHashChange: boolean\n}\n\n/**\n * Handles keeping the state of app-router.\n */\nexport type AppRouterState = {\n /**\n * The router state, this is written into the history state in app-router using replaceState/pushState.\n * - Has to be serializable as it is written into the history state.\n * - Holds which segments and parallel routes are shown on the screen.\n */\n tree: FlightRouterState\n /**\n * The cache holds React nodes for every segment that is shown on screen as well as previously shown segments.\n * It also holds in-progress data requests.\n */\n cache: CacheNode\n /**\n * Decides if the update should create a new history entry and if the navigation has to trigger a browser navigation.\n */\n pushRef: PushRef\n /**\n * Decides if the update should apply scroll management.\n */\n scrollRef: ScrollHandlerRef\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 /**\n * The search query observed by the server during rendering. This may be\n * different from the canonical URL's search query if the server performed\n * a rewrite. Even though a client component won't observe this (unless it\n * were passed from a Server component), the client router needs to know this\n * so it can properly cache segment data; it'ss part of a page segment's\n * cache key.\n */\n renderedSearch: string\n\n /**\n * The underlying \"url\" representing the UI state, which is used for intercepting routes.\n */\n nextUrl: string | null\n\n /**\n * The previous next-url that was used previous to a dynamic navigation.\n */\n previousNextUrl: string | null\n\n debugInfo: Array<unknown> | null\n}\n\nexport type ReadonlyReducerState = Readonly<AppRouterState>\nexport type ReducerState =\n | (Promise<AppRouterState> & { _debugInfo?: Array<unknown> })\n | AppRouterState\nexport type ReducerActions = Readonly<\n | RefreshAction\n | NavigateAction\n | RestoreAction\n | ServerPatchAction\n | HmrRefreshAction\n | ServerActionAction\n>\n"],"names":["ACTION_HMR_REFRESH","ACTION_NAVIGATE","ACTION_REFRESH","ACTION_RESTORE","ACTION_SERVER_ACTION","ACTION_SERVER_PATCH","PrefetchKind","ScrollBehavior"],"mappings":";;;;;;;;;;;;;;;;;;;;;IAUaA,kBAAkB;eAAlBA;;IAHAC,eAAe;eAAfA;;IADAC,cAAc;eAAdA;;IAEAC,cAAc;eAAdA;;IAGAC,oBAAoB;eAApBA;;IAFAC,mBAAmB;eAAnBA;;IAuIDC,YAAY;eAAZA;;IAuBMC,cAAc;eAAdA;;;AAjKX,MAAML,iBAAiB;AACvB,MAAMD,kBAAkB;AACxB,MAAME,iBAAiB;AACvB,MAAME,sBAAsB;AAC5B,MAAML,qBAAqB;AAC3B,MAAMI,uBAAuB;AAqI7B,IAAA,AAAKE,sCAAAA;;;WAAAA;;AAuBL,IAAA,AAAWC,wCAAAA;IAChB,wDAAwD;IAExD,2EAA2E;WAH3DA","ignoreList":[0]} |
@@ -7,6 +7,5 @@ import type React from 'react'; | ||
| import { type PrefetchTask, type PrefetchSubtaskResult } from './scheduler'; | ||
| import type { NavigationLockPrefetch } from './navigation-testing-lock'; | ||
| import { type SegmentVaryPath, type PartialSegmentVaryPath, type PageVaryPath, type LayoutVaryPath } from './vary-path'; | ||
| import type { NormalizedPathname, NormalizedSearch, RouteCacheKey } from './cache-key'; | ||
| import { EntryStatus, type UnknownMapEntry } from './cache-map'; | ||
| import { EntryStatus, type CacheMap, type UnknownMapEntry } from './cache-map'; | ||
| export { EntryStatus } from './cache-map'; | ||
@@ -174,2 +173,26 @@ import { type SegmentRequestKey } from '../../../shared/lib/segment-cache/segment-value-encoding'; | ||
| export declare const MetadataOnlyRequestTree: FlightRouterState; | ||
| /** | ||
| * The shared segment cache map. Segment cache functions do not access this | ||
| * ambiently — every unit of work is bound to a map when it is created, and | ||
| * reads and writes receive that map explicitly: | ||
| * | ||
| * - A prefetch task captures its map when it is scheduled | ||
| * (`PrefetchTask.segmentCacheMap` in scheduler.ts). Almost always this one; | ||
| * a task scheduled while the Instant Navigation Testing lock is held gets | ||
| * the lock scope's private map instead (which starts empty and is discarded | ||
| * at release), so a locked navigation observes only data fetched under the | ||
| * lock — never a stale entry left in the shared cache by an earlier | ||
| * navigation, prefetch, or scope. | ||
| * - A locked navigation inherits the map of the prefetch task that drives it | ||
| * (see `ensurePrefetchThenNavigate` in navigation.ts). | ||
| * - Everything else — unlocked navigations, hydration, and router work that | ||
| * is not a captured navigation (refreshes, history-traversal restores, | ||
| * server-action redirects, server patches) — uses this shared map | ||
| * directly, even while a lock is held. | ||
| * | ||
| * Binding at creation means a task queued before a lock scope begins never | ||
| * leaks entries into the scope's map (or reads out of it), and a scope task's | ||
| * late responses never leak into the shared map. | ||
| */ | ||
| export declare const segmentCacheMap: CacheMap<SegmentCacheEntry>; | ||
| export declare function getCurrentRouteCacheVersion(): number; | ||
@@ -202,9 +225,8 @@ export declare function getCurrentSegmentCacheVersion(): number; | ||
| export declare function readRouteCacheEntry(now: number, key: RouteCacheKey): RouteCacheEntry | null; | ||
| export declare function readSegmentCacheEntry(now: number, varyPath: SegmentVaryPath): SegmentCacheEntry | null; | ||
| /** | ||
| * Like `readSegmentCacheEntry`, but prefers a Fulfilled entry over a | ||
| * more-specific Pending or Rejected entry. Use this during a navigation, where | ||
| * a less-specific shell entry (e.g. params -> Fallback) should be rendered | ||
| * immediately rather than blocking on a more-specific Pending entry that may | ||
| * still be in-flight. | ||
| * Reads the cache entry for a segment during a navigation. Unlike a plain | ||
| * lookup, prefers a Fulfilled entry over a more-specific Pending or Rejected | ||
| * entry: during a navigation, a less-specific shell entry (e.g. params -> | ||
| * Fallback) should be rendered immediately rather than blocking on a | ||
| * more-specific Pending entry that may still be in-flight. | ||
| * | ||
@@ -218,3 +240,3 @@ * Performs up to two lookups: | ||
| */ | ||
| export declare function readSegmentCacheEntryForNavigation(now: number, varyPath: SegmentVaryPath, restrictToShell?: boolean): SegmentCacheEntry | null; | ||
| export declare function readSegmentCacheEntryForNavigation(now: number, map: CacheMap<SegmentCacheEntry>, varyPath: SegmentVaryPath, restrictToShell?: boolean): SegmentCacheEntry | null; | ||
| export declare function waitForSegmentCacheEntry(pendingEntry: PendingSegmentCacheEntry): Promise<FulfilledSegmentCacheEntry | null>; | ||
@@ -231,8 +253,8 @@ /** | ||
| */ | ||
| export declare function readOrCreateSegmentCacheEntry(now: number, fetchStrategy: FetchStrategy, tree: RouteTree<RSCSegmentData | null>, navigationLockPrefetch: NavigationLockPrefetch | null): SegmentCacheEntry; | ||
| export declare function readOrCreateRevalidatingSegmentEntry(now: number, fetchStrategy: FetchStrategy, tree: RouteTree<RSCSegmentData | null>): SegmentCacheEntry; | ||
| export declare function overwriteRevalidatingSegmentCacheEntry(now: number, fetchStrategy: FetchStrategy, tree: RouteTree<RSCSegmentData | null>): EmptySegmentCacheEntry; | ||
| export declare function upsertSegmentEntry(now: number, varyPath: SegmentVaryPath, candidateEntry: SegmentCacheEntry, lookupVaryPath: SegmentVaryPath | null): SegmentCacheEntry | null; | ||
| export declare function readOrCreateSegmentCacheEntry(now: number, map: CacheMap<SegmentCacheEntry>, fetchStrategy: FetchStrategy, tree: RouteTree<RSCSegmentData | null>): SegmentCacheEntry; | ||
| export declare function readOrCreateRevalidatingSegmentEntry(now: number, map: CacheMap<SegmentCacheEntry>, fetchStrategy: FetchStrategy, tree: RouteTree<RSCSegmentData | null>): SegmentCacheEntry; | ||
| export declare function overwriteRevalidatingSegmentCacheEntry(now: number, map: CacheMap<SegmentCacheEntry>, fetchStrategy: FetchStrategy, tree: RouteTree<RSCSegmentData | null>): EmptySegmentCacheEntry; | ||
| export declare function upsertSegmentEntry(now: number, map: CacheMap<SegmentCacheEntry>, varyPath: SegmentVaryPath, candidateEntry: SegmentCacheEntry, lookupVaryPath: SegmentVaryPath | null): SegmentCacheEntry | null; | ||
| export declare function createDetachedSegmentCacheEntry(now: number): EmptySegmentCacheEntry; | ||
| export declare function upgradeToPendingSegment(emptyEntry: EmptySegmentCacheEntry, fetchStrategy: FetchStrategy, navigationLockPrefetch: NavigationLockPrefetch | null): PendingSegmentCacheEntry; | ||
| export declare function upgradeToPendingSegment(emptyEntry: EmptySegmentCacheEntry, fetchStrategy: FetchStrategy): PendingSegmentCacheEntry; | ||
| export declare function attemptToFulfillDynamicSegmentFromBFCache(now: number, segment: EmptySegmentCacheEntry, tree: RouteTree<RSCSegmentData | null>): FulfilledSegmentCacheEntry | null; | ||
@@ -245,3 +267,3 @@ /** | ||
| */ | ||
| export declare function attemptToUpgradeSegmentFromBFCache(now: number, tree: RouteTree<RSCSegmentData | null>): FulfilledSegmentCacheEntry | null; | ||
| export declare function attemptToUpgradeSegmentFromBFCache(now: number, map: CacheMap<SegmentCacheEntry>, tree: RouteTree<RSCSegmentData | null>): FulfilledSegmentCacheEntry | null; | ||
| export declare function createMetadataRouteTree(metadataVaryPath: PageVaryPath): RouteTree<null>; | ||
@@ -267,6 +289,6 @@ export declare function fulfillRouteCacheEntry(now: number, entry: PendingRouteCacheEntry, tree: RouteTree<RSCSegmentData | null>, metadataVaryPath: PageVaryPath, couldBeIntercepted: boolean, canonicalUrl: string, supportsPerSegmentPrefetching: boolean): FulfilledRouteCacheEntry; | ||
| export declare function convertRouteTreeToFlightRouterState(routeTree: RouteTree<RSCSegmentData | null>): FlightRouterState; | ||
| export declare function fetchRouteOnCacheMiss(entry: PendingRouteCacheEntry, key: RouteCacheKey): Promise<PrefetchSubtaskResult<null> | null>; | ||
| export declare function fetchRouteOnCacheMiss(entry: PendingRouteCacheEntry, key: RouteCacheKey, map: CacheMap<SegmentCacheEntry>): Promise<PrefetchSubtaskResult<null> | null>; | ||
| export declare function fetchSegmentsOnCacheMiss(task: PrefetchTask, route: FulfilledRouteCacheEntry, routeKey: RouteCacheKey, tree: RouteTree<RSCSegmentData | null>, segments: SegmentBundle, segmentCount: number, fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell): Promise<PrefetchSubtaskResult<null> | null>; | ||
| export declare function fetchSegmentPrefetchesUsingDynamicRequest(task: PrefetchTask, route: FulfilledRouteCacheEntry, fetchStrategy: FetchStrategy.LoadingBoundary | FetchStrategy.PPRRuntime | FetchStrategy.RuntimeShell | FetchStrategy.Full, dynamicRequestTree: FlightRouterState, spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>): Promise<PrefetchSubtaskResult<null> | null>; | ||
| export declare function writeDynamicRenderResponseIntoCache(now: number, fetchStrategy: FetchStrategy.LoadingBoundary | FetchStrategy.PPR | FetchStrategy.PPRRuntime | FetchStrategy.RuntimeShell | FetchStrategy.Full, buildId: string | undefined, isResponsePartial: boolean, headVaryParams: VaryParams | null, rootVaryParamsIterable: VaryParamsIterable | null, staleAt: number, navigationSeed: NavigationSeed, spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null): Array<FulfilledSegmentCacheEntry> | null; | ||
| export declare function writeDynamicRenderResponseIntoCache(now: number, fetchStrategy: FetchStrategy.LoadingBoundary | FetchStrategy.PPR | FetchStrategy.PPRRuntime | FetchStrategy.RuntimeShell | FetchStrategy.Full, buildId: string | undefined, isResponsePartial: boolean, headVaryParams: VaryParams | null, rootVaryParamsIterable: VaryParamsIterable | null, staleAt: number, navigationSeed: NavigationSeed, spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null, map: CacheMap<SegmentCacheEntry>): Array<FulfilledSegmentCacheEntry> | null; | ||
| export declare function createNonTaskyPrefetchResponseStream(body: ReadableStream<Uint8Array>, byteLimit?: number): Promise<{ | ||
@@ -328,3 +350,3 @@ stream: ReadableStream<Uint8Array>; | ||
| */ | ||
| export declare function writePrerenderResponseIntoCache(now: number, fetchStrategy: FetchStrategy.PPR | FetchStrategy.RuntimeShell, transportData: PartialTransportData | null, buildId: string | undefined, rootVaryParamsIterable: VaryParamsIterable | null, staleAt: number, baseTree: FlightRouterState, renderedSearch: string, isResponsePartial: boolean): void; | ||
| export declare function writePrerenderResponseIntoCache(now: number, fetchStrategy: FetchStrategy.PPR | FetchStrategy.RuntimeShell, transportData: PartialTransportData | null, buildId: string | undefined, rootVaryParamsIterable: VaryParamsIterable | null, staleAt: number, baseTree: FlightRouterState, renderedSearch: string, isResponsePartial: boolean, map: CacheMap<SegmentCacheEntry>): void; | ||
| /** | ||
@@ -331,0 +353,0 @@ * Decodes an embedded runtime prefetch Flight stream, normalizes the flight |
@@ -21,16 +21,15 @@ /** | ||
| import { type FlightRouterState } from '../../../shared/lib/app-router-types'; | ||
| import { type PendingSegmentCacheEntry, type SegmentCacheEntry } from './cache'; | ||
| import type { SegmentCacheEntry } from './cache'; | ||
| import { type CacheMap } from './cache-map'; | ||
| import type { FetchStrategy } from './types'; | ||
| /** | ||
| * The "wait for the locked navigation's prefetch to fulfill" state for a single | ||
| * locked navigation. `promise` resolves once that prefetch has spawned every | ||
| * request and all of them have fulfilled, so the navigation reads present data | ||
| * rather than a still-in-flight entry. Owned by the prefetch task (one per | ||
| * navigation, so successive navigations in a scope resolve independently) and | ||
| * also tracked in `NavigationLockState.activePrefetches` so the lock can | ||
| * force-resolve any that are still pending when it's released. | ||
| * | ||
| * `pendingCount` holds one reference for the scheduler while it is still | ||
| * spawning, plus one per in-flight entry; `promise` resolves when it drains to | ||
| * 0. `trackedEntries` dedupes entry registration. | ||
| * locked navigation. `promise` resolves when the driving prefetch task | ||
| * completes — which the scheduler only allows after a full pass has observed | ||
| * every segment response it cares about (see `blockTaskOnPendingResponse` in | ||
| * scheduler.ts) — so the navigation reads present data rather than a | ||
| * still-in-flight entry. Owned by the prefetch task (one per navigation, so | ||
| * successive navigations in a scope resolve independently) and also tracked | ||
| * in `NavigationLockState.activePrefetches` so the lock can force-resolve any | ||
| * that are still pending when it's released. | ||
| */ | ||
@@ -40,4 +39,2 @@ export type NavigationLockPrefetch = { | ||
| resolve: () => void; | ||
| pendingCount: number; | ||
| trackedEntries: Set<PendingSegmentCacheEntry>; | ||
| }; | ||
@@ -49,3 +46,3 @@ export type NavigationLockState = { | ||
| activePrefetches: Set<NavigationLockPrefetch>; | ||
| ownedEntries: Set<SegmentCacheEntry>; | ||
| segmentCacheMap: CacheMap<SegmentCacheEntry>; | ||
| currentNavigation: Promise<void>; | ||
@@ -59,34 +56,21 @@ resolveCurrentNavigation: () => void; | ||
| * prefetch task and awaits `.promise`). Returns null if no lock is held. | ||
| * | ||
| * `pendingCount` starts at 1, representing the scheduler itself while it is | ||
| * still spawning requests; that reference is released by | ||
| * `finishNavigationLockPrefetchSpawning`. Each spawned pending entry adds | ||
| * another (see `trackNavigationLockPrefetchEntry`). `promise` resolves when the | ||
| * count drains to 0 — i.e. spawning finished and every entry fulfilled. | ||
| * Resolved by the scheduler via `resolveNavigationLockPrefetch` when the | ||
| * driving prefetch task completes. | ||
| */ | ||
| export declare function beginNavigationLockPrefetch(): NavigationLockPrefetch | null; | ||
| /** | ||
| * Records a freshly-created segment entry as owned by the current lock scope, so | ||
| * navigation reads will match it — and only entries created within the scope | ||
| * (see `NavigationLockState.ownedEntries`). Called from | ||
| * `createDetachedSegmentCacheEntry`, the single factory every creation path | ||
| * funnels through, so re-keyed entries created during response processing (e.g. | ||
| * a runtime prefetch resolving a concrete param) are owned too. No-op when no | ||
| * lock is held. | ||
| * Returns the current lock scope's private segment cache map, or null when no | ||
| * lock is held. See `NavigationLockState.segmentCacheMap`. | ||
| */ | ||
| export declare function recordNavigationLockOwnedEntry(entry: SegmentCacheEntry): void; | ||
| export declare function getNavigationLockSegmentCacheMap(): CacheMap<SegmentCacheEntry> | null; | ||
| /** | ||
| * Called by `upgradeToPendingSegment` whenever the locked-navigation prefetch | ||
| * spawns a pending segment entry. Adds the entry to the prefetch's ref count and | ||
| * decrements when it fulfills (or rejects — `waitForSegmentCacheEntry` resolves | ||
| * to null). Deduped so the same entry never double-counts. | ||
| * Called by the scheduler when the locked-navigation prefetch task completes. | ||
| * A task only completes after a full pass observed every segment response it | ||
| * cares about, so the data the navigation will read has settled by this | ||
| * point. Unregisters from the lock (if still held) and resolves. Resolving is | ||
| * idempotent, so it's safe even if the lock already force-resolved this on | ||
| * release. | ||
| */ | ||
| export declare function trackNavigationLockPrefetchEntry(prefetch: NavigationLockPrefetch, entry: PendingSegmentCacheEntry): void; | ||
| export declare function resolveNavigationLockPrefetch(prefetch: NavigationLockPrefetch): void; | ||
| /** | ||
| * Called once the scheduler has finished spawning every request for the | ||
| * locked-navigation prefetch, releasing the scheduler's reference from the ref | ||
| * count. The prefetch resolves here if every spawned entry already fulfilled. | ||
| */ | ||
| export declare function finishNavigationLockPrefetchSpawning(prefetch: NavigationLockPrefetch): void; | ||
| /** | ||
| * Called when a new locked navigation begins (from `navigate` while the lock is | ||
@@ -141,3 +125,2 @@ * held). Rolls over the lock's withheld-data gate: it resolves the current | ||
| export declare function isNavigationLocked(): boolean; | ||
| export declare function getCurrentNavigationLock(): NavigationLockState | null; | ||
| /** | ||
@@ -144,0 +127,0 @@ * Returns the current locked navigation's withheld-data gate — the same |
@@ -15,15 +15,14 @@ /** | ||
| import type { FlightRouterState } from '../../../shared/lib/app-router-types'; | ||
| import type { PendingSegmentCacheEntry, SegmentCacheEntry } from './cache'; | ||
| import type { SegmentCacheEntry } from './cache'; | ||
| import type { CacheMap } from './cache-map'; | ||
| import type { FetchStrategy } from './types'; | ||
| import type { NavigationLockPrefetch, NavigationLockState } from './navigation-testing-lock'; | ||
| import type { NavigationLockPrefetch } from './navigation-testing-lock'; | ||
| export type { NavigationLockPrefetch, NavigationLockState, } from './navigation-testing-lock'; | ||
| export declare function getPreLockFetch(): typeof fetch | null; | ||
| export declare function beginNavigationLockPrefetch(): NavigationLockPrefetch | null; | ||
| export declare function recordNavigationLockOwnedEntry(_entry: SegmentCacheEntry): void; | ||
| export declare function trackNavigationLockPrefetchEntry(_prefetch: NavigationLockPrefetch, _entry: PendingSegmentCacheEntry): void; | ||
| export declare function finishNavigationLockPrefetchSpawning(_prefetch: NavigationLockPrefetch): void; | ||
| export declare function getNavigationLockSegmentCacheMap(): CacheMap<SegmentCacheEntry> | null; | ||
| export declare function resolveNavigationLockPrefetch(_prefetch: NavigationLockPrefetch): void; | ||
| export declare function startListeningForInstantNavigationCookie(): void; | ||
| export declare function updateCapturedSPAToTree(_fromTree: FlightRouterState, _toTree: FlightRouterState): void; | ||
| export declare function isNavigationLocked(): boolean; | ||
| export declare function getCurrentNavigationLock(): NavigationLockState | null; | ||
| export declare function beginLockedNavigation(): Promise<void> | null; | ||
@@ -30,0 +29,0 @@ export declare function getCurrentNavigationGate(): Promise<void> | null; |
@@ -20,12 +20,10 @@ /** | ||
| beginNavigationLockPrefetch: null, | ||
| finishNavigationLockPrefetchSpawning: null, | ||
| getCurrentNavigationGate: null, | ||
| getCurrentNavigationLock: null, | ||
| getNavigationLockSegmentCacheMap: null, | ||
| getPreLockFetch: null, | ||
| isNavigationLocked: null, | ||
| recordNavigationLockOwnedEntry: null, | ||
| resetNavigationLockToPending: null, | ||
| resolveNavigationLockPrefetch: null, | ||
| shouldRestrictNavigationToShell: null, | ||
| startListeningForInstantNavigationCookie: null, | ||
| trackNavigationLockPrefetchEntry: null, | ||
| updateCapturedSPAToTree: null | ||
@@ -46,10 +44,7 @@ }); | ||
| }, | ||
| finishNavigationLockPrefetchSpawning: function() { | ||
| return finishNavigationLockPrefetchSpawning; | ||
| }, | ||
| getCurrentNavigationGate: function() { | ||
| return getCurrentNavigationGate; | ||
| }, | ||
| getCurrentNavigationLock: function() { | ||
| return getCurrentNavigationLock; | ||
| getNavigationLockSegmentCacheMap: function() { | ||
| return getNavigationLockSegmentCacheMap; | ||
| }, | ||
@@ -62,8 +57,8 @@ getPreLockFetch: function() { | ||
| }, | ||
| recordNavigationLockOwnedEntry: function() { | ||
| return recordNavigationLockOwnedEntry; | ||
| }, | ||
| resetNavigationLockToPending: function() { | ||
| return resetNavigationLockToPending; | ||
| }, | ||
| resolveNavigationLockPrefetch: function() { | ||
| return resolveNavigationLockPrefetch; | ||
| }, | ||
| shouldRestrictNavigationToShell: function() { | ||
@@ -75,5 +70,2 @@ return shouldRestrictNavigationToShell; | ||
| }, | ||
| trackNavigationLockPrefetchEntry: function() { | ||
| return trackNavigationLockPrefetchEntry; | ||
| }, | ||
| updateCapturedSPAToTree: function() { | ||
@@ -89,5 +81,6 @@ return updateCapturedSPAToTree; | ||
| } | ||
| function recordNavigationLockOwnedEntry(_entry) {} | ||
| function trackNavigationLockPrefetchEntry(_prefetch, _entry) {} | ||
| function finishNavigationLockPrefetchSpawning(_prefetch) {} | ||
| function getNavigationLockSegmentCacheMap() { | ||
| return null; | ||
| } | ||
| function resolveNavigationLockPrefetch(_prefetch) {} | ||
| function startListeningForInstantNavigationCookie() {} | ||
@@ -98,5 +91,2 @@ function updateCapturedSPAToTree(_fromTree, _toTree) {} | ||
| } | ||
| function getCurrentNavigationLock() { | ||
| return null; | ||
| } | ||
| function beginLockedNavigation() { | ||
@@ -103,0 +93,0 @@ return null; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/client/components/segment-cache/navigation-testing-lock.disabled.ts"],"sourcesContent":["/**\n * Inert stand-in for `./navigation-testing-lock`.\n *\n * When the Instant Navigation Testing API is disabled (a production build\n * without `experimental.exposeTestingApiInProductionBuild`), the browser\n * bundle resolves `./navigation-testing-lock` to this module instead of the\n * real implementation, so none of the lock machinery ships. The alias is set\n * up in `create-compiler-aliases.ts` (webpack) and\n * `crates/next-core/src/next_import_map.rs` (Turbopack).\n *\n * Every export mirrors the real module's signature and returns the value the\n * real implementation produces when no lock is held.\n */\n\nimport type { FlightRouterState } from '../../../shared/lib/app-router-types'\nimport type { PendingSegmentCacheEntry, SegmentCacheEntry } from './cache'\nimport type { FetchStrategy } from './types'\nimport type {\n NavigationLockPrefetch,\n NavigationLockState,\n} from './navigation-testing-lock'\n\nexport type {\n NavigationLockPrefetch,\n NavigationLockState,\n} from './navigation-testing-lock'\n\nexport function getPreLockFetch(): typeof fetch | null {\n return null\n}\n\nexport function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {\n return null\n}\n\nexport function recordNavigationLockOwnedEntry(\n _entry: SegmentCacheEntry\n): void {}\n\nexport function trackNavigationLockPrefetchEntry(\n _prefetch: NavigationLockPrefetch,\n _entry: PendingSegmentCacheEntry\n): void {}\n\nexport function finishNavigationLockPrefetchSpawning(\n _prefetch: NavigationLockPrefetch\n): void {}\n\nexport function startListeningForInstantNavigationCookie(): void {}\n\nexport function updateCapturedSPAToTree(\n _fromTree: FlightRouterState,\n _toTree: FlightRouterState\n): void {}\n\nexport function isNavigationLocked(): boolean {\n return false\n}\n\nexport function getCurrentNavigationLock(): NavigationLockState | null {\n return null\n}\n\nexport function beginLockedNavigation(): Promise<void> | null {\n return null\n}\n\nexport function getCurrentNavigationGate(): Promise<void> | null {\n return null\n}\n\nexport function resetNavigationLockToPending(): void {}\n\nexport function shouldRestrictNavigationToShell(\n _rootPrefetchHints: number,\n _linkFetchStrategy: FetchStrategy\n): boolean {\n return false\n}\n"],"names":["beginLockedNavigation","beginNavigationLockPrefetch","finishNavigationLockPrefetchSpawning","getCurrentNavigationGate","getCurrentNavigationLock","getPreLockFetch","isNavigationLocked","recordNavigationLockOwnedEntry","resetNavigationLockToPending","shouldRestrictNavigationToShell","startListeningForInstantNavigationCookie","trackNavigationLockPrefetchEntry","updateCapturedSPAToTree","_entry","_prefetch","_fromTree","_toTree","_rootPrefetchHints","_linkFetchStrategy"],"mappings":"AAAA;;;;;;;;;;;;CAYC;;;;;;;;;;;;;;;;;;;;;;;;;;IAmDeA,qBAAqB;eAArBA;;IAhCAC,2BAA2B;eAA3BA;;IAaAC,oCAAoC;eAApCA;;IAuBAC,wBAAwB;eAAxBA;;IARAC,wBAAwB;eAAxBA;;IAhCAC,eAAe;eAAfA;;IA4BAC,kBAAkB;eAAlBA;;IApBAC,8BAA8B;eAA9BA;;IAoCAC,4BAA4B;eAA5BA;;IAEAC,+BAA+B;eAA/BA;;IAzBAC,wCAAwC;eAAxCA;;IATAC,gCAAgC;eAAhCA;;IAWAC,uBAAuB;eAAvBA;;;AAvBT,SAASP;IACd,OAAO;AACT;AAEO,SAASJ;IACd,OAAO;AACT;AAEO,SAASM,+BACdM,MAAyB,GAClB;AAEF,SAASF,iCACdG,SAAiC,EACjCD,MAAgC,GACzB;AAEF,SAASX,qCACdY,SAAiC,GAC1B;AAEF,SAASJ,4CAAkD;AAE3D,SAASE,wBACdG,SAA4B,EAC5BC,OAA0B,GACnB;AAEF,SAASV;IACd,OAAO;AACT;AAEO,SAASF;IACd,OAAO;AACT;AAEO,SAASJ;IACd,OAAO;AACT;AAEO,SAASG;IACd,OAAO;AACT;AAEO,SAASK,gCAAsC;AAE/C,SAASC,gCACdQ,kBAA0B,EAC1BC,kBAAiC;IAEjC,OAAO;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/client/components/segment-cache/navigation-testing-lock.disabled.ts"],"sourcesContent":["/**\n * Inert stand-in for `./navigation-testing-lock`.\n *\n * When the Instant Navigation Testing API is disabled (a production build\n * without `experimental.exposeTestingApiInProductionBuild`), the browser\n * bundle resolves `./navigation-testing-lock` to this module instead of the\n * real implementation, so none of the lock machinery ships. The alias is set\n * up in `create-compiler-aliases.ts` (webpack) and\n * `crates/next-core/src/next_import_map.rs` (Turbopack).\n *\n * Every export mirrors the real module's signature and returns the value the\n * real implementation produces when no lock is held.\n */\n\nimport type { FlightRouterState } from '../../../shared/lib/app-router-types'\nimport type { SegmentCacheEntry } from './cache'\nimport type { CacheMap } from './cache-map'\nimport type { FetchStrategy } from './types'\nimport type { NavigationLockPrefetch } from './navigation-testing-lock'\n\nexport type {\n NavigationLockPrefetch,\n NavigationLockState,\n} from './navigation-testing-lock'\n\nexport function getPreLockFetch(): typeof fetch | null {\n return null\n}\n\nexport function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {\n return null\n}\n\nexport function getNavigationLockSegmentCacheMap(): CacheMap<SegmentCacheEntry> | null {\n return null\n}\n\nexport function resolveNavigationLockPrefetch(\n _prefetch: NavigationLockPrefetch\n): void {}\n\nexport function startListeningForInstantNavigationCookie(): void {}\n\nexport function updateCapturedSPAToTree(\n _fromTree: FlightRouterState,\n _toTree: FlightRouterState\n): void {}\n\nexport function isNavigationLocked(): boolean {\n return false\n}\n\nexport function beginLockedNavigation(): Promise<void> | null {\n return null\n}\n\nexport function getCurrentNavigationGate(): Promise<void> | null {\n return null\n}\n\nexport function resetNavigationLockToPending(): void {}\n\nexport function shouldRestrictNavigationToShell(\n _rootPrefetchHints: number,\n _linkFetchStrategy: FetchStrategy\n): boolean {\n return false\n}\n"],"names":["beginLockedNavigation","beginNavigationLockPrefetch","getCurrentNavigationGate","getNavigationLockSegmentCacheMap","getPreLockFetch","isNavigationLocked","resetNavigationLockToPending","resolveNavigationLockPrefetch","shouldRestrictNavigationToShell","startListeningForInstantNavigationCookie","updateCapturedSPAToTree","_prefetch","_fromTree","_toTree","_rootPrefetchHints","_linkFetchStrategy"],"mappings":"AAAA;;;;;;;;;;;;CAYC;;;;;;;;;;;;;;;;;;;;;;;;IAwCeA,qBAAqB;eAArBA;;IAvBAC,2BAA2B;eAA3BA;;IA2BAC,wBAAwB;eAAxBA;;IAvBAC,gCAAgC;eAAhCA;;IARAC,eAAe;eAAfA;;IAuBAC,kBAAkB;eAAlBA;;IAYAC,4BAA4B;eAA5BA;;IAvBAC,6BAA6B;eAA7BA;;IAyBAC,+BAA+B;eAA/BA;;IArBAC,wCAAwC;eAAxCA;;IAEAC,uBAAuB;eAAvBA;;;AAlBT,SAASN;IACd,OAAO;AACT;AAEO,SAASH;IACd,OAAO;AACT;AAEO,SAASE;IACd,OAAO;AACT;AAEO,SAASI,8BACdI,SAAiC,GAC1B;AAEF,SAASF,4CAAkD;AAE3D,SAASC,wBACdE,SAA4B,EAC5BC,OAA0B,GACnB;AAEF,SAASR;IACd,OAAO;AACT;AAEO,SAASL;IACd,OAAO;AACT;AAEO,SAASE;IACd,OAAO;AACT;AAEO,SAASI,gCAAsC;AAE/C,SAASE,gCACdM,kBAA0B,EAC1BC,kBAAiC;IAEjC,OAAO;AACT","ignoreList":[0]} |
@@ -26,12 +26,10 @@ /** | ||
| beginNavigationLockPrefetch: null, | ||
| finishNavigationLockPrefetchSpawning: null, | ||
| getCurrentNavigationGate: null, | ||
| getCurrentNavigationLock: null, | ||
| getNavigationLockSegmentCacheMap: null, | ||
| getPreLockFetch: null, | ||
| isNavigationLocked: null, | ||
| recordNavigationLockOwnedEntry: null, | ||
| resetNavigationLockToPending: null, | ||
| resolveNavigationLockPrefetch: null, | ||
| shouldRestrictNavigationToShell: null, | ||
| startListeningForInstantNavigationCookie: null, | ||
| trackNavigationLockPrefetchEntry: null, | ||
| updateCapturedSPAToTree: null | ||
@@ -52,10 +50,7 @@ }); | ||
| }, | ||
| finishNavigationLockPrefetchSpawning: function() { | ||
| return finishNavigationLockPrefetchSpawning; | ||
| }, | ||
| getCurrentNavigationGate: function() { | ||
| return getCurrentNavigationGate; | ||
| }, | ||
| getCurrentNavigationLock: function() { | ||
| return getCurrentNavigationLock; | ||
| getNavigationLockSegmentCacheMap: function() { | ||
| return getNavigationLockSegmentCacheMap; | ||
| }, | ||
@@ -68,8 +63,8 @@ getPreLockFetch: function() { | ||
| }, | ||
| recordNavigationLockOwnedEntry: function() { | ||
| return recordNavigationLockOwnedEntry; | ||
| }, | ||
| resetNavigationLockToPending: function() { | ||
| return resetNavigationLockToPending; | ||
| }, | ||
| resolveNavigationLockPrefetch: function() { | ||
| return resolveNavigationLockPrefetch; | ||
| }, | ||
| shouldRestrictNavigationToShell: function() { | ||
@@ -81,5 +76,2 @@ return shouldRestrictNavigationToShell; | ||
| }, | ||
| trackNavigationLockPrefetchEntry: function() { | ||
| return trackNavigationLockPrefetchEntry; | ||
| }, | ||
| updateCapturedSPAToTree: function() { | ||
@@ -93,3 +85,3 @@ return updateCapturedSPAToTree; | ||
| const _scheduler = require("./scheduler"); | ||
| const _cache = require("./cache"); | ||
| const _cachemap = require("./cache-map"); | ||
| function parseCookieValue(raw) { | ||
@@ -162,5 +154,3 @@ if (raw === '') { | ||
| promise, | ||
| resolve: resolve, | ||
| pendingCount: 1, | ||
| trackedEntries: new Set() | ||
| resolve: resolve | ||
| }; | ||
@@ -172,36 +162,11 @@ lockState.activePrefetches.add(prefetch); | ||
| } | ||
| function recordNavigationLockOwnedEntry(entry) { | ||
| function getNavigationLockSegmentCacheMap() { | ||
| return lockState !== null ? lockState.segmentCacheMap : null; | ||
| } | ||
| function resolveNavigationLockPrefetch(prefetch) { | ||
| if (lockState !== null) { | ||
| lockState.ownedEntries.add(entry); | ||
| lockState.activePrefetches.delete(prefetch); | ||
| } | ||
| prefetch.resolve(); | ||
| } | ||
| function trackNavigationLockPrefetchEntry(prefetch, entry) { | ||
| if (prefetch.trackedEntries.has(entry)) { | ||
| return; | ||
| } | ||
| prefetch.trackedEntries.add(entry); | ||
| prefetch.pendingCount++; | ||
| const onSettled = ()=>{ | ||
| prefetch.pendingCount--; | ||
| settleNavigationLockPrefetchIfDrained(prefetch); | ||
| }; | ||
| // Decrement whether the entry fulfills or its request rejects, so a failed | ||
| // segment can't leave the navigation waiting forever. | ||
| (0, _cache.waitForSegmentCacheEntry)(entry).then(onSettled, onSettled); | ||
| } | ||
| function finishNavigationLockPrefetchSpawning(prefetch) { | ||
| prefetch.pendingCount--; | ||
| settleNavigationLockPrefetchIfDrained(prefetch); | ||
| } | ||
| function settleNavigationLockPrefetchIfDrained(prefetch) { | ||
| if (prefetch.pendingCount === 0) { | ||
| // Unregister from the lock (if still held) and resolve. Resolving is | ||
| // idempotent, so it's safe even if the lock already force-resolved this on | ||
| // release. | ||
| if (lockState !== null) { | ||
| lockState.activePrefetches.delete(prefetch); | ||
| } | ||
| prefetch.resolve(); | ||
| } | ||
| } | ||
| function acquireLock() { | ||
@@ -224,3 +189,3 @@ if (lockState !== null) { | ||
| activePrefetches: new Set(), | ||
| ownedEntries: new Set(), | ||
| segmentCacheMap: (0, _cachemap.createCacheMap)(), | ||
| currentNavigation, | ||
@@ -445,5 +410,2 @@ resolveCurrentNavigation: resolveCurrentNavigation | ||
| } | ||
| function getCurrentNavigationLock() { | ||
| return lockState; | ||
| } | ||
| function getCurrentNavigationGate() { | ||
@@ -450,0 +412,0 @@ return lockState !== null ? lockState.currentNavigation : null; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/client/components/segment-cache/navigation-testing-lock.ts"],"sourcesContent":["/**\n * Navigation lock for the Instant Navigation Testing API.\n *\n * Manages the in-memory lock (a promise) that gates dynamic data writes\n * during instant navigation captures, and owns all cookie state\n * transitions (pending → captured-MPA, pending → captured-SPA).\n *\n * External actors (Playwright, devtools) set [0] to start a lock scope\n * and delete the cookie to end one. Next.js writes captured values.\n * The CookieStore handler distinguishes them by value: pending = external,\n * captured = self-write (ignored).\n *\n * This module assumes the Instant Navigation Testing API is enabled. When it\n * is disabled, the bundler resolves this module to\n * `./navigation-testing-lock.disabled` instead (see\n * `create-compiler-aliases.ts` for webpack and\n * `crates/next-core/src/next_import_map.rs` for Turbopack), so none of this\n * code ships in the browser bundle.\n */\n\nimport {\n PrefetchHint,\n type FlightRouterState,\n type InstantCookie,\n} from '../../../shared/lib/app-router-types'\nimport { NEXT_INSTANT_TEST_COOKIE } from '../app-router-headers'\nimport { refreshOnInstantNavigationUnlock } from '../use-action-queue'\nimport { subtreeHasSpeculativePrefetch } from './scheduler'\nimport {\n waitForSegmentCacheEntry,\n type PendingSegmentCacheEntry,\n type SegmentCacheEntry,\n} from './cache'\nimport type { FetchStrategy } from './types'\n\ntype InstantNavCookieState = 'empty' | 'pending' | 'mpa' | 'spa'\n\nfunction parseCookieValue(raw: string): InstantNavCookieState {\n if (raw === '') {\n return 'empty'\n }\n try {\n const parsed = JSON.parse(raw)\n if (Array.isArray(parsed)) {\n if (parsed.length >= 3) {\n const rawState = parsed[2]\n return rawState === null ? 'mpa' : 'spa'\n }\n }\n } catch {}\n return 'pending'\n}\n\nfunction writeDocumentCookie(\n value: InstantCookie,\n options: { domain?: string | null; path?: string | null }\n): void {\n if (typeof document === 'undefined') {\n return\n }\n let cookie = `${NEXT_INSTANT_TEST_COOKIE}=${JSON.stringify(value)}; Path=${\n options.path ?? '/'\n }`\n if (options.domain) {\n cookie += `; Domain=${options.domain}`\n }\n document.cookie = cookie\n}\n\nfunction writeCookieValue(value: InstantCookie): void {\n if (typeof cookieStore === 'undefined') {\n return\n }\n // Read the existing cookie to preserve its attributes (domain, path), then\n // write back with the new value. This updates the same cookie entry that the\n // external actor created, regardless of how it was scoped. The read goes\n // through `cookieStore.get` because `document.cookie` exposes only names and\n // values, not the domain/path we need to preserve. The write goes through\n // document.cookie because WebKit exposes Cookie Store on localhost but does\n // not commit cookies written through cookieStore.set() there.\n //\n // Capture the current lockState and compare it in the callback so we only\n // write if the lock we observed at call time is still held. This guards\n // against two races: (a) the scope ended between get and set (lockState is\n // now null), and (b) the scope ended and a new one was acquired in the same\n // gap (lockState is a different object). In either case we must not write —\n // doing so would leak stale state into the next scope or outlive the current\n // one. It cannot close one window, though: the callback can run after an\n // external delete but before the deleted-event handler nulls lockState, so\n // the guard still passes and we resurrect the cookie. The deleted handler\n // clears any such entry once the lock is released (see the `event.deleted`\n // loop below).\n const lockAtCall = lockState\n cookieStore.get(NEXT_INSTANT_TEST_COOKIE).then((existing: any) => {\n if (existing && lockState === lockAtCall && lockAtCall !== null) {\n writeDocumentCookie(value, existing)\n }\n })\n}\n\n/**\n * The \"wait for the locked navigation's prefetch to fulfill\" state for a single\n * locked navigation. `promise` resolves once that prefetch has spawned every\n * request and all of them have fulfilled, so the navigation reads present data\n * rather than a still-in-flight entry. Owned by the prefetch task (one per\n * navigation, so successive navigations in a scope resolve independently) and\n * also tracked in `NavigationLockState.activePrefetches` so the lock can\n * force-resolve any that are still pending when it's released.\n *\n * `pendingCount` holds one reference for the scheduler while it is still\n * spawning, plus one per in-flight entry; `promise` resolves when it drains to\n * 0. `trackedEntries` dedupes entry registration.\n */\nexport type NavigationLockPrefetch = {\n promise: Promise<void>\n resolve: () => void\n pendingCount: number\n trackedEntries: Set<PendingSegmentCacheEntry>\n}\n\nexport type NavigationLockState = {\n // Resolves when the lock is released (the testing scope ends). Out-of-band\n // user fetches blocked by `globalFetchOverride` wait on this so they dispatch\n // only once the scope ends. (A locked navigation's *withheld dynamic write*\n // waits on `currentNavigation` instead — see below.)\n released: Promise<void>\n resolveReleased: () => void\n // The pre-lock `window.fetch`, captured at `acquireLock` time and\n // restored at `releaseLock`. Internal Next.js code reads this via\n // `getPreLockFetch` to bypass the override we install on `window.fetch`\n // during a lock scope.\n fetch: typeof fetch\n // Every prefetch-completion state for this scope that hasn't resolved yet.\n // A prefetch removes itself when it drains; on release, any still here are\n // force-resolved so no navigation hangs waiting on a prefetch that the scope\n // ended before it could finish.\n activePrefetches: Set<NavigationLockPrefetch>\n // Every segment entry that was (re)fetched within this lock scope. Navigation\n // reads are restricted to these, so each instant() navigation observes only\n // data fetched under the lock — a \"clean read\" — and never matches a stale\n // entry left in the cache by an earlier navigation or prefetch. See\n // `readSegmentCacheEntryForNavigation`.\n ownedEntries: Set<SegmentCacheEntry>\n // The withheld-data gate for the current locked navigation. A locked\n // navigation's dynamic write waits on this rather than on the scope-wide\n // `released`. Each navigation captures the promise when it begins (via\n // `beginLockedNavigation` or `getCurrentNavigationGate`) and awaits that\n // immutable snapshot, never this mutable field. `beginLockedNavigation`\n // rolls the field over on each new locked navigation: it resolves the\n // current promise — so the *previous* navigation's withheld data is written\n // out and the cache nodes it produced stop holding pending deferred promises\n // that a reused shared segment would otherwise suspend on — then installs a\n // fresh one. `releaseLock` resolves it too. Net effect: only the most recent\n // navigation's data stays withheld; a new navigation always releases the\n // previous one.\n currentNavigation: Promise<void>\n resolveCurrentNavigation: () => void\n}\n\nlet lockState: NavigationLockState | null = null\n\nexport function getPreLockFetch(): typeof fetch | null {\n return lockState !== null ? lockState.fetch : null\n}\n\n/**\n * Creates the \"wait for prefetch to fulfill\" state for one locked navigation,\n * registers it on the current lock, and returns it (the caller stores it on the\n * prefetch task and awaits `.promise`). Returns null if no lock is held.\n *\n * `pendingCount` starts at 1, representing the scheduler itself while it is\n * still spawning requests; that reference is released by\n * `finishNavigationLockPrefetchSpawning`. Each spawned pending entry adds\n * another (see `trackNavigationLockPrefetchEntry`). `promise` resolves when the\n * count drains to 0 — i.e. spawning finished and every entry fulfilled.\n */\nexport function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {\n if (lockState !== null) {\n let resolve: () => void\n const promise = new Promise<void>((r) => {\n resolve = r\n })\n const prefetch: NavigationLockPrefetch = {\n promise,\n resolve: resolve!,\n pendingCount: 1,\n trackedEntries: new Set(),\n }\n lockState.activePrefetches.add(prefetch)\n return prefetch\n }\n return null\n}\n\n/**\n * Records a freshly-created segment entry as owned by the current lock scope, so\n * navigation reads will match it — and only entries created within the scope\n * (see `NavigationLockState.ownedEntries`). Called from\n * `createDetachedSegmentCacheEntry`, the single factory every creation path\n * funnels through, so re-keyed entries created during response processing (e.g.\n * a runtime prefetch resolving a concrete param) are owned too. No-op when no\n * lock is held.\n */\nexport function recordNavigationLockOwnedEntry(entry: SegmentCacheEntry): void {\n if (lockState !== null) {\n lockState.ownedEntries.add(entry)\n }\n}\n\n/**\n * Called by `upgradeToPendingSegment` whenever the locked-navigation prefetch\n * spawns a pending segment entry. Adds the entry to the prefetch's ref count and\n * decrements when it fulfills (or rejects — `waitForSegmentCacheEntry` resolves\n * to null). Deduped so the same entry never double-counts.\n */\nexport function trackNavigationLockPrefetchEntry(\n prefetch: NavigationLockPrefetch,\n entry: PendingSegmentCacheEntry\n): void {\n if (prefetch.trackedEntries.has(entry)) {\n return\n }\n prefetch.trackedEntries.add(entry)\n prefetch.pendingCount++\n const onSettled = () => {\n prefetch.pendingCount--\n settleNavigationLockPrefetchIfDrained(prefetch)\n }\n // Decrement whether the entry fulfills or its request rejects, so a failed\n // segment can't leave the navigation waiting forever.\n waitForSegmentCacheEntry(entry).then(onSettled, onSettled)\n}\n\n/**\n * Called once the scheduler has finished spawning every request for the\n * locked-navigation prefetch, releasing the scheduler's reference from the ref\n * count. The prefetch resolves here if every spawned entry already fulfilled.\n */\nexport function finishNavigationLockPrefetchSpawning(\n prefetch: NavigationLockPrefetch\n): void {\n prefetch.pendingCount--\n settleNavigationLockPrefetchIfDrained(prefetch)\n}\n\nfunction settleNavigationLockPrefetchIfDrained(\n prefetch: NavigationLockPrefetch\n): void {\n if (prefetch.pendingCount === 0) {\n // Unregister from the lock (if still held) and resolve. Resolving is\n // idempotent, so it's safe even if the lock already force-resolved this on\n // release.\n if (lockState !== null) {\n lockState.activePrefetches.delete(prefetch)\n }\n prefetch.resolve()\n }\n}\n\nfunction acquireLock(): void {\n if (lockState !== null) {\n return\n }\n let resolveReleased: () => void\n const released = new Promise<void>((r) => {\n resolveReleased = r\n })\n let resolveCurrentNavigation: () => void\n const currentNavigation = new Promise<void>((r) => {\n resolveCurrentNavigation = r\n })\n lockState = {\n released,\n resolveReleased: resolveReleased!,\n fetch: window.fetch,\n activePrefetches: new Set(),\n ownedEntries: new Set(),\n currentNavigation,\n resolveCurrentNavigation: resolveCurrentNavigation!,\n }\n\n // Install the fetch blocker. We only intercept `window.fetch` for the\n // duration of the lock so that — outside of a testing scope — user-\n // installed overrides of `window.fetch` are untouched.\n window.fetch = globalFetchOverride\n}\n\nfunction releaseLock(): void {\n if (lockState === null) {\n return\n }\n // Restore the pre-lock `window.fetch` before resolving the lock promise\n // so any fetches queued on the promise see the restored fetch.\n window.fetch = lockState.fetch\n const { resolveReleased, activePrefetches, resolveCurrentNavigation } =\n lockState\n lockState = null\n // Force-resolve every prefetch that hasn't finished, so a navigation still\n // waiting on one doesn't hang now that the scope is ending.\n for (const prefetch of activePrefetches) {\n prefetch.resolve()\n }\n // Resolve the current locked navigation's withheld-data gate, so its gated\n // dynamic write unblocks now that the scope is ending.\n resolveCurrentNavigation()\n // Resolve the release promise so blocked out-of-band fetches dispatch too.\n resolveReleased()\n}\n\n/**\n * Called when a new locked navigation begins (from `navigate` while the lock is\n * held). Rolls over the lock's withheld-data gate: it resolves the current\n * `currentNavigation` promise — so the *previous* locked navigation's withheld\n * dynamic write proceeds and the cache nodes it produced stop holding pending\n * deferred `rsc` promises that a reused shared segment in this navigation would\n * otherwise suspend on — then installs a fresh promise for this navigation.\n * Only the most recent navigation's data stays withheld; a new navigation\n * always releases the previous one. Returns this navigation's gate — the\n * immutable promise its dynamic write awaits — or null when no lock is held.\n *\n * This is the testing-lock behavior for repeated navigations while paused. It\n * is not a principled fix for the underlying `useDeferredValue`/reuse-suspend\n * behavior; it just ensures that, under the lock, a reused segment never\n * carries a still-pending deferred `rsc` from an earlier navigation.\n */\nexport function beginLockedNavigation(): Promise<void> | null {\n if (lockState === null) {\n return null\n }\n // Release the previous locked navigation's withheld data, then roll over to a\n // fresh gate for this navigation — all without ending the scope.\n lockState.resolveCurrentNavigation()\n let resolveCurrentNavigation: () => void\n const currentNavigation = new Promise<void>((r) => {\n resolveCurrentNavigation = r\n })\n lockState.currentNavigation = currentNavigation\n lockState.resolveCurrentNavigation = resolveCurrentNavigation!\n return currentNavigation\n}\n\n/**\n * Called when the router applies a history traversal (Back/Forward restore) while\n * the testing lock is active. A traversal is not a capture — the mental model is\n * that history entries are already cached — so it must not participate in the\n * current capture. Instead it resets the lock to a fresh pending scope:\n *\n * - `releaseLock` flushes every still-withheld write from prior forward\n * navigations, so the pages you navigated away from finish streaming.\n * - `acquireLock` immediately re-arms a fresh pending scope (no gap where the\n * lock or fetch blocker is down).\n * - the cookie flips from the captured state back to pending.\n *\n * The traversal's own dynamic requests are spawned ungated by the caller (see\n * `restore-reducer`), so they render from cache or fetch normally rather than\n * being withheld.\n */\nexport function resetNavigationLockToPending(): void {\n if (lockState === null || typeof document === 'undefined') {\n return\n }\n releaseLock()\n acquireLock()\n writeCookieValue([0, `c${Math.random()}`])\n}\n\n/**\n * Returns true if the request targets a dev-server endpoint — one of the\n * hot-reloader middleware routes (error overlay, source maps, launch-editor,\n * devtools). They all share the `/__nextjs_` path prefix and are always\n * requested root-relative on the same origin.\n */\nfunction isDevServerRequest(input: RequestInfo | URL): boolean {\n let url: URL\n try {\n url = new URL(\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input\n : input.url,\n window.location.href\n )\n } catch {\n return false\n }\n return (\n url.origin === window.location.origin &&\n url.pathname.startsWith('/__nextjs_')\n )\n}\n\n/**\n * Global fetch override\n *\n * While the navigation lock is active, we install this as `window.fetch` so\n * out-of-band client-side fetches (e.g. `fetch('/api/data')` inside a\n * useEffect) are blocked until the lock is released. Next.js internals\n * bypass the override by importing `fetch` from `./fetch`, which reads the\n * captured pre-lock fetch via `getPreLockFetch`.\n *\n * NOTE: This override only affects environments where the Instant Navigation\n * Testing API is enabled. It has no impact on live production behavior.\n */\nfunction globalFetchOverride(\n input: RequestInfo | URL,\n init?: RequestInit\n): Promise<Response> {\n if (lockState === null) {\n // Lock is not active. Fall through to the global fetch — we reach this\n // only if a caller captured a reference to this function during a lock\n // scope and invoked it after release.\n return fetch(input, init)\n }\n if (process.env.__NEXT_DEV_SERVER && isDevServerRequest(input)) {\n // Dev-server requests must not be gated on the testing lock — blocking\n // them would break the error overlay, source maps, and devtools for the\n // whole scope. Dispatch immediately through the pre-lock fetch. Copy to a\n // local so the call doesn't bind `this` to the lock state object (native\n // fetch throws \"Illegal invocation\" for a foreign receiver).\n const preLockFetch = lockState.fetch\n return preLockFetch(input, init)\n }\n // Block user-initiated fetches until the lock is released, then dispatch\n // through the fetch captured at acquire time. Reading from `lockState`\n // (rather than `window.fetch`) pins to the capture even if `window.fetch`\n // is reassigned after release.\n const currentLock = lockState\n return currentLock.released.then(() => {\n const preLockFetch = currentLock.fetch\n return preLockFetch(input, init)\n })\n}\n\n/**\n * Sets up the cookie-based lock. Handles the initial page load state and\n * registers a CookieStore listener for runtime changes.\n *\n * Called once during page initialization from app-globals.ts.\n */\nexport function startListeningForInstantNavigationCookie(): void {\n // If the server served a shell, this is an MPA page load\n // while the lock is held. Transition to captured-MPA and acquire.\n if (self.__next_instant_test) {\n if (typeof cookieStore !== 'undefined') {\n // If the cookie was already cleared during the MPA page\n // transition, reload to get the full dynamic page.\n cookieStore.get(NEXT_INSTANT_TEST_COOKIE).then((cookie: any) => {\n if (!cookie) {\n window.location.reload()\n }\n })\n }\n\n // Acquire the lock before writing the cookie. writeCookieValue's\n // guard requires lockState to be non-null at call time (so a stale\n // write can't outlive its scope). On a fresh page load that scope\n // is the one we're about to establish, so we have to establish it\n // first.\n acquireLock()\n writeCookieValue([1, `c${Math.random()}`, null])\n }\n\n if (typeof cookieStore === 'undefined') {\n return\n }\n\n cookieStore.addEventListener('change', (event: CookieChangeEvent) => {\n for (const cookie of event.changed) {\n if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {\n const state = parseCookieValue(cookie.value ?? '')\n\n if (state === 'pending') {\n // External actor starting a new lock scope.\n if (lockState !== null) {\n // This can be the delayed CookieStore event for the pending\n // cookie that was already observed synchronously from\n // document.cookie. Keep the existing lock identity so work that\n // captured it keeps waiting on the same promise.\n return\n }\n acquireLock()\n }\n // Captured value (our own transition) or empty. Ignore.\n return\n }\n }\n\n for (const cookie of event.deleted) {\n if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {\n if (lockState === null) {\n // Either no lock is active, or this is the re-entrant change event\n // from the defensive clear below (which runs after releaseLock).\n // Nothing to release either way.\n return\n }\n releaseLock()\n // A captured write from this page's bootstrap can resurrect the\n // cookie in the narrow gap between the external delete and this\n // handler: writeCookieValue's guard only rejects the write once the\n // lock is torn down, which happens here. Now that the lock is\n // released, no further captured write can re-add the cookie, so clear\n // any entry that was resurrected in that gap. Otherwise an unlock\n // that falls back to a hard reload (when the shell has not yet\n // hydrated) would carry the stale cookie, be served the shell again,\n // and re-enter instant mode with no scope left to release it.\n if (typeof document !== 'undefined') {\n document.cookie = `${NEXT_INSTANT_TEST_COOKIE}=; Path=/; Max-Age=0`\n }\n refreshOnInstantNavigationUnlock()\n return\n }\n }\n })\n}\n\n/**\n * Transitions the cookie from pending to captured-SPA once the prefetch resolves\n * and the navigation is known to be an SPA.\n */\nexport function updateCapturedSPAToTree(\n fromTree: FlightRouterState,\n toTree: FlightRouterState\n): void {\n writeCookieValue([1, `c${Math.random()}`, { from: fromTree, to: toTree }])\n}\n\n/**\n * Returns true if the navigation lock is currently active.\n */\nexport function isNavigationLocked(): boolean {\n if (lockState !== null) {\n return true\n }\n\n // If `lockState` is null, fall back to reading the test cookie\n // synchronously from `document.cookie`. This accounts for a small race\n // between `cookieStore.set(...)` and its corresponding `change` event.\n // During that gap `lockState` is still null even though the cookie\n // indicates a new lock scope is starting.\n if (typeof document === 'undefined') {\n return false\n }\n const allCookies = document.cookie\n if (!allCookies.includes(NEXT_INSTANT_TEST_COOKIE)) {\n // Fast bail-out: in almost every navigation the test cookie is not\n // set at all.\n return false\n }\n const target = NEXT_INSTANT_TEST_COOKIE + '='\n for (const segment of allCookies.split(';')) {\n const trimmed = segment.trim()\n if (\n trimmed.startsWith(target) &&\n parseCookieValue(trimmed.slice(target.length)) === 'pending'\n ) {\n // The cookie was set by an external actor but the change event was not\n // yet dispatched. Acquire the lock synchronously.\n acquireLock()\n return true\n }\n }\n return false\n}\n\nexport function getCurrentNavigationLock(): NavigationLockState | null {\n return lockState\n}\n\n/**\n * Returns the current locked navigation's withheld-data gate — the same\n * immutable promise `beginLockedNavigation` handed that navigation — or null\n * when no lock is held. For router work that spawns a dynamic write without\n * beginning a navigation of its own (refreshes, server actions, server\n * patches): it gates behind the navigation that is current when it spawns, so\n * the next locked navigation (or unlock) releases it.\n */\nexport function getCurrentNavigationGate(): Promise<void> | null {\n return lockState !== null ? lockState.currentNavigation : null\n}\n\n/**\n * Decides whether segment reads during a navigation should be restricted to\n * shell entries (every param substituted with Fallback) rather than matching\n * entries that vary on concrete route params.\n *\n * The testing tools (Navigation Inspector, instant()) simulate what a user\n * would see with a warm cache. When the lock is held, partial prefetching is\n * enabled for the target route, and no whole-route (\"speculative\") prefetch\n * would have been made, only the shell is prefetched — so that's all a\n * navigation should be allowed to match. A speculative prefetch happens for a\n * `<Link prefetch={true}>` or an eagerly-prefetched subtree, in which case the\n * concrete-param entry is genuinely warm and may be matched.\n *\n * Always returns false outside the testing API, via the aliased\n * `navigation-testing-lock.disabled` module.\n */\nexport function shouldRestrictNavigationToShell(\n rootPrefetchHints: number,\n linkFetchStrategy: FetchStrategy\n): boolean {\n return (\n isNavigationLocked() &&\n (rootPrefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0 &&\n !subtreeHasSpeculativePrefetch(linkFetchStrategy, rootPrefetchHints)\n )\n}\n"],"names":["beginLockedNavigation","beginNavigationLockPrefetch","finishNavigationLockPrefetchSpawning","getCurrentNavigationGate","getCurrentNavigationLock","getPreLockFetch","isNavigationLocked","recordNavigationLockOwnedEntry","resetNavigationLockToPending","shouldRestrictNavigationToShell","startListeningForInstantNavigationCookie","trackNavigationLockPrefetchEntry","updateCapturedSPAToTree","parseCookieValue","raw","parsed","JSON","parse","Array","isArray","length","rawState","writeDocumentCookie","value","options","document","cookie","NEXT_INSTANT_TEST_COOKIE","stringify","path","domain","writeCookieValue","cookieStore","lockAtCall","lockState","get","then","existing","fetch","resolve","promise","Promise","r","prefetch","pendingCount","trackedEntries","Set","activePrefetches","add","entry","ownedEntries","has","onSettled","settleNavigationLockPrefetchIfDrained","waitForSegmentCacheEntry","delete","acquireLock","resolveReleased","released","resolveCurrentNavigation","currentNavigation","window","globalFetchOverride","releaseLock","Math","random","isDevServerRequest","input","url","URL","location","href","origin","pathname","startsWith","init","process","env","__NEXT_DEV_SERVER","preLockFetch","currentLock","self","__next_instant_test","reload","addEventListener","event","changed","name","state","deleted","refreshOnInstantNavigationUnlock","fromTree","toTree","from","to","allCookies","includes","target","segment","split","trimmed","trim","slice","rootPrefetchHints","linkFetchStrategy","PrefetchHint","SubtreeHasPartialPrefetching","subtreeHasSpeculativePrefetch"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;CAkBC;;;;;;;;;;;;;;;;;;;;;;;;;;IAmTeA,qBAAqB;eAArBA;;IArJAC,2BAA2B;eAA3BA;;IA8DAC,oCAAoC;eAApCA;;IAmVAC,wBAAwB;eAAxBA;;IAZAC,wBAAwB;eAAxBA;;IApZAC,eAAe;eAAfA;;IAiXAC,kBAAkB;eAAlBA;;IAvUAC,8BAA8B;eAA9BA;;IA0JAC,4BAA4B;eAA5BA;;IAgPAC,+BAA+B;eAA/BA;;IA7JAC,wCAAwC;eAAxCA;;IAjOAC,gCAAgC;eAAhCA;;IAiTAC,uBAAuB;eAAvBA;;;gCAhfT;kCACkC;gCACQ;2BACH;uBAKvC;AAKP,SAASC,iBAAiBC,GAAW;IACnC,IAAIA,QAAQ,IAAI;QACd,OAAO;IACT;IACA,IAAI;QACF,MAAMC,SAASC,KAAKC,KAAK,CAACH;QAC1B,IAAII,MAAMC,OAAO,CAACJ,SAAS;YACzB,IAAIA,OAAOK,MAAM,IAAI,GAAG;gBACtB,MAAMC,WAAWN,MAAM,CAAC,EAAE;gBAC1B,OAAOM,aAAa,OAAO,QAAQ;YACrC;QACF;IACF,EAAE,OAAM,CAAC;IACT,OAAO;AACT;AAEA,SAASC,oBACPC,KAAoB,EACpBC,OAAyD;IAEzD,IAAI,OAAOC,aAAa,aAAa;QACnC;IACF;IACA,IAAIC,SAAS,GAAGC,0CAAwB,C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,UAAU0B,iBAAiB,GAAG;AAC5D;AAkBO,SAASnD,gCACd8F,iBAAyB,EACzBC,iBAAgC;IAEhC,OACElG,wBACA,AAACiG,CAAAA,oBAAoBE,4BAAY,CAACC,4BAA4B,AAAD,MAAO,KACpE,CAACC,IAAAA,wCAA6B,EAACH,mBAAmBD;AAEtD","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/client/components/segment-cache/navigation-testing-lock.ts"],"sourcesContent":["/**\n * Navigation lock for the Instant Navigation Testing API.\n *\n * Manages the in-memory lock (a promise) that gates dynamic data writes\n * during instant navigation captures, and owns all cookie state\n * transitions (pending → captured-MPA, pending → captured-SPA).\n *\n * External actors (Playwright, devtools) set [0] to start a lock scope\n * and delete the cookie to end one. Next.js writes captured values.\n * The CookieStore handler distinguishes them by value: pending = external,\n * captured = self-write (ignored).\n *\n * This module assumes the Instant Navigation Testing API is enabled. When it\n * is disabled, the bundler resolves this module to\n * `./navigation-testing-lock.disabled` instead (see\n * `create-compiler-aliases.ts` for webpack and\n * `crates/next-core/src/next_import_map.rs` for Turbopack), so none of this\n * code ships in the browser bundle.\n */\n\nimport {\n PrefetchHint,\n type FlightRouterState,\n type InstantCookie,\n} from '../../../shared/lib/app-router-types'\nimport { NEXT_INSTANT_TEST_COOKIE } from '../app-router-headers'\nimport { refreshOnInstantNavigationUnlock } from '../use-action-queue'\nimport { subtreeHasSpeculativePrefetch } from './scheduler'\nimport type { SegmentCacheEntry } from './cache'\nimport { createCacheMap, type CacheMap } from './cache-map'\nimport type { FetchStrategy } from './types'\n\ntype InstantNavCookieState = 'empty' | 'pending' | 'mpa' | 'spa'\n\nfunction parseCookieValue(raw: string): InstantNavCookieState {\n if (raw === '') {\n return 'empty'\n }\n try {\n const parsed = JSON.parse(raw)\n if (Array.isArray(parsed)) {\n if (parsed.length >= 3) {\n const rawState = parsed[2]\n return rawState === null ? 'mpa' : 'spa'\n }\n }\n } catch {}\n return 'pending'\n}\n\nfunction writeDocumentCookie(\n value: InstantCookie,\n options: { domain?: string | null; path?: string | null }\n): void {\n if (typeof document === 'undefined') {\n return\n }\n let cookie = `${NEXT_INSTANT_TEST_COOKIE}=${JSON.stringify(value)}; Path=${\n options.path ?? '/'\n }`\n if (options.domain) {\n cookie += `; Domain=${options.domain}`\n }\n document.cookie = cookie\n}\n\nfunction writeCookieValue(value: InstantCookie): void {\n if (typeof cookieStore === 'undefined') {\n return\n }\n // Read the existing cookie to preserve its attributes (domain, path), then\n // write back with the new value. This updates the same cookie entry that the\n // external actor created, regardless of how it was scoped. The read goes\n // through `cookieStore.get` because `document.cookie` exposes only names and\n // values, not the domain/path we need to preserve. The write goes through\n // document.cookie because WebKit exposes Cookie Store on localhost but does\n // not commit cookies written through cookieStore.set() there.\n //\n // Capture the current lockState and compare it in the callback so we only\n // write if the lock we observed at call time is still held. This guards\n // against two races: (a) the scope ended between get and set (lockState is\n // now null), and (b) the scope ended and a new one was acquired in the same\n // gap (lockState is a different object). In either case we must not write —\n // doing so would leak stale state into the next scope or outlive the current\n // one. It cannot close one window, though: the callback can run after an\n // external delete but before the deleted-event handler nulls lockState, so\n // the guard still passes and we resurrect the cookie. The deleted handler\n // clears any such entry once the lock is released (see the `event.deleted`\n // loop below).\n const lockAtCall = lockState\n cookieStore.get(NEXT_INSTANT_TEST_COOKIE).then((existing: any) => {\n if (existing && lockState === lockAtCall && lockAtCall !== null) {\n writeDocumentCookie(value, existing)\n }\n })\n}\n\n/**\n * The \"wait for the locked navigation's prefetch to fulfill\" state for a single\n * locked navigation. `promise` resolves when the driving prefetch task\n * completes — which the scheduler only allows after a full pass has observed\n * every segment response it cares about (see `blockTaskOnPendingResponse` in\n * scheduler.ts) — so the navigation reads present data rather than a\n * still-in-flight entry. Owned by the prefetch task (one per navigation, so\n * successive navigations in a scope resolve independently) and also tracked\n * in `NavigationLockState.activePrefetches` so the lock can force-resolve any\n * that are still pending when it's released.\n */\nexport type NavigationLockPrefetch = {\n promise: Promise<void>\n resolve: () => void\n}\n\nexport type NavigationLockState = {\n // Resolves when the lock is released (the testing scope ends). Out-of-band\n // user fetches blocked by `globalFetchOverride` wait on this so they dispatch\n // only once the scope ends. (A locked navigation's *withheld dynamic write*\n // waits on `currentNavigation` instead — see below.)\n released: Promise<void>\n resolveReleased: () => void\n // The pre-lock `window.fetch`, captured at `acquireLock` time and\n // restored at `releaseLock`. Internal Next.js code reads this via\n // `getPreLockFetch` to bypass the override we install on `window.fetch`\n // during a lock scope.\n fetch: typeof fetch\n // Every prefetch-completion state for this scope that hasn't resolved yet.\n // A prefetch removes itself when its driving task completes; on release, any\n // still here are force-resolved so no navigation hangs waiting on a prefetch\n // that the scope ended before it could finish.\n activePrefetches: Set<NavigationLockPrefetch>\n // The scope's private segment cache. Prefetch tasks scheduled while the\n // lock is held are bound to this map instead of the shared one, and a\n // locked navigation inherits the map of the task that drives it (see\n // `segmentCacheMap` in cache.ts). It starts empty, so each instant()\n // navigation observes only data fetched under the lock — a \"clean read\" —\n // and never matches a stale entry left in the shared cache by an earlier\n // navigation, prefetch, or scope. Discarded when the lock is released; its\n // entries are reclaimed by the LRU under memory pressure.\n segmentCacheMap: CacheMap<SegmentCacheEntry>\n // The withheld-data gate for the current locked navigation. A locked\n // navigation's dynamic write waits on this rather than on the scope-wide\n // `released`. Each navigation captures the promise when it begins (via\n // `beginLockedNavigation` or `getCurrentNavigationGate`) and awaits that\n // immutable snapshot, never this mutable field. `beginLockedNavigation`\n // rolls the field over on each new locked navigation: it resolves the\n // current promise — so the *previous* navigation's withheld data is written\n // out and the cache nodes it produced stop holding pending deferred promises\n // that a reused shared segment would otherwise suspend on — then installs a\n // fresh one. `releaseLock` resolves it too. Net effect: only the most recent\n // navigation's data stays withheld; a new navigation always releases the\n // previous one.\n currentNavigation: Promise<void>\n resolveCurrentNavigation: () => void\n}\n\nlet lockState: NavigationLockState | null = null\n\nexport function getPreLockFetch(): typeof fetch | null {\n return lockState !== null ? lockState.fetch : null\n}\n\n/**\n * Creates the \"wait for prefetch to fulfill\" state for one locked navigation,\n * registers it on the current lock, and returns it (the caller stores it on the\n * prefetch task and awaits `.promise`). Returns null if no lock is held.\n * Resolved by the scheduler via `resolveNavigationLockPrefetch` when the\n * driving prefetch task completes.\n */\nexport function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {\n if (lockState !== null) {\n let resolve: () => void\n const promise = new Promise<void>((r) => {\n resolve = r\n })\n const prefetch: NavigationLockPrefetch = {\n promise,\n resolve: resolve!,\n }\n lockState.activePrefetches.add(prefetch)\n return prefetch\n }\n return null\n}\n\n/**\n * Returns the current lock scope's private segment cache map, or null when no\n * lock is held. See `NavigationLockState.segmentCacheMap`.\n */\nexport function getNavigationLockSegmentCacheMap(): CacheMap<SegmentCacheEntry> | null {\n return lockState !== null ? lockState.segmentCacheMap : null\n}\n\n/**\n * Called by the scheduler when the locked-navigation prefetch task completes.\n * A task only completes after a full pass observed every segment response it\n * cares about, so the data the navigation will read has settled by this\n * point. Unregisters from the lock (if still held) and resolves. Resolving is\n * idempotent, so it's safe even if the lock already force-resolved this on\n * release.\n */\nexport function resolveNavigationLockPrefetch(\n prefetch: NavigationLockPrefetch\n): void {\n if (lockState !== null) {\n lockState.activePrefetches.delete(prefetch)\n }\n prefetch.resolve()\n}\n\nfunction acquireLock(): void {\n if (lockState !== null) {\n return\n }\n let resolveReleased: () => void\n const released = new Promise<void>((r) => {\n resolveReleased = r\n })\n let resolveCurrentNavigation: () => void\n const currentNavigation = new Promise<void>((r) => {\n resolveCurrentNavigation = r\n })\n lockState = {\n released,\n resolveReleased: resolveReleased!,\n fetch: window.fetch,\n activePrefetches: new Set(),\n segmentCacheMap: createCacheMap(),\n currentNavigation,\n resolveCurrentNavigation: resolveCurrentNavigation!,\n }\n\n // Install the fetch blocker. We only intercept `window.fetch` for the\n // duration of the lock so that — outside of a testing scope — user-\n // installed overrides of `window.fetch` are untouched.\n window.fetch = globalFetchOverride\n}\n\nfunction releaseLock(): void {\n if (lockState === null) {\n return\n }\n // Restore the pre-lock `window.fetch` before resolving the lock promise\n // so any fetches queued on the promise see the restored fetch.\n window.fetch = lockState.fetch\n const { resolveReleased, activePrefetches, resolveCurrentNavigation } =\n lockState\n lockState = null\n // Force-resolve every prefetch that hasn't finished, so a navigation still\n // waiting on one doesn't hang now that the scope is ending.\n for (const prefetch of activePrefetches) {\n prefetch.resolve()\n }\n // Resolve the current locked navigation's withheld-data gate, so its gated\n // dynamic write unblocks now that the scope is ending.\n resolveCurrentNavigation()\n // Resolve the release promise so blocked out-of-band fetches dispatch too.\n resolveReleased()\n}\n\n/**\n * Called when a new locked navigation begins (from `navigate` while the lock is\n * held). Rolls over the lock's withheld-data gate: it resolves the current\n * `currentNavigation` promise — so the *previous* locked navigation's withheld\n * dynamic write proceeds and the cache nodes it produced stop holding pending\n * deferred `rsc` promises that a reused shared segment in this navigation would\n * otherwise suspend on — then installs a fresh promise for this navigation.\n * Only the most recent navigation's data stays withheld; a new navigation\n * always releases the previous one. Returns this navigation's gate — the\n * immutable promise its dynamic write awaits — or null when no lock is held.\n *\n * This is the testing-lock behavior for repeated navigations while paused. It\n * is not a principled fix for the underlying `useDeferredValue`/reuse-suspend\n * behavior; it just ensures that, under the lock, a reused segment never\n * carries a still-pending deferred `rsc` from an earlier navigation.\n */\nexport function beginLockedNavigation(): Promise<void> | null {\n if (lockState === null) {\n return null\n }\n // Release the previous locked navigation's withheld data, then roll over to a\n // fresh gate for this navigation — all without ending the scope.\n lockState.resolveCurrentNavigation()\n let resolveCurrentNavigation: () => void\n const currentNavigation = new Promise<void>((r) => {\n resolveCurrentNavigation = r\n })\n lockState.currentNavigation = currentNavigation\n lockState.resolveCurrentNavigation = resolveCurrentNavigation!\n return currentNavigation\n}\n\n/**\n * Called when the router applies a history traversal (Back/Forward restore) while\n * the testing lock is active. A traversal is not a capture — the mental model is\n * that history entries are already cached — so it must not participate in the\n * current capture. Instead it resets the lock to a fresh pending scope:\n *\n * - `releaseLock` flushes every still-withheld write from prior forward\n * navigations, so the pages you navigated away from finish streaming.\n * - `acquireLock` immediately re-arms a fresh pending scope (no gap where the\n * lock or fetch blocker is down).\n * - the cookie flips from the captured state back to pending.\n *\n * The traversal's own dynamic requests are spawned ungated by the caller (see\n * `restore-reducer`), so they render from cache or fetch normally rather than\n * being withheld.\n */\nexport function resetNavigationLockToPending(): void {\n if (lockState === null || typeof document === 'undefined') {\n return\n }\n releaseLock()\n acquireLock()\n writeCookieValue([0, `c${Math.random()}`])\n}\n\n/**\n * Returns true if the request targets a dev-server endpoint — one of the\n * hot-reloader middleware routes (error overlay, source maps, launch-editor,\n * devtools). They all share the `/__nextjs_` path prefix and are always\n * requested root-relative on the same origin.\n */\nfunction isDevServerRequest(input: RequestInfo | URL): boolean {\n let url: URL\n try {\n url = new URL(\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input\n : input.url,\n window.location.href\n )\n } catch {\n return false\n }\n return (\n url.origin === window.location.origin &&\n url.pathname.startsWith('/__nextjs_')\n )\n}\n\n/**\n * Global fetch override\n *\n * While the navigation lock is active, we install this as `window.fetch` so\n * out-of-band client-side fetches (e.g. `fetch('/api/data')` inside a\n * useEffect) are blocked until the lock is released. Next.js internals\n * bypass the override by importing `fetch` from `./fetch`, which reads the\n * captured pre-lock fetch via `getPreLockFetch`.\n *\n * NOTE: This override only affects environments where the Instant Navigation\n * Testing API is enabled. It has no impact on live production behavior.\n */\nfunction globalFetchOverride(\n input: RequestInfo | URL,\n init?: RequestInit\n): Promise<Response> {\n if (lockState === null) {\n // Lock is not active. Fall through to the global fetch — we reach this\n // only if a caller captured a reference to this function during a lock\n // scope and invoked it after release.\n return fetch(input, init)\n }\n if (process.env.__NEXT_DEV_SERVER && isDevServerRequest(input)) {\n // Dev-server requests must not be gated on the testing lock — blocking\n // them would break the error overlay, source maps, and devtools for the\n // whole scope. Dispatch immediately through the pre-lock fetch. Copy to a\n // local so the call doesn't bind `this` to the lock state object (native\n // fetch throws \"Illegal invocation\" for a foreign receiver).\n const preLockFetch = lockState.fetch\n return preLockFetch(input, init)\n }\n // Block user-initiated fetches until the lock is released, then dispatch\n // through the fetch captured at acquire time. Reading from `lockState`\n // (rather than `window.fetch`) pins to the capture even if `window.fetch`\n // is reassigned after release.\n const currentLock = lockState\n return currentLock.released.then(() => {\n const preLockFetch = currentLock.fetch\n return preLockFetch(input, init)\n })\n}\n\n/**\n * Sets up the cookie-based lock. Handles the initial page load state and\n * registers a CookieStore listener for runtime changes.\n *\n * Called once during page initialization from app-globals.ts.\n */\nexport function startListeningForInstantNavigationCookie(): void {\n // If the server served a shell, this is an MPA page load\n // while the lock is held. Transition to captured-MPA and acquire.\n if (self.__next_instant_test) {\n if (typeof cookieStore !== 'undefined') {\n // If the cookie was already cleared during the MPA page\n // transition, reload to get the full dynamic page.\n cookieStore.get(NEXT_INSTANT_TEST_COOKIE).then((cookie: any) => {\n if (!cookie) {\n window.location.reload()\n }\n })\n }\n\n // Acquire the lock before writing the cookie. writeCookieValue's\n // guard requires lockState to be non-null at call time (so a stale\n // write can't outlive its scope). On a fresh page load that scope\n // is the one we're about to establish, so we have to establish it\n // first.\n acquireLock()\n writeCookieValue([1, `c${Math.random()}`, null])\n }\n\n if (typeof cookieStore === 'undefined') {\n return\n }\n\n cookieStore.addEventListener('change', (event: CookieChangeEvent) => {\n for (const cookie of event.changed) {\n if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {\n const state = parseCookieValue(cookie.value ?? '')\n\n if (state === 'pending') {\n // External actor starting a new lock scope.\n if (lockState !== null) {\n // This can be the delayed CookieStore event for the pending\n // cookie that was already observed synchronously from\n // document.cookie. Keep the existing lock identity so work that\n // captured it keeps waiting on the same promise.\n return\n }\n acquireLock()\n }\n // Captured value (our own transition) or empty. Ignore.\n return\n }\n }\n\n for (const cookie of event.deleted) {\n if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {\n if (lockState === null) {\n // Either no lock is active, or this is the re-entrant change event\n // from the defensive clear below (which runs after releaseLock).\n // Nothing to release either way.\n return\n }\n releaseLock()\n // A captured write from this page's bootstrap can resurrect the\n // cookie in the narrow gap between the external delete and this\n // handler: writeCookieValue's guard only rejects the write once the\n // lock is torn down, which happens here. Now that the lock is\n // released, no further captured write can re-add the cookie, so clear\n // any entry that was resurrected in that gap. Otherwise an unlock\n // that falls back to a hard reload (when the shell has not yet\n // hydrated) would carry the stale cookie, be served the shell again,\n // and re-enter instant mode with no scope left to release it.\n if (typeof document !== 'undefined') {\n document.cookie = `${NEXT_INSTANT_TEST_COOKIE}=; Path=/; Max-Age=0`\n }\n refreshOnInstantNavigationUnlock()\n return\n }\n }\n })\n}\n\n/**\n * Transitions the cookie from pending to captured-SPA once the prefetch resolves\n * and the navigation is known to be an SPA.\n */\nexport function updateCapturedSPAToTree(\n fromTree: FlightRouterState,\n toTree: FlightRouterState\n): void {\n writeCookieValue([1, `c${Math.random()}`, { from: fromTree, to: toTree }])\n}\n\n/**\n * Returns true if the navigation lock is currently active.\n */\nexport function isNavigationLocked(): boolean {\n if (lockState !== null) {\n return true\n }\n\n // If `lockState` is null, fall back to reading the test cookie\n // synchronously from `document.cookie`. This accounts for a small race\n // between `cookieStore.set(...)` and its corresponding `change` event.\n // During that gap `lockState` is still null even though the cookie\n // indicates a new lock scope is starting.\n if (typeof document === 'undefined') {\n return false\n }\n const allCookies = document.cookie\n if (!allCookies.includes(NEXT_INSTANT_TEST_COOKIE)) {\n // Fast bail-out: in almost every navigation the test cookie is not\n // set at all.\n return false\n }\n const target = NEXT_INSTANT_TEST_COOKIE + '='\n for (const segment of allCookies.split(';')) {\n const trimmed = segment.trim()\n if (\n trimmed.startsWith(target) &&\n parseCookieValue(trimmed.slice(target.length)) === 'pending'\n ) {\n // The cookie was set by an external actor but the change event was not\n // yet dispatched. Acquire the lock synchronously.\n acquireLock()\n return true\n }\n }\n return false\n}\n\n/**\n * Returns the current locked navigation's withheld-data gate — the same\n * immutable promise `beginLockedNavigation` handed that navigation — or null\n * when no lock is held. For router work that spawns a dynamic write without\n * beginning a navigation of its own (refreshes, server actions, server\n * patches): it gates behind the navigation that is current when it spawns, so\n * the next locked navigation (or unlock) releases it.\n */\nexport function getCurrentNavigationGate(): Promise<void> | null {\n return lockState !== null ? lockState.currentNavigation : null\n}\n\n/**\n * Decides whether segment reads during a navigation should be restricted to\n * shell entries (every param substituted with Fallback) rather than matching\n * entries that vary on concrete route params.\n *\n * The testing tools (Navigation Inspector, instant()) simulate what a user\n * would see with a warm cache. When the lock is held, partial prefetching is\n * enabled for the target route, and no whole-route (\"speculative\") prefetch\n * would have been made, only the shell is prefetched — so that's all a\n * navigation should be allowed to match. A speculative prefetch happens for a\n * `<Link prefetch={true}>` or an eagerly-prefetched subtree, in which case the\n * concrete-param entry is genuinely warm and may be matched.\n *\n * Always returns false outside the testing API, via the aliased\n * `navigation-testing-lock.disabled` module.\n */\nexport function shouldRestrictNavigationToShell(\n rootPrefetchHints: number,\n linkFetchStrategy: FetchStrategy\n): boolean {\n return (\n isNavigationLocked() &&\n (rootPrefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0 &&\n !subtreeHasSpeculativePrefetch(linkFetchStrategy, rootPrefetchHints)\n )\n}\n"],"names":["beginLockedNavigation","beginNavigationLockPrefetch","getCurrentNavigationGate","getNavigationLockSegmentCacheMap","getPreLockFetch","isNavigationLocked","resetNavigationLockToPending","resolveNavigationLockPrefetch","shouldRestrictNavigationToShell","startListeningForInstantNavigationCookie","updateCapturedSPAToTree","parseCookieValue","raw","parsed","JSON","parse","Array","isArray","length","rawState","writeDocumentCookie","value","options","document","cookie","NEXT_INSTANT_TEST_COOKIE","stringify","path","domain","writeCookieValue","cookieStore","lockAtCall","lockState","get","then","existing","fetch","resolve","promise","Promise","r","prefetch","activePrefetches","add","segmentCacheMap","delete","acquireLock","resolveReleased","released","resolveCurrentNavigation","currentNavigation","window","Set","createCacheMap","globalFetchOverride","releaseLock","Math","random","isDevServerRequest","input","url","URL","location","href","origin","pathname","startsWith","init","process","env","__NEXT_DEV_SERVER","preLockFetch","currentLock","self","__next_instant_test","reload","addEventListener","event","changed","name","state","deleted","refreshOnInstantNavigationUnlock","fromTree","toTree","from","to","allCookies","includes","target","segment","split","trimmed","trim","slice","rootPrefetchHints","linkFetchStrategy","PrefetchHint","SubtreeHasPartialPrefetching","subtreeHasSpeculativePrefetch"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;CAkBC;;;;;;;;;;;;;;;;;;;;;;;;IAiQeA,qBAAqB;eAArBA;;IA3GAC,2BAA2B;eAA3BA;;IAmWAC,wBAAwB;eAAxBA;;IA/UAC,gCAAgC;eAAhCA;;IA/BAC,eAAe;eAAfA;;IAmUAC,kBAAkB;eAAlBA;;IA7KAC,4BAA4B;eAA5BA;;IA3GAC,6BAA6B;eAA7BA;;IAuVAC,+BAA+B;eAA/BA;;IAzJAC,wCAAwC;eAAxCA;;IAgFAC,uBAAuB;eAAvBA;;;gCA9bT;kCACkC;gCACQ;2BACH;0BAEA;AAK9C,SAASC,iBAAiBC,GAAW;IACnC,IAAIA,QAAQ,IAAI;QACd,OAAO;IACT;IACA,IAAI;QACF,MAAMC,SAASC,KAAKC,KAAK,CAACH;QAC1B,IAAII,MAAMC,OAAO,CAACJ,SAAS;YACzB,IAAIA,OAAOK,MAAM,IAAI,GAAG;gBACtB,MAAMC,WAAWN,MAAM,CAAC,EAAE;gBAC1B,OAAOM,aAAa,OAAO,QAAQ;YACrC;QACF;IACF,EAAE,OAAM,CAAC;IACT,OAAO;AACT;AAEA,SAASC,oBACPC,KAAoB,EACpBC,OAAyD;IAEzD,IAAI,OAAOC,aAAa,aAAa;QACnC;IACF;IACA,IAAIC,SAAS,GAAGC,0CAAwB,CAAC,CAAC,EAAEX,KAAKY,SAAS,CAACL,OAAO,OAAO,EACvEC,QAAQK,IAAI,IAAI,KAChB;IACF,IAAIL,QAAQM,MAAM,EAAE;QAClBJ,UAAU,CAAC,SAAS,EAAEF,QAAQM,MAAM,EAAE;IACxC;IACAL,SAASC,MAAM,GAAGA;AACpB;AAEA,SAASK,iBAAiBR,KAAoB;IAC5C,IAAI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C/D,0CAAwB,GAAG;QAClD,mEAAmE;QACnE,cAAc;QACd,OAAO;IACT;IACA,MAAMgE,SAAShE,0CAAwB,GAAG;IAC1C,KAAK,MAAMiE,WAAWH,WAAWI,KAAK,CAAC,KAAM;QAC3C,MAAMC,UAAUF,QAAQG,IAAI;QAC5B,IACED,QAAQ1B,UAAU,CAACuB,WACnB9E,iBAAiBiF,QAAQE,KAAK,CAACL,OAAOvE,MAAM,OAAO,WACnD;YACA,uEAAuE;YACvE,kDAAkD;YAClD4B;YACA,OAAO;QACT;IACF;IACA,OAAO;AACT;AAUO,SAAS5C;IACd,OAAO8B,cAAc,OAAOA,UAAUkB,iBAAiB,GAAG;AAC5D;AAkBO,SAAS1C,gCACduF,iBAAyB,EACzBC,iBAAgC;IAEhC,OACE3F,wBACA,AAAC0F,CAAAA,oBAAoBE,4BAAY,CAACC,4BAA4B,AAAD,MAAO,KACpE,CAACC,IAAAA,wCAA6B,EAACH,mBAAmBD;AAEtD","ignoreList":[0]} |
| import type { FlightRouterState, ScrollRef } from '../../../shared/lib/app-router-types'; | ||
| import type { CacheNode } from '../../../shared/lib/app-router-types'; | ||
| import { FreshnessPolicy, type NavigationLock } from '../router-reducer/ppr-navigations'; | ||
| import { type FulfilledRouteCacheEntry } from './cache'; | ||
| import { type SegmentCacheEntry, type FulfilledRouteCacheEntry } from './cache'; | ||
| import type { CacheMap } from './cache-map'; | ||
| import type { AppRouterState } from '../router-reducer/router-reducer-types'; | ||
@@ -17,3 +18,3 @@ import { ScrollBehavior } from '../router-reducer/router-reducer-types'; | ||
| export declare function navigate(state: AppRouterState, url: URL, currentUrl: URL, currentRenderedSearch: string, currentCacheNode: CacheNode | null, currentFlightRouterState: FlightRouterState, nextUrl: string | null, freshnessPolicy: FreshnessPolicy, scrollBehavior: ScrollBehavior, navigateType: 'push' | 'replace'): AppRouterState | Promise<AppRouterState>; | ||
| export declare function navigateToKnownRoute(now: number, state: AppRouterState, url: URL, canonicalUrl: string, navigationSeed: NavigationSeed, currentUrl: URL, currentRenderedSearch: string, currentCacheNode: CacheNode | null, currentFlightRouterState: FlightRouterState, freshnessPolicy: FreshnessPolicy, nextUrl: string | null, scrollBehavior: ScrollBehavior, navigateType: 'push' | 'replace', navigationLock: NavigationLock | null, debugInfo: Array<unknown> | null, routeCacheEntry: FulfilledRouteCacheEntry | null, signal: AbortSignal | undefined): AppRouterState; | ||
| export declare function navigateToKnownRoute(now: number, state: AppRouterState, url: URL, canonicalUrl: string, navigationSeed: NavigationSeed, currentUrl: URL, currentRenderedSearch: string, currentCacheNode: CacheNode | null, currentFlightRouterState: FlightRouterState, freshnessPolicy: FreshnessPolicy, nextUrl: string | null, scrollBehavior: ScrollBehavior, navigateType: 'push' | 'replace', navigationLock: NavigationLock | null, map: CacheMap<SegmentCacheEntry>, debugInfo: Array<unknown> | null, routeCacheEntry: FulfilledRouteCacheEntry | null, signal: AbortSignal | undefined): AppRouterState; | ||
| export declare function completeHardNavigation(state: AppRouterState, url: URL, navigateType: 'push' | 'replace'): AppRouterState; | ||
@@ -29,3 +30,3 @@ export declare function completeSoftNavigation(oldState: AppRouterState, url: URL, referringNextUrl: string | null, tree: FlightRouterState, cache: CacheNode, renderedSearch: string, canonicalUrl: string, navigateType: 'push' | 'replace', scrollBehavior: ScrollBehavior, scrollRef: ScrollRef | null, collectedDebugInfo: Array<unknown> | null): AppRouterState; | ||
| }; | ||
| focusAndScrollRef: import("../router-reducer/router-reducer-types").FocusAndScrollRef; | ||
| scrollRef: import("../router-reducer/router-reducer-types").ScrollHandlerRef; | ||
| cache: CacheNode; | ||
@@ -32,0 +33,0 @@ tree: FlightRouterState; |
@@ -71,5 +71,8 @@ "use strict"; | ||
| } | ||
| return navigateImpl(state, url, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType, navigationLock); | ||
| return navigateImpl(state, url, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType, navigationLock, // An unlocked navigation is bound to the shared map. | ||
| _cache.segmentCacheMap); | ||
| } | ||
| function navigateImpl(state, url, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType, navigationLock) { | ||
| function navigateImpl(state, url, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType, navigationLock, // The segment cache map this navigation is bound to: a locked navigation's | ||
| // driving-task map, or the shared map. See `segmentCacheMap` in cache.ts. | ||
| map) { | ||
| const now = Date.now(); | ||
@@ -81,3 +84,3 @@ const href = url.href; | ||
| // We have a matching prefetch. | ||
| return navigateUsingPrefetchedRouteTree(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, route, navigationLock); | ||
| return navigateUsingPrefetchedRouteTree(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, route, navigationLock, map); | ||
| } | ||
@@ -100,3 +103,3 @@ // There was no matching route tree in the cache. Let's see if we can | ||
| // We have an optimistic route tree. Proceed with the normal flow. | ||
| return navigateUsingPrefetchedRouteTree(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, optimisticRoute, navigationLock); | ||
| return navigateUsingPrefetchedRouteTree(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, optimisticRoute, navigationLock, map); | ||
| } | ||
@@ -110,3 +113,3 @@ } | ||
| // dynamic request, we should do a runtime prefetch. | ||
| return navigateToUnknownRoute(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, navigationLock).catch(()=>{ | ||
| return navigateToUnknownRoute(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, navigationLock, map).catch(()=>{ | ||
| // If the navigation fails, return the current state | ||
@@ -116,3 +119,5 @@ return state; | ||
| } | ||
| function navigateToKnownRoute(now, state, url, canonicalUrl, navigationSeed, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, debugInfo, // The route cache entry used for this navigation, if it came from route | ||
| function navigateToKnownRoute(now, state, url, canonicalUrl, navigationSeed, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, // The segment cache map this navigation is bound to: a locked navigation's | ||
| // driving-task map, or the shared map. See `segmentCacheMap` in cache.ts. | ||
| map, debugInfo, // The route cache entry used for this navigation, if it came from route | ||
| // prediction. Passed through so it can be marked as having a dynamic rewrite | ||
@@ -194,6 +199,6 @@ // if the server returns a different pathname (indicating dynamic rewrite | ||
| const isSamePageNavigation = url.href === currentUrl.href; | ||
| const task = (0, _pprnavigations.startPPRNavigation)(now, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, navigationSeed.routeTree, navigationSeed.metadataVaryPath, freshnessPolicy, navigationSeed.head, navigationSeed.dynamicStaleAt, isSamePageNavigation, accumulation, restrictToShell); | ||
| const task = (0, _pprnavigations.startPPRNavigation)(now, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, navigationSeed.routeTree, navigationSeed.metadataVaryPath, freshnessPolicy, navigationSeed.head, navigationSeed.dynamicStaleAt, isSamePageNavigation, accumulation, map, restrictToShell); | ||
| if (task !== null) { | ||
| if (freshnessPolicy !== _pprnavigations.FreshnessPolicy.Gesture) { | ||
| (0, _pprnavigations.spawnDynamicRequests)(task, url, nextUrl, freshnessPolicy, accumulation, routeCacheEntry, navigateType, navigationLock, signal); | ||
| (0, _pprnavigations.spawnDynamicRequests)(task, url, nextUrl, freshnessPolicy, accumulation, routeCacheEntry, navigateType, navigationLock, map, signal); | ||
| } | ||
@@ -205,3 +210,3 @@ return completeSoftNavigation(state, url, nextUrl, task.route, task.node, navigationSeed.renderedSearch, canonicalUrl, navigateType, scrollBehavior, accumulation.scrollRef, debugInfo); | ||
| } | ||
| function navigateUsingPrefetchedRouteTree(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, route, navigationLock) { | ||
| function navigateUsingPrefetchedRouteTree(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, route, navigationLock, map) { | ||
| const routeTree = route.tree; | ||
@@ -219,3 +224,3 @@ const canonicalUrl = route.canonicalUrl + url.hash; | ||
| }; | ||
| return navigateToKnownRoute(now, state, url, canonicalUrl, prefetchSeed, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, null, route, // Not an HMR refresh, so there's no request generation to cancel. | ||
| return navigateToKnownRoute(now, state, url, canonicalUrl, prefetchSeed, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, map, null, route, // Not an HMR refresh, so there's no request generation to cancel. | ||
| undefined); | ||
@@ -234,3 +239,3 @@ } | ||
| ]; | ||
| async function navigateToUnknownRoute(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, navigationLock) { | ||
| async function navigateToUnknownRoute(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, navigationLock, map) { | ||
| // Runs when a navigation happens but there's no cached prefetch we can use. | ||
@@ -300,3 +305,3 @@ // Don't bother to wait for a prefetch response; go straight to a full | ||
| // Shells. | ||
| (0, _cache.writePrerenderResponseIntoCache)(now, _types.FetchStrategy.PPR, staticStageResponse.t ?? null, buildId, staticStageResponse.r ?? null, staleAt, currentFlightRouterState, renderedSearch, isResponsePartial); | ||
| (0, _cache.writePrerenderResponseIntoCache)(now, _types.FetchStrategy.PPR, staticStageResponse.t ?? null, buildId, staticStageResponse.r ?? null, staleAt, currentFlightRouterState, renderedSearch, isResponsePartial, map); | ||
| }).catch(()=>{ | ||
@@ -310,3 +315,3 @@ // The static stage processing failed. Not fatal — the navigation | ||
| if (processed !== null) { | ||
| (0, _cache.writeDynamicRenderResponseIntoCache)(now, _types.FetchStrategy.PPRRuntime, processed.buildId, processed.isResponsePartial, processed.headVaryParams, processed.rootVaryParamsIterable, processed.staleAt, processed.navigationSeed, null); | ||
| (0, _cache.writeDynamicRenderResponseIntoCache)(now, _types.FetchStrategy.PPRRuntime, processed.buildId, processed.isResponsePartial, processed.headVaryParams, processed.rootVaryParamsIterable, processed.staleAt, processed.navigationSeed, null, map); | ||
| } | ||
@@ -333,3 +338,3 @@ }).catch(()=>{ | ||
| } | ||
| return navigateToKnownRoute(now, state, url, (0, _createhreffromurl.createHrefFromUrl)(canonicalUrl), navigationSeed, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, debugInfo, // Unknown route navigations don't use route prediction - the route tree | ||
| return navigateToKnownRoute(now, state, url, (0, _createhreffromurl.createHrefFromUrl)(canonicalUrl), navigationSeed, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, map, debugInfo, // Unknown route navigations don't use route prediction - the route tree | ||
| // came directly from the server. If a mismatch occurs during dynamic data | ||
@@ -359,3 +364,3 @@ // fetch, the retry handler will traverse the known route tree to mark the | ||
| renderedSearch: state.renderedSearch, | ||
| focusAndScrollRef: state.focusAndScrollRef, | ||
| scrollRef: state.scrollRef, | ||
| cache: state.cache, | ||
@@ -420,3 +425,3 @@ tree: state.tree, | ||
| } | ||
| activeScrollRef = oldState.focusAndScrollRef.scrollRef; | ||
| activeScrollRef = oldState.scrollRef.scrollRef; | ||
| forceScroll = false; | ||
@@ -429,3 +434,3 @@ } else if (onlyHashChange) { | ||
| // been consumed yet. | ||
| const oldScrollRef = oldState.focusAndScrollRef.scrollRef; | ||
| const oldScrollRef = oldState.scrollRef.scrollRef; | ||
| if (oldScrollRef !== null) { | ||
@@ -452,3 +457,3 @@ oldScrollRef.current = false; | ||
| if (scrollRef !== null) { | ||
| const oldScrollRef = oldState.focusAndScrollRef.scrollRef; | ||
| const oldScrollRef = oldState.scrollRef.scrollRef; | ||
| if (oldScrollRef !== null) { | ||
@@ -468,3 +473,3 @@ oldScrollRef.current = false; | ||
| }, | ||
| focusAndScrollRef: { | ||
| scrollRef: { | ||
| scrollRef: activeScrollRef, | ||
@@ -478,4 +483,4 @@ forceScroll, | ||
| // | ||
| // Refer to `ScrollAndFocusHandler` for details on how this is used. | ||
| scrollBehavior !== _routerreducertypes.ScrollBehavior.NoScroll && url.hash !== '' ? decodeURIComponent(url.hash.slice(1)) : oldState.focusAndScrollRef.hashFragment | ||
| // Refer to `ScrollHandler` for details on how this is used. | ||
| scrollBehavior !== _routerreducertypes.ScrollBehavior.NoScroll && url.hash !== '' ? decodeURIComponent(url.hash.slice(1)) : oldState.scrollRef.hashFragment | ||
| }, | ||
@@ -501,3 +506,3 @@ cache, | ||
| }, | ||
| focusAndScrollRef: state.focusAndScrollRef, | ||
| scrollRef: state.scrollRef, | ||
| cache, | ||
@@ -527,8 +532,8 @@ // Restore provided tree | ||
| // the prefetch as a locked-navigation prefetch. The prefetch's promise | ||
| // resolves once it has spawned every request and all of them have fulfilled, | ||
| // so the navigation below reads present data rather than a still-in-flight | ||
| // entry. | ||
| // resolves when the task completes — after every segment response the task | ||
| // cares about has settled — so the navigation below reads present data | ||
| // rather than a still-in-flight entry. | ||
| const { beginNavigationLockPrefetch } = require('./navigation-testing-lock'); | ||
| const navigationLockPrefetch = beginNavigationLockPrefetch(); | ||
| (0, _scheduler.schedulePrefetchTask)(cacheKey, currentFlightRouterState, fetchStrategy, _types.PrefetchPriority.Default, null, navigationLockPrefetch); | ||
| const prefetchTask = (0, _scheduler.schedulePrefetchTask)(cacheKey, currentFlightRouterState, fetchStrategy, _types.PrefetchPriority.Default, null, navigationLockPrefetch); | ||
| if (navigationLockPrefetch !== null) { | ||
@@ -538,4 +543,7 @@ await navigationLockPrefetch.promise; | ||
| // Prefetch is complete. Proceed with the normal navigation flow, which | ||
| // will now find the route in the cache. | ||
| const result = await navigateImpl(state, url, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType, navigationLock); | ||
| // will now find the route in the cache. The navigation inherits the map of | ||
| // the prefetch task that drives it: the task was scheduled inside the lock | ||
| // scope, so this is the scope's private map, and the navigation reads only | ||
| // data fetched under the lock. | ||
| const result = await navigateImpl(state, url, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType, navigationLock, prefetchTask.segmentCacheMap); | ||
| // Only transition to captured-SPA once the navigation is known to be an SPA. | ||
@@ -542,0 +550,0 @@ // If the result is an MPA navigation, leave the cookie pending and let the new |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/client/components/segment-cache/navigation.ts"],"sourcesContent":["import type {\n FlightRouterState,\n ScrollRef,\n} from '../../../shared/lib/app-router-types'\nimport type { CacheNode } from '../../../shared/lib/app-router-types'\nimport { PrefetchHint } from '../../../shared/lib/app-router-types'\nimport { fetchServerResponse } from '../router-reducer/fetch-server-response'\nimport {\n startPPRNavigation,\n spawnDynamicRequests,\n FreshnessPolicy,\n beginLockedNavigation,\n type NavigationLock,\n type NavigationRequestAccumulation,\n} from '../router-reducer/ppr-navigations'\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport {\n EntryStatus,\n readRouteCacheEntry,\n deprecated_requestOptimisticRouteCacheEntry,\n resolveStaleAt,\n writePrerenderResponseIntoCache,\n processRuntimePrefetchStream,\n writeDynamicRenderResponseIntoCache,\n type FulfilledRouteCacheEntry,\n} from './cache'\nimport { discoverKnownRoute } from './optimistic-routes'\nimport { createCacheKey, type NormalizedSearch } from './cache-key'\nimport { schedulePrefetchTask } from './scheduler'\nimport { PrefetchPriority, FetchStrategy } from './types'\nimport { getLinkForCurrentNavigation } from '../links'\nimport type { AppRouterState } from '../router-reducer/router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer/router-reducer-types'\nimport { computeChangedPath } from '../router-reducer/compute-changed-path'\nimport { isJavaScriptURLString } from '../../lib/javascript-url'\nimport { UnknownDynamicStaleTime, computeDynamicStaleAt } from './bfcache'\nimport { createLinkPrefetchPartialError } from '../../../shared/lib/instant-messages'\nimport {\n convertServerPatchToFullTree,\n type NavigationSeed,\n} from './decode-server-response'\n\n/**\n * Navigate to a new URL, using the Segment Cache to construct a response.\n *\n * To allow for synchronous navigations whenever possible, this is not an async\n * function. It returns a promise only if there's no matching prefetch in\n * the cache. Otherwise it returns an immediate result and uses Suspense/RSC to\n * stream in any missing data.\n */\nexport function navigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace'\n): AppRouterState | Promise<AppRouterState> {\n let navigationLock: NavigationLock | null = null\n\n // Instant Navigation Testing API: when the lock is active, ensure a\n // prefetch task has been initiated before proceeding with the navigation.\n // This guarantees that segment data requests are at least pending, even\n // for routes that already have a cached route tree. Without this, the\n // shell might be incomplete because some segments were never\n // requested.\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { isNavigationLocked } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n if (isNavigationLocked()) {\n // Signal that a new locked navigation is starting. This force-resolves the\n // previous locked navigation's withheld data (so a reused shared segment\n // no longer carries a pending deferred rsc) and returns this navigation's\n // own withheld-data gate.\n navigationLock = beginLockedNavigation()\n return ensurePrefetchThenNavigate(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n }\n }\n\n return navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n}\n\nfunction navigateImpl(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): AppRouterState | Promise<AppRouterState> {\n const now = Date.now()\n const href = url.href\n\n const cacheKey = createCacheKey(href, nextUrl)\n const route = readRouteCacheEntry(now, cacheKey)\n if (route !== null && route.status === EntryStatus.Fulfilled) {\n // We have a matching prefetch.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n route,\n navigationLock\n )\n }\n\n // There was no matching route tree in the cache. Let's see if we can\n // construct an \"optimistic\" route tree using the deprecated search-params\n // based matching. This is only used when the new optimisticRouting flag is\n // disabled.\n //\n // Do not construct an optimistic route tree if there was a cache hit, but\n // the entry has a rejected status, since it may have been rejected due to a\n // rewrite or redirect based on the search params.\n //\n // TODO: There are multiple reasons a prefetch might be rejected; we should\n // track them explicitly and choose what to do here based on that.\n if (!process.env.__NEXT_OPTIMISTIC_ROUTING) {\n if (route === null || route.status !== EntryStatus.Rejected) {\n const optimisticRoute = deprecated_requestOptimisticRouteCacheEntry(\n now,\n url,\n nextUrl\n )\n if (optimisticRoute !== null) {\n // We have an optimistic route tree. Proceed with the normal flow.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n optimisticRoute,\n navigationLock\n )\n }\n }\n }\n\n // There's no matching prefetch for this route in the cache. We must lazily\n // fetch it from the server before we can perform the navigation.\n //\n // TODO: If this is a gesture navigation, instead of performing a\n // dynamic request, we should do a runtime prefetch.\n return navigateToUnknownRoute(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n ).catch(() => {\n // If the navigation fails, return the current state\n return state\n })\n}\n\nexport function navigateToKnownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n canonicalUrl: string,\n navigationSeed: NavigationSeed,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n nextUrl: string | null,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n debugInfo: Array<unknown> | null,\n // The route cache entry used for this navigation, if it came from route\n // prediction. Passed through so it can be marked as having a dynamic rewrite\n // if the server returns a different pathname (indicating dynamic rewrite\n // behavior).\n //\n // When null, the navigation did not use route prediction - either because\n // the route was already fully cached, or it's a navigation that doesn't\n // involve prediction (refresh, history traversal, server action, etc.).\n // In these cases, if a mismatch occurs, we still mark the route as having a\n // dynamic rewrite by traversing the known route tree (see\n // dispatchRetryDueToTreeMismatch).\n routeCacheEntry: FulfilledRouteCacheEntry | null,\n signal: AbortSignal | undefined\n): AppRouterState {\n // A version of navigate() that accepts the target route tree as an argument\n // rather than reading it from the prefetch cache.\n if (\n process.env.NODE_ENV !== 'production' &&\n process.env.__NEXT_CACHE_COMPONENTS\n ) {\n // Warn when navigating via a `<Link prefetch={true}>` to a route that has\n // not opted into Partial Prefetching. Such a link does a legacy \"full\"\n // prefetch that includes the route's dynamic data, defeating the\n // static/dynamic split that Cache Components provides.\n //\n // This runs at navigation time (rather than prefetch time) so that, in dev\n // where we don't prefetch, the warning only appears when you actually\n // navigate to the route — existing apps with many `prefetch={true}` links\n // aren't flooded with warnings the moment they enable Cache Components.\n //\n // The warning is suppressed if any segment on the target route exports\n // `instant = false`, which is the explicit API for opting a route out of\n // this validation.\n const link = getLinkForCurrentNavigation()\n if (\n link !== null &&\n link.fetchStrategy === FetchStrategy.Full &&\n (navigationSeed.routeTree.prefetchHints &\n (PrefetchHint.SubtreeHasPartialPrefetching |\n PrefetchHint.SubtreeHasInstantFalse)) ===\n 0\n ) {\n const error = createLinkPrefetchPartialError(url.pathname)\n const ownerStack = 'ownerStack' in link ? link.ownerStack : undefined\n if (ownerStack === undefined) {\n console.error(\n '' +\n 'Cannot associate the \"prefetch={true}\" warning with a specific <Link> making it harder to find the cause of the following warning. ' +\n 'This is a bug in Next.js.'\n )\n } else if (ownerStack !== null) {\n // Replace the (useless) stack captured at the throw site — which\n // points into router internals — with the Owner Stack captured when\n // the <Link> rendered. That way the dev overlay associates this\n // warning with the JSX that created the link, not with\n // navigation.ts.\n error.stack = `${error.name}: ${error.message}${ownerStack}`\n }\n console.error(error)\n }\n }\n\n // Instant Navigation Testing API: when the lock is held, restrict segment\n // reads to shell entries if the target route would only have prefetched\n // its shell.\n let restrictToShell = false\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { shouldRestrictNavigationToShell } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const link = getLinkForCurrentNavigation()\n restrictToShell = shouldRestrictNavigationToShell(\n navigationSeed.routeTree.prefetchHints,\n link !== null ? link.fetchStrategy : FetchStrategy.PPR\n )\n }\n\n const accumulation: NavigationRequestAccumulation = {\n separateRefreshUrls: null,\n scrollRef: null,\n }\n // We special case navigations to the exact same URL as the current location.\n // It's a common UI pattern for apps to refresh when you click a link to the\n // current page. So when this happens, we refresh the dynamic data in the page\n // segments.\n //\n // Note that this does not apply if the any part of the hash or search query\n // has changed. This might feel a bit weird but it makes more sense when you\n // consider that the way to trigger this behavior is to click the same link\n // multiple times.\n //\n // TODO: We should probably refresh the *entire* route when this case occurs,\n // not just the page segments. Essentially treating it the same as a refresh()\n // triggered by an action, which is the more explicit way of modeling the UI\n // pattern described above.\n //\n // Also note that this only refreshes the dynamic data, not static/ cached\n // data. If the page segment is fully static and prefetched, the request is\n // skipped. (This is also how refresh() works.)\n const isSamePageNavigation = url.href === currentUrl.href\n const task = startPPRNavigation(\n now,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n navigationSeed.routeTree,\n navigationSeed.metadataVaryPath,\n freshnessPolicy,\n navigationSeed.head,\n navigationSeed.dynamicStaleAt,\n isSamePageNavigation,\n accumulation,\n restrictToShell\n )\n if (task !== null) {\n if (freshnessPolicy !== FreshnessPolicy.Gesture) {\n spawnDynamicRequests(\n task,\n url,\n nextUrl,\n freshnessPolicy,\n accumulation,\n routeCacheEntry,\n navigateType,\n navigationLock,\n signal\n )\n }\n return completeSoftNavigation(\n state,\n url,\n nextUrl,\n task.route,\n task.node,\n navigationSeed.renderedSearch,\n canonicalUrl,\n navigateType,\n scrollBehavior,\n accumulation.scrollRef,\n debugInfo\n )\n }\n // Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.\n return completeHardNavigation(state, url, navigateType)\n}\n\nfunction navigateUsingPrefetchedRouteTree(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n route: FulfilledRouteCacheEntry,\n navigationLock: NavigationLock | null\n): AppRouterState {\n const routeTree = route.tree\n const canonicalUrl = route.canonicalUrl + url.hash\n const renderedSearch = route.renderedSearch\n const prefetchSeed: NavigationSeed = {\n renderedSearch,\n routeTree,\n metadataVaryPath: route.metadata.varyPath as any,\n head: null,\n isHeadPartial: true,\n headVaryParams: null,\n dynamicStaleAt: computeDynamicStaleAt(now, UnknownDynamicStaleTime),\n }\n return navigateToKnownRoute(\n now,\n state,\n url,\n canonicalUrl,\n prefetchSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n null,\n route,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\n// Used to request all the dynamic data for a route, rather than just a subset,\n// e.g. during a refresh or a revalidation. Typically this gets constructed\n// during the normal flow when diffing the route tree, but for an unprefetched\n// navigation, where we don't know the structure of the target route, we use\n// this instead.\nconst DynamicRequestTreeForEntireRoute: FlightRouterState = [\n '',\n {},\n null,\n 'refetch',\n]\n\nasync function navigateToUnknownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): Promise<AppRouterState> {\n // Runs when a navigation happens but there's no cached prefetch we can use.\n // Don't bother to wait for a prefetch response; go straight to a full\n // navigation that contains both static and dynamic data in a single stream.\n // (This is unlike the old navigation implementation, which instead blocks\n // the dynamic request until a prefetch request is received.)\n //\n // To avoid duplication of logic, we're going to pretend that the tree\n // returned by the dynamic request is, in fact, a prefetch tree. Then we can\n // use the same server response to write the actual data into the CacheNode\n // tree. So it's the same flow as the \"happy path\" (prefetch, then\n // navigation), except we use a single server response for both stages.\n\n let dynamicRequestTree: FlightRouterState\n switch (freshnessPolicy) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.HistoryTraversal:\n case FreshnessPolicy.Gesture:\n dynamicRequestTree = currentFlightRouterState\n break\n case FreshnessPolicy.Hydration: // <- shouldn't happen during client nav\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n dynamicRequestTree = DynamicRequestTreeForEntireRoute\n break\n default:\n freshnessPolicy satisfies never\n dynamicRequestTree = currentFlightRouterState\n break\n }\n\n const promiseForDynamicServerResponse = fetchServerResponse(url, {\n flightRouterState: dynamicRequestTree,\n nextUrl,\n })\n const result = await promiseForDynamicServerResponse\n if (typeof result === 'string') {\n // This is an MPA navigation.\n const redirectUrl = new URL(result, location.origin)\n return completeHardNavigation(state, redirectUrl, navigateType)\n }\n\n const {\n transportData,\n canonicalUrl,\n renderedSearch,\n couldBeIntercepted,\n supportsPerSegmentPrefetching,\n dynamicStaleTime,\n staticStageData,\n runtimePrefetchStream,\n responseHeaders,\n debugInfo,\n } = result\n\n // Since the response format of dynamic requests and prefetches is slightly\n // different, we'll need to massage the data a bit. Create FlightRouterState\n // tree that simulates what we'd receive as the result of a prefetch.\n const navigationSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n transportData,\n renderedSearch,\n dynamicStaleTime\n )\n\n // Learn the route pattern so we can predict it for future navigations.\n // hasDynamicRewrite is false because this is a fresh navigation to an\n // unknown route - any rewrite detection happens during the traversal inside\n // discoverKnownRoute. The hasDynamicRewrite param is only set to true when\n // retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).\n const metadataVaryPath = navigationSeed.metadataVaryPath\n if (metadataVaryPath !== null) {\n discoverKnownRoute(\n now,\n url.pathname,\n url.search as NormalizedSearch,\n nextUrl,\n null, // No pending entry\n navigationSeed.routeTree,\n metadataVaryPath,\n couldBeIntercepted,\n // Store a hashless canonical URL: the entry is shared across hashes, and\n // a later same-route hash nav appends `url.hash` to it.\n createHrefFromUrl(canonicalUrl, false),\n supportsPerSegmentPrefetching,\n false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal\n )\n\n if (staticStageData !== null) {\n const { response: staticStageResponse, isResponsePartial } =\n staticStageData\n\n // Write the static stage of the response into the segment cache so that\n // subsequent navigations can serve cached static segments instantly.\n resolveStaleAt(now, staticStageResponse.s)\n .then((staleAt) => {\n const buildId =\n responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n staticStageResponse.b\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the\n // Cached Navigations behavior should work in combination with App\n // Shells.\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.t ?? null,\n buildId,\n staticStageResponse.r ?? null,\n staleAt,\n currentFlightRouterState,\n renderedSearch,\n isResponsePartial\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the navigation\n // completed normally, we just won't write into the cache.\n })\n }\n\n if (runtimePrefetchStream !== null) {\n processRuntimePrefetchStream(\n now,\n runtimePrefetchStream,\n currentFlightRouterState,\n renderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n now,\n FetchStrategy.PPRRuntime,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null\n )\n }\n })\n .catch(() => {\n // The runtime prefetch cache write failed. Not fatal — the\n // navigation completed normally, we just won't cache runtime data.\n })\n }\n }\n\n // In the streaming dev render, this single response's seed content may still\n // be streaming when we build the tree below. An unknown-route navigation\n // places that content inline (it has no prior cache entry, so the server\n // sends a full seed rather than the dynamic-only delta a known route gets),\n // and that inline content is not gated like a known route's deferred RSCs. So\n // React could read a still-pending chunk and flash a Suspense fallback\n // (wanted on a cold cache, but not on a warm one). Wait for the shell to\n // flush (`revealAfter`) first, so the inline seed content is decoded by the\n // time React reads it, the same way the known-route path gates its deferred\n // RSCs. `revealAfter` is null outside the streaming dev render. On a cache\n // miss it resolves early, so the cold-cache fallback is still shown.\n if (result.revealAfter !== null) {\n await result.revealAfter\n }\n\n return navigateToKnownRoute(\n now,\n state,\n url,\n createHrefFromUrl(canonicalUrl),\n navigationSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n debugInfo,\n // Unknown route navigations don't use route prediction - the route tree\n // came directly from the server. If a mismatch occurs during dynamic data\n // fetch, the retry handler will traverse the known route tree to mark the\n // entry as having a dynamic rewrite.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\nexport function completeHardNavigation(\n state: AppRouterState,\n url: URL,\n navigateType: 'push' | 'replace'\n): AppRouterState {\n if (isJavaScriptURLString(url.href)) {\n console.error(\n 'Next.js has blocked a javascript: URL as a security precaution.'\n )\n return state\n }\n const newState: AppRouterState = {\n canonicalUrl:\n url.origin === location.origin ? createHrefFromUrl(url) : url.href,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: true,\n preserveCustomHistoryState: false,\n },\n // TODO: None of the rest of these values are consistent with the incoming\n // navigation. We rely on the fact that AppRouter will suspend and trigger\n // a hard navigation before it accesses any of these values. But instead\n // we should trigger the hard navigation and blocking any subsequent\n // router updates without updating React.\n renderedSearch: state.renderedSearch,\n focusAndScrollRef: state.focusAndScrollRef,\n cache: state.cache,\n tree: state.tree,\n nextUrl: state.nextUrl,\n previousNextUrl: state.previousNextUrl,\n debugInfo: null,\n }\n return newState\n}\n\nexport function completeSoftNavigation(\n oldState: AppRouterState,\n url: URL,\n referringNextUrl: string | null,\n tree: FlightRouterState,\n cache: CacheNode,\n renderedSearch: string,\n canonicalUrl: string,\n navigateType: 'push' | 'replace',\n scrollBehavior: ScrollBehavior,\n scrollRef: ScrollRef | null,\n collectedDebugInfo: Array<unknown> | null\n) {\n // The \"Next-Url\" is a special representation of the URL that Next.js\n // uses to implement interception routes.\n // TODO: Get rid of this extra traversal by computing this during the\n // same traversal that computes the tree itself. We should also figure out\n // what is the minimum information needed for the server to correctly\n // intercept the route.\n const changedPath = computeChangedPath(oldState.tree, tree)\n const nextUrlForNewRoute = changedPath ? changedPath : oldState.nextUrl\n\n // This value is stored on the state as `previousNextUrl`; the naming is\n // confusing. What it represents is the \"Next-Url\" header that was used to\n // fetch the incoming route. It's essentially the refererer URL, but in a\n // Next.js specific format. During refreshes, this is sent back to the server\n // instead of the current route's \"Next-Url\" so that the same interception\n // logic is applied as during the original navigation.\n const previousNextUrl = referringNextUrl\n\n // Check if the only thing that changed was the hash fragment.\n const oldUrl = new URL(oldState.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\n // Determine whether and how the page should scroll after this\n // navigation.\n //\n // By default, we scroll to the segments that were navigated to — i.e.\n // segments in the new part of the route, as opposed to shared segments\n // that were already part of the previous route. All newly navigated\n // segments share a single ScrollRef. When they mount, the first one\n // to mount initiates the scroll. They share a ref so that only one\n // scroll happens per navigation.\n //\n // If a subsequent navigation produces new segments, those supersede\n // any pending scroll from the previous navigation by invalidating its\n // ScrollRef. If a navigation doesn't produce any new segments (e.g.\n // a refresh where the route structure didn't change), any pending\n // scrolls from previous navigations are unaffected.\n //\n // The branches below handle special cases layered on top of this\n // default model.\n let activeScrollRef: ScrollRef | null\n let forceScroll: boolean\n if (scrollBehavior === ScrollBehavior.NoScroll) {\n // The user explicitly opted out of scrolling (e.g. scroll={false}\n // on a Link or router.push).\n //\n // If this navigation created new scroll targets (scrollRef !== null),\n // neutralize them. If it didn't, any prior scroll targets carried\n // forward on the cache nodes via reuseSharedCacheNode remain active.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = oldState.focusAndScrollRef.scrollRef\n forceScroll = false\n } else if (onlyHashChange) {\n // Hash-only navigations should scroll regardless of per-node state.\n // Create a fresh ref so the first segment to scroll consumes it.\n //\n // Invalidate any scroll ref from a prior navigation that hasn't\n // been consumed yet.\n const oldScrollRef = oldState.focusAndScrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n // Also invalidate any per-node refs that were accumulated during\n // this navigation's tree construction — the hash-only ref\n // supersedes them.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = { current: true }\n forceScroll = true\n } else {\n // Default case. Use the accumulated scrollRef (may be null if no\n // new segments were created). The handler checks per-node refs, so\n // unchanged parallel route slots won't scroll.\n activeScrollRef = scrollRef\n\n // If this navigation created new scroll targets, invalidate any\n // pending scroll from a previous navigation.\n if (scrollRef !== null) {\n const oldScrollRef = oldState.focusAndScrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n }\n forceScroll = false\n }\n\n const newState: AppRouterState = {\n canonicalUrl,\n renderedSearch,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: false,\n preserveCustomHistoryState: false,\n },\n focusAndScrollRef: {\n scrollRef: activeScrollRef,\n forceScroll,\n onlyHashChange,\n hashFragment:\n // Remove leading # and decode hash to make non-latin hashes work.\n //\n // Empty hash should trigger default behavior of scrolling layout into\n // view. #top is handled in layout-router.\n //\n // Refer to `ScrollAndFocusHandler` for details on how this is used.\n scrollBehavior !== ScrollBehavior.NoScroll && url.hash !== ''\n ? decodeURIComponent(url.hash.slice(1))\n : oldState.focusAndScrollRef.hashFragment,\n },\n cache,\n tree,\n nextUrl: nextUrlForNewRoute,\n previousNextUrl,\n debugInfo: collectedDebugInfo,\n }\n return newState\n}\n\nexport function completeTraverseNavigation(\n state: AppRouterState,\n url: URL,\n renderedSearch: string,\n cache: CacheNode,\n tree: FlightRouterState,\n nextUrl: string | null\n) {\n return {\n // Set canonical url\n canonicalUrl: createHrefFromUrl(url),\n renderedSearch,\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,\n // Restore provided tree\n tree,\n nextUrl,\n // TODO: We need to restore previousNextUrl, too, which represents the\n // Next-Url that was used to fetch the data. Anywhere we fetch using the\n // canonical URL, there should be a corresponding Next-Url.\n previousNextUrl: null,\n debugInfo: null,\n }\n}\n\n/**\n * Instant Navigation Testing API: ensures a prefetch task has been initiated\n * and completed before proceeding with the navigation. This guarantees that\n * segment data requests are at least pending, even for routes whose route\n * tree is already cached.\n *\n * After the prefetch completes, delegates to the normal navigation flow.\n */\nasync function ensurePrefetchThenNavigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): Promise<AppRouterState> {\n const link = getLinkForCurrentNavigation()\n const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR\n\n const cacheKey = createCacheKey(url.href, nextUrl)\n\n // Create this navigation's \"wait for prefetch to fulfill\" state and schedule\n // the prefetch as a locked-navigation prefetch. The prefetch's promise\n // resolves once it has spawned every request and all of them have fulfilled,\n // so the navigation below reads present data rather than a still-in-flight\n // entry.\n const { beginNavigationLockPrefetch } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const navigationLockPrefetch = beginNavigationLockPrefetch()\n schedulePrefetchTask(\n cacheKey,\n currentFlightRouterState,\n fetchStrategy,\n PrefetchPriority.Default,\n null, // onInvalidate\n navigationLockPrefetch\n )\n if (navigationLockPrefetch !== null) {\n await navigationLockPrefetch.promise\n }\n\n // Prefetch is complete. Proceed with the normal navigation flow, which\n // will now find the route in the cache.\n const result = await navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n\n // Only transition to captured-SPA once the navigation is known to be an SPA.\n // If the result is an MPA navigation, leave the cookie pending and let the new\n // document load transition it to captured-MPA.\n if (!result.pushRef.mpaNavigation) {\n const { updateCapturedSPAToTree } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n updateCapturedSPAToTree(currentFlightRouterState, result.tree)\n }\n\n return result\n}\n"],"names":["completeHardNavigation","completeSoftNavigation","completeTraverseNavigation","navigate","navigateToKnownRoute","state","url","currentUrl","currentRenderedSearch","currentCacheNode","currentFlightRouterState","nextUrl","freshnessPolicy","scrollBehavior","navigateType","navigationLock","process","env","__NEXT_EXPOSE_TESTING_API","isNavigationLocked","require","beginLockedNavigation","ensurePrefetchThenNavigate","navigateImpl","now","Date","href","cacheKey","createCacheKey","route","readRouteCacheEntry","status","EntryStatus","Fulfilled","navigateUsingPrefetchedRouteTree","__NEXT_OPTIMISTIC_ROUTING","Rejected","optimisticRoute","deprecated_requestOptimisticRouteCacheEntry","navigateToUnknownRoute","catch","canonicalUrl","navigationSeed","debugInfo","routeCacheEntry","signal","NODE_ENV","__NEXT_CACHE_COMPONENTS","link","getLinkForCurrentNavigation","fetchStrategy","FetchStrategy","Full","routeTree","prefetchHints","PrefetchHint","SubtreeHasPartialPrefetching","SubtreeHasInstantFalse","error","createLinkPrefetchPartialError","pathname","ownerStack","undefined","console","stack","name","message","restrictToShell","shouldRestrictNavigationToShell","PPR","accumulation","separateRefreshUrls","scrollRef","isSamePageNavigation","task","startPPRNavigation","metadataVaryPath","head","dynamicStaleAt","FreshnessPolicy","Gesture","spawnDynamicRequests","node","renderedSearch","tree","hash","prefetchSeed","metadata","varyPath","isHeadPartial","headVaryParams","computeDynamicStaleAt","UnknownDynamicStaleTime","DynamicRequestTreeForEntireRoute","dynamicRequestTree","Default","HistoryTraversal","Hydration","RefreshAll","HMRRefresh","promiseForDynamicServerResponse","fetchServerResponse","flightRouterState","result","redirectUrl","URL","location","origin","transportData","couldBeIntercepted","supportsPerSegmentPrefetching","dynamicStaleTime","staticStageData","runtimePrefetchStream","responseHeaders","convertServerPatchToFullTree","discoverKnownRoute","search","createHrefFromUrl","response","staticStageResponse","isResponsePartial","resolveStaleAt","s","then","staleAt","buildId","get","NEXT_NAV_DEPLOYMENT_ID_HEADER","b","writePrerenderResponseIntoCache","t","r","processRuntimePrefetchStream","processed","writeDynamicRenderResponseIntoCache","PPRRuntime","rootVaryParamsIterable","revealAfter","isJavaScriptURLString","newState","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","cache","previousNextUrl","oldState","referringNextUrl","collectedDebugInfo","changedPath","computeChangedPath","nextUrlForNewRoute","oldUrl","onlyHashChange","activeScrollRef","forceScroll","ScrollBehavior","NoScroll","current","oldScrollRef","hashFragment","decodeURIComponent","slice","beginNavigationLockPrefetch","navigationLockPrefetch","schedulePrefetchTask","PrefetchPriority","promise","updateCapturedSPAToTree"],"mappings":";;;;;;;;;;;;;;;;;;IAgoBgBA,sBAAsB;eAAtBA;;IAmCAC,sBAAsB;eAAtBA;;IA0IAC,0BAA0B;eAA1BA;;IA1vBAC,QAAQ;eAARA;;IAgKAC,oBAAoB;eAApBA;;;gCA9Ma;qCACO;gCAQ7B;mCAC2B;2BACY;uBAUvC;kCAC4B;0BACmB;2BACjB;uBACW;uBACJ;oCAEb;oCACI;+BACG;yBACyB;iCAChB;sCAIxC;AAUA,SAASD,SACdE,KAAqB,EACrBC,GAAQ,EACRC,UAAe,EACfC,qBAA6B,EAC7BC,gBAAkC,EAClCC,wBAA2C,EAC3CC,OAAsB,EACtBC,eAAgC,EAChCC,cAA8B,EAC9BC,YAAgC;IAEhC,IAAIC,iBAAwC;IAE5C,oEAAoE;IACpE,0EAA0E;IAC1E,wEAAwE;IACxE,sEAAsE;IACtE,6DAA6D;IAC7D,aAAa;IACb,IAAIC,QAAQC,GAAG,CAACC,yBAAyB,EAAE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BG,OAAO;IACtC;IAEA,uEAAuE;IACvE,wCAAwC;IACxC,MAAMlE,SAAS,MAAMhF,aACnBlB,OACAC,KACAC,YACAC,uBACAC,kBACAC,0BACAC,SACAC,iBACAC,gBACAC,cACAC;IAGF,6EAA6E;IAC7E,+EAA+E;IAC/E,+CAA+C;IAC/C,IAAI,CAACwF,OAAOsC,OAAO,CAACE,aAAa,EAAE;QACjC,MAAM,EAAE2B,uBAAuB,EAAE,GAC/BtJ,QAAQ;QACVsJ,wBAAwBhK,0BAA0B6F,OAAOnB,IAAI;IAC/D;IAEA,OAAOmB;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/client/components/segment-cache/navigation.ts"],"sourcesContent":["import type {\n FlightRouterState,\n ScrollRef,\n} from '../../../shared/lib/app-router-types'\nimport type { CacheNode } from '../../../shared/lib/app-router-types'\nimport { PrefetchHint } from '../../../shared/lib/app-router-types'\nimport { fetchServerResponse } from '../router-reducer/fetch-server-response'\nimport {\n startPPRNavigation,\n spawnDynamicRequests,\n FreshnessPolicy,\n beginLockedNavigation,\n type NavigationLock,\n type NavigationRequestAccumulation,\n} from '../router-reducer/ppr-navigations'\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport {\n EntryStatus,\n segmentCacheMap,\n type SegmentCacheEntry,\n readRouteCacheEntry,\n deprecated_requestOptimisticRouteCacheEntry,\n resolveStaleAt,\n writePrerenderResponseIntoCache,\n processRuntimePrefetchStream,\n writeDynamicRenderResponseIntoCache,\n type FulfilledRouteCacheEntry,\n} from './cache'\nimport { discoverKnownRoute } from './optimistic-routes'\nimport { createCacheKey, type NormalizedSearch } from './cache-key'\nimport type { CacheMap } from './cache-map'\nimport { schedulePrefetchTask } from './scheduler'\nimport { PrefetchPriority, FetchStrategy } from './types'\nimport { getLinkForCurrentNavigation } from '../links'\nimport type { AppRouterState } from '../router-reducer/router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer/router-reducer-types'\nimport { computeChangedPath } from '../router-reducer/compute-changed-path'\nimport { isJavaScriptURLString } from '../../lib/javascript-url'\nimport { UnknownDynamicStaleTime, computeDynamicStaleAt } from './bfcache'\nimport { createLinkPrefetchPartialError } from '../../../shared/lib/instant-messages'\nimport {\n convertServerPatchToFullTree,\n type NavigationSeed,\n} from './decode-server-response'\n\n/**\n * Navigate to a new URL, using the Segment Cache to construct a response.\n *\n * To allow for synchronous navigations whenever possible, this is not an async\n * function. It returns a promise only if there's no matching prefetch in\n * the cache. Otherwise it returns an immediate result and uses Suspense/RSC to\n * stream in any missing data.\n */\nexport function navigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace'\n): AppRouterState | Promise<AppRouterState> {\n let navigationLock: NavigationLock | null = null\n\n // Instant Navigation Testing API: when the lock is active, ensure a\n // prefetch task has been initiated before proceeding with the navigation.\n // This guarantees that segment data requests are at least pending, even\n // for routes that already have a cached route tree. Without this, the\n // shell might be incomplete because some segments were never\n // requested.\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { isNavigationLocked } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n if (isNavigationLocked()) {\n // Signal that a new locked navigation is starting. This force-resolves the\n // previous locked navigation's withheld data (so a reused shared segment\n // no longer carries a pending deferred rsc) and returns this navigation's\n // own withheld-data gate.\n navigationLock = beginLockedNavigation()\n return ensurePrefetchThenNavigate(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n }\n }\n\n return navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n // An unlocked navigation is bound to the shared map.\n segmentCacheMap\n )\n}\n\nfunction navigateImpl(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n // The segment cache map this navigation is bound to: a locked navigation's\n // driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.\n map: CacheMap<SegmentCacheEntry>\n): AppRouterState | Promise<AppRouterState> {\n const now = Date.now()\n const href = url.href\n\n const cacheKey = createCacheKey(href, nextUrl)\n const route = readRouteCacheEntry(now, cacheKey)\n if (route !== null && route.status === EntryStatus.Fulfilled) {\n // We have a matching prefetch.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n route,\n navigationLock,\n map\n )\n }\n\n // There was no matching route tree in the cache. Let's see if we can\n // construct an \"optimistic\" route tree using the deprecated search-params\n // based matching. This is only used when the new optimisticRouting flag is\n // disabled.\n //\n // Do not construct an optimistic route tree if there was a cache hit, but\n // the entry has a rejected status, since it may have been rejected due to a\n // rewrite or redirect based on the search params.\n //\n // TODO: There are multiple reasons a prefetch might be rejected; we should\n // track them explicitly and choose what to do here based on that.\n if (!process.env.__NEXT_OPTIMISTIC_ROUTING) {\n if (route === null || route.status !== EntryStatus.Rejected) {\n const optimisticRoute = deprecated_requestOptimisticRouteCacheEntry(\n now,\n url,\n nextUrl\n )\n if (optimisticRoute !== null) {\n // We have an optimistic route tree. Proceed with the normal flow.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n optimisticRoute,\n navigationLock,\n map\n )\n }\n }\n }\n\n // There's no matching prefetch for this route in the cache. We must lazily\n // fetch it from the server before we can perform the navigation.\n //\n // TODO: If this is a gesture navigation, instead of performing a\n // dynamic request, we should do a runtime prefetch.\n return navigateToUnknownRoute(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n map\n ).catch(() => {\n // If the navigation fails, return the current state\n return state\n })\n}\n\nexport function navigateToKnownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n canonicalUrl: string,\n navigationSeed: NavigationSeed,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n nextUrl: string | null,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n // The segment cache map this navigation is bound to: a locked navigation's\n // driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.\n map: CacheMap<SegmentCacheEntry>,\n debugInfo: Array<unknown> | null,\n // The route cache entry used for this navigation, if it came from route\n // prediction. Passed through so it can be marked as having a dynamic rewrite\n // if the server returns a different pathname (indicating dynamic rewrite\n // behavior).\n //\n // When null, the navigation did not use route prediction - either because\n // the route was already fully cached, or it's a navigation that doesn't\n // involve prediction (refresh, history traversal, server action, etc.).\n // In these cases, if a mismatch occurs, we still mark the route as having a\n // dynamic rewrite by traversing the known route tree (see\n // dispatchRetryDueToTreeMismatch).\n routeCacheEntry: FulfilledRouteCacheEntry | null,\n signal: AbortSignal | undefined\n): AppRouterState {\n // A version of navigate() that accepts the target route tree as an argument\n // rather than reading it from the prefetch cache.\n if (\n process.env.NODE_ENV !== 'production' &&\n process.env.__NEXT_CACHE_COMPONENTS\n ) {\n // Warn when navigating via a `<Link prefetch={true}>` to a route that has\n // not opted into Partial Prefetching. Such a link does a legacy \"full\"\n // prefetch that includes the route's dynamic data, defeating the\n // static/dynamic split that Cache Components provides.\n //\n // This runs at navigation time (rather than prefetch time) so that, in dev\n // where we don't prefetch, the warning only appears when you actually\n // navigate to the route — existing apps with many `prefetch={true}` links\n // aren't flooded with warnings the moment they enable Cache Components.\n //\n // The warning is suppressed if any segment on the target route exports\n // `instant = false`, which is the explicit API for opting a route out of\n // this validation.\n const link = getLinkForCurrentNavigation()\n if (\n link !== null &&\n link.fetchStrategy === FetchStrategy.Full &&\n (navigationSeed.routeTree.prefetchHints &\n (PrefetchHint.SubtreeHasPartialPrefetching |\n PrefetchHint.SubtreeHasInstantFalse)) ===\n 0\n ) {\n const error = createLinkPrefetchPartialError(url.pathname)\n const ownerStack = 'ownerStack' in link ? link.ownerStack : undefined\n if (ownerStack === undefined) {\n console.error(\n '' +\n 'Cannot associate the \"prefetch={true}\" warning with a specific <Link> making it harder to find the cause of the following warning. ' +\n 'This is a bug in Next.js.'\n )\n } else if (ownerStack !== null) {\n // Replace the (useless) stack captured at the throw site — which\n // points into router internals — with the Owner Stack captured when\n // the <Link> rendered. That way the dev overlay associates this\n // warning with the JSX that created the link, not with\n // navigation.ts.\n error.stack = `${error.name}: ${error.message}${ownerStack}`\n }\n console.error(error)\n }\n }\n\n // Instant Navigation Testing API: when the lock is held, restrict segment\n // reads to shell entries if the target route would only have prefetched\n // its shell.\n let restrictToShell = false\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { shouldRestrictNavigationToShell } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const link = getLinkForCurrentNavigation()\n restrictToShell = shouldRestrictNavigationToShell(\n navigationSeed.routeTree.prefetchHints,\n link !== null ? link.fetchStrategy : FetchStrategy.PPR\n )\n }\n\n const accumulation: NavigationRequestAccumulation = {\n separateRefreshUrls: null,\n scrollRef: null,\n }\n // We special case navigations to the exact same URL as the current location.\n // It's a common UI pattern for apps to refresh when you click a link to the\n // current page. So when this happens, we refresh the dynamic data in the page\n // segments.\n //\n // Note that this does not apply if the any part of the hash or search query\n // has changed. This might feel a bit weird but it makes more sense when you\n // consider that the way to trigger this behavior is to click the same link\n // multiple times.\n //\n // TODO: We should probably refresh the *entire* route when this case occurs,\n // not just the page segments. Essentially treating it the same as a refresh()\n // triggered by an action, which is the more explicit way of modeling the UI\n // pattern described above.\n //\n // Also note that this only refreshes the dynamic data, not static/ cached\n // data. If the page segment is fully static and prefetched, the request is\n // skipped. (This is also how refresh() works.)\n const isSamePageNavigation = url.href === currentUrl.href\n const task = startPPRNavigation(\n now,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n navigationSeed.routeTree,\n navigationSeed.metadataVaryPath,\n freshnessPolicy,\n navigationSeed.head,\n navigationSeed.dynamicStaleAt,\n isSamePageNavigation,\n accumulation,\n map,\n restrictToShell\n )\n if (task !== null) {\n if (freshnessPolicy !== FreshnessPolicy.Gesture) {\n spawnDynamicRequests(\n task,\n url,\n nextUrl,\n freshnessPolicy,\n accumulation,\n routeCacheEntry,\n navigateType,\n navigationLock,\n map,\n signal\n )\n }\n return completeSoftNavigation(\n state,\n url,\n nextUrl,\n task.route,\n task.node,\n navigationSeed.renderedSearch,\n canonicalUrl,\n navigateType,\n scrollBehavior,\n accumulation.scrollRef,\n debugInfo\n )\n }\n // Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.\n return completeHardNavigation(state, url, navigateType)\n}\n\nfunction navigateUsingPrefetchedRouteTree(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n route: FulfilledRouteCacheEntry,\n navigationLock: NavigationLock | null,\n map: CacheMap<SegmentCacheEntry>\n): AppRouterState {\n const routeTree = route.tree\n const canonicalUrl = route.canonicalUrl + url.hash\n const renderedSearch = route.renderedSearch\n const prefetchSeed: NavigationSeed = {\n renderedSearch,\n routeTree,\n metadataVaryPath: route.metadata.varyPath as any,\n head: null,\n isHeadPartial: true,\n headVaryParams: null,\n dynamicStaleAt: computeDynamicStaleAt(now, UnknownDynamicStaleTime),\n }\n return navigateToKnownRoute(\n now,\n state,\n url,\n canonicalUrl,\n prefetchSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n map,\n null,\n route,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\n// Used to request all the dynamic data for a route, rather than just a subset,\n// e.g. during a refresh or a revalidation. Typically this gets constructed\n// during the normal flow when diffing the route tree, but for an unprefetched\n// navigation, where we don't know the structure of the target route, we use\n// this instead.\nconst DynamicRequestTreeForEntireRoute: FlightRouterState = [\n '',\n {},\n null,\n 'refetch',\n]\n\nasync function navigateToUnknownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n map: CacheMap<SegmentCacheEntry>\n): Promise<AppRouterState> {\n // Runs when a navigation happens but there's no cached prefetch we can use.\n // Don't bother to wait for a prefetch response; go straight to a full\n // navigation that contains both static and dynamic data in a single stream.\n // (This is unlike the old navigation implementation, which instead blocks\n // the dynamic request until a prefetch request is received.)\n //\n // To avoid duplication of logic, we're going to pretend that the tree\n // returned by the dynamic request is, in fact, a prefetch tree. Then we can\n // use the same server response to write the actual data into the CacheNode\n // tree. So it's the same flow as the \"happy path\" (prefetch, then\n // navigation), except we use a single server response for both stages.\n\n let dynamicRequestTree: FlightRouterState\n switch (freshnessPolicy) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.HistoryTraversal:\n case FreshnessPolicy.Gesture:\n dynamicRequestTree = currentFlightRouterState\n break\n case FreshnessPolicy.Hydration: // <- shouldn't happen during client nav\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n dynamicRequestTree = DynamicRequestTreeForEntireRoute\n break\n default:\n freshnessPolicy satisfies never\n dynamicRequestTree = currentFlightRouterState\n break\n }\n\n const promiseForDynamicServerResponse = fetchServerResponse(url, {\n flightRouterState: dynamicRequestTree,\n nextUrl,\n })\n const result = await promiseForDynamicServerResponse\n if (typeof result === 'string') {\n // This is an MPA navigation.\n const redirectUrl = new URL(result, location.origin)\n return completeHardNavigation(state, redirectUrl, navigateType)\n }\n\n const {\n transportData,\n canonicalUrl,\n renderedSearch,\n couldBeIntercepted,\n supportsPerSegmentPrefetching,\n dynamicStaleTime,\n staticStageData,\n runtimePrefetchStream,\n responseHeaders,\n debugInfo,\n } = result\n\n // Since the response format of dynamic requests and prefetches is slightly\n // different, we'll need to massage the data a bit. Create FlightRouterState\n // tree that simulates what we'd receive as the result of a prefetch.\n const navigationSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n transportData,\n renderedSearch,\n dynamicStaleTime\n )\n\n // Learn the route pattern so we can predict it for future navigations.\n // hasDynamicRewrite is false because this is a fresh navigation to an\n // unknown route - any rewrite detection happens during the traversal inside\n // discoverKnownRoute. The hasDynamicRewrite param is only set to true when\n // retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).\n const metadataVaryPath = navigationSeed.metadataVaryPath\n if (metadataVaryPath !== null) {\n discoverKnownRoute(\n now,\n url.pathname,\n url.search as NormalizedSearch,\n nextUrl,\n null, // No pending entry\n navigationSeed.routeTree,\n metadataVaryPath,\n couldBeIntercepted,\n // Store a hashless canonical URL: the entry is shared across hashes, and\n // a later same-route hash nav appends `url.hash` to it.\n createHrefFromUrl(canonicalUrl, false),\n supportsPerSegmentPrefetching,\n false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal\n )\n\n if (staticStageData !== null) {\n const { response: staticStageResponse, isResponsePartial } =\n staticStageData\n\n // Write the static stage of the response into the segment cache so that\n // subsequent navigations can serve cached static segments instantly.\n resolveStaleAt(now, staticStageResponse.s)\n .then((staleAt) => {\n const buildId =\n responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n staticStageResponse.b\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the\n // Cached Navigations behavior should work in combination with App\n // Shells.\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.t ?? null,\n buildId,\n staticStageResponse.r ?? null,\n staleAt,\n currentFlightRouterState,\n renderedSearch,\n isResponsePartial,\n map\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the navigation\n // completed normally, we just won't write into the cache.\n })\n }\n\n if (runtimePrefetchStream !== null) {\n processRuntimePrefetchStream(\n now,\n runtimePrefetchStream,\n currentFlightRouterState,\n renderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n now,\n FetchStrategy.PPRRuntime,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null,\n map\n )\n }\n })\n .catch(() => {\n // The runtime prefetch cache write failed. Not fatal — the\n // navigation completed normally, we just won't cache runtime data.\n })\n }\n }\n\n // In the streaming dev render, this single response's seed content may still\n // be streaming when we build the tree below. An unknown-route navigation\n // places that content inline (it has no prior cache entry, so the server\n // sends a full seed rather than the dynamic-only delta a known route gets),\n // and that inline content is not gated like a known route's deferred RSCs. So\n // React could read a still-pending chunk and flash a Suspense fallback\n // (wanted on a cold cache, but not on a warm one). Wait for the shell to\n // flush (`revealAfter`) first, so the inline seed content is decoded by the\n // time React reads it, the same way the known-route path gates its deferred\n // RSCs. `revealAfter` is null outside the streaming dev render. On a cache\n // miss it resolves early, so the cold-cache fallback is still shown.\n if (result.revealAfter !== null) {\n await result.revealAfter\n }\n\n return navigateToKnownRoute(\n now,\n state,\n url,\n createHrefFromUrl(canonicalUrl),\n navigationSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n map,\n debugInfo,\n // Unknown route navigations don't use route prediction - the route tree\n // came directly from the server. If a mismatch occurs during dynamic data\n // fetch, the retry handler will traverse the known route tree to mark the\n // entry as having a dynamic rewrite.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\nexport function completeHardNavigation(\n state: AppRouterState,\n url: URL,\n navigateType: 'push' | 'replace'\n): AppRouterState {\n if (isJavaScriptURLString(url.href)) {\n console.error(\n 'Next.js has blocked a javascript: URL as a security precaution.'\n )\n return state\n }\n const newState: AppRouterState = {\n canonicalUrl:\n url.origin === location.origin ? createHrefFromUrl(url) : url.href,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: true,\n preserveCustomHistoryState: false,\n },\n // TODO: None of the rest of these values are consistent with the incoming\n // navigation. We rely on the fact that AppRouter will suspend and trigger\n // a hard navigation before it accesses any of these values. But instead\n // we should trigger the hard navigation and blocking any subsequent\n // router updates without updating React.\n renderedSearch: state.renderedSearch,\n scrollRef: state.scrollRef,\n cache: state.cache,\n tree: state.tree,\n nextUrl: state.nextUrl,\n previousNextUrl: state.previousNextUrl,\n debugInfo: null,\n }\n return newState\n}\n\nexport function completeSoftNavigation(\n oldState: AppRouterState,\n url: URL,\n referringNextUrl: string | null,\n tree: FlightRouterState,\n cache: CacheNode,\n renderedSearch: string,\n canonicalUrl: string,\n navigateType: 'push' | 'replace',\n scrollBehavior: ScrollBehavior,\n scrollRef: ScrollRef | null,\n collectedDebugInfo: Array<unknown> | null\n) {\n // The \"Next-Url\" is a special representation of the URL that Next.js\n // uses to implement interception routes.\n // TODO: Get rid of this extra traversal by computing this during the\n // same traversal that computes the tree itself. We should also figure out\n // what is the minimum information needed for the server to correctly\n // intercept the route.\n const changedPath = computeChangedPath(oldState.tree, tree)\n const nextUrlForNewRoute = changedPath ? changedPath : oldState.nextUrl\n\n // This value is stored on the state as `previousNextUrl`; the naming is\n // confusing. What it represents is the \"Next-Url\" header that was used to\n // fetch the incoming route. It's essentially the refererer URL, but in a\n // Next.js specific format. During refreshes, this is sent back to the server\n // instead of the current route's \"Next-Url\" so that the same interception\n // logic is applied as during the original navigation.\n const previousNextUrl = referringNextUrl\n\n // Check if the only thing that changed was the hash fragment.\n const oldUrl = new URL(oldState.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\n // Determine whether and how the page should scroll after this\n // navigation.\n //\n // By default, we scroll to the segments that were navigated to — i.e.\n // segments in the new part of the route, as opposed to shared segments\n // that were already part of the previous route. All newly navigated\n // segments share a single ScrollRef. When they mount, the first one\n // to mount initiates the scroll. They share a ref so that only one\n // scroll happens per navigation.\n //\n // If a subsequent navigation produces new segments, those supersede\n // any pending scroll from the previous navigation by invalidating its\n // ScrollRef. If a navigation doesn't produce any new segments (e.g.\n // a refresh where the route structure didn't change), any pending\n // scrolls from previous navigations are unaffected.\n //\n // The branches below handle special cases layered on top of this\n // default model.\n let activeScrollRef: ScrollRef | null\n let forceScroll: boolean\n if (scrollBehavior === ScrollBehavior.NoScroll) {\n // The user explicitly opted out of scrolling (e.g. scroll={false}\n // on a Link or router.push).\n //\n // If this navigation created new scroll targets (scrollRef !== null),\n // neutralize them. If it didn't, any prior scroll targets carried\n // forward on the cache nodes via reuseSharedCacheNode remain active.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = oldState.scrollRef.scrollRef\n forceScroll = false\n } else if (onlyHashChange) {\n // Hash-only navigations should scroll regardless of per-node state.\n // Create a fresh ref so the first segment to scroll consumes it.\n //\n // Invalidate any scroll ref from a prior navigation that hasn't\n // been consumed yet.\n const oldScrollRef = oldState.scrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n // Also invalidate any per-node refs that were accumulated during\n // this navigation's tree construction — the hash-only ref\n // supersedes them.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = { current: true }\n forceScroll = true\n } else {\n // Default case. Use the accumulated scrollRef (may be null if no\n // new segments were created). The handler checks per-node refs, so\n // unchanged parallel route slots won't scroll.\n activeScrollRef = scrollRef\n\n // If this navigation created new scroll targets, invalidate any\n // pending scroll from a previous navigation.\n if (scrollRef !== null) {\n const oldScrollRef = oldState.scrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n }\n forceScroll = false\n }\n\n const newState: AppRouterState = {\n canonicalUrl,\n renderedSearch,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: false,\n preserveCustomHistoryState: false,\n },\n scrollRef: {\n scrollRef: activeScrollRef,\n forceScroll,\n onlyHashChange,\n hashFragment:\n // Remove leading # and decode hash to make non-latin hashes work.\n //\n // Empty hash should trigger default behavior of scrolling layout into\n // view. #top is handled in layout-router.\n //\n // Refer to `ScrollHandler` for details on how this is used.\n scrollBehavior !== ScrollBehavior.NoScroll && url.hash !== ''\n ? decodeURIComponent(url.hash.slice(1))\n : oldState.scrollRef.hashFragment,\n },\n cache,\n tree,\n nextUrl: nextUrlForNewRoute,\n previousNextUrl,\n debugInfo: collectedDebugInfo,\n }\n return newState\n}\n\nexport function completeTraverseNavigation(\n state: AppRouterState,\n url: URL,\n renderedSearch: string,\n cache: CacheNode,\n tree: FlightRouterState,\n nextUrl: string | null\n) {\n return {\n // Set canonical url\n canonicalUrl: createHrefFromUrl(url),\n renderedSearch,\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 scrollRef: state.scrollRef,\n cache,\n // Restore provided tree\n tree,\n nextUrl,\n // TODO: We need to restore previousNextUrl, too, which represents the\n // Next-Url that was used to fetch the data. Anywhere we fetch using the\n // canonical URL, there should be a corresponding Next-Url.\n previousNextUrl: null,\n debugInfo: null,\n }\n}\n\n/**\n * Instant Navigation Testing API: ensures a prefetch task has been initiated\n * and completed before proceeding with the navigation. This guarantees that\n * segment data requests are at least pending, even for routes whose route\n * tree is already cached.\n *\n * After the prefetch completes, delegates to the normal navigation flow.\n */\nasync function ensurePrefetchThenNavigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): Promise<AppRouterState> {\n const link = getLinkForCurrentNavigation()\n const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR\n\n const cacheKey = createCacheKey(url.href, nextUrl)\n\n // Create this navigation's \"wait for prefetch to fulfill\" state and schedule\n // the prefetch as a locked-navigation prefetch. The prefetch's promise\n // resolves when the task completes — after every segment response the task\n // cares about has settled — so the navigation below reads present data\n // rather than a still-in-flight entry.\n const { beginNavigationLockPrefetch } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const navigationLockPrefetch = beginNavigationLockPrefetch()\n const prefetchTask = schedulePrefetchTask(\n cacheKey,\n currentFlightRouterState,\n fetchStrategy,\n PrefetchPriority.Default,\n null, // onInvalidate\n navigationLockPrefetch\n )\n if (navigationLockPrefetch !== null) {\n await navigationLockPrefetch.promise\n }\n\n // Prefetch is complete. Proceed with the normal navigation flow, which\n // will now find the route in the cache. The navigation inherits the map of\n // the prefetch task that drives it: the task was scheduled inside the lock\n // scope, so this is the scope's private map, and the navigation reads only\n // data fetched under the lock.\n const result = await navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n prefetchTask.segmentCacheMap\n )\n\n // Only transition to captured-SPA once the navigation is known to be an SPA.\n // If the result is an MPA navigation, leave the cookie pending and let the new\n // document load transition it to captured-MPA.\n if (!result.pushRef.mpaNavigation) {\n const { updateCapturedSPAToTree } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n updateCapturedSPAToTree(currentFlightRouterState, result.tree)\n }\n\n return result\n}\n"],"names":["completeHardNavigation","completeSoftNavigation","completeTraverseNavigation","navigate","navigateToKnownRoute","state","url","currentUrl","currentRenderedSearch","currentCacheNode","currentFlightRouterState","nextUrl","freshnessPolicy","scrollBehavior","navigateType","navigationLock","process","env","__NEXT_EXPOSE_TESTING_API","isNavigationLocked","require","beginLockedNavigation","ensurePrefetchThenNavigate","navigateImpl","segmentCacheMap","map","now","Date","href","cacheKey","createCacheKey","route","readRouteCacheEntry","status","EntryStatus","Fulfilled","navigateUsingPrefetchedRouteTree","__NEXT_OPTIMISTIC_ROUTING","Rejected","optimisticRoute","deprecated_requestOptimisticRouteCacheEntry","navigateToUnknownRoute","catch","canonicalUrl","navigationSeed","debugInfo","routeCacheEntry","signal","NODE_ENV","__NEXT_CACHE_COMPONENTS","link","getLinkForCurrentNavigation","fetchStrategy","FetchStrategy","Full","routeTree","prefetchHints","PrefetchHint","SubtreeHasPartialPrefetching","SubtreeHasInstantFalse","error","createLinkPrefetchPartialError","pathname","ownerStack","undefined","console","stack","name","message","restrictToShell","shouldRestrictNavigationToShell","PPR","accumulation","separateRefreshUrls","scrollRef","isSamePageNavigation","task","startPPRNavigation","metadataVaryPath","head","dynamicStaleAt","FreshnessPolicy","Gesture","spawnDynamicRequests","node","renderedSearch","tree","hash","prefetchSeed","metadata","varyPath","isHeadPartial","headVaryParams","computeDynamicStaleAt","UnknownDynamicStaleTime","DynamicRequestTreeForEntireRoute","dynamicRequestTree","Default","HistoryTraversal","Hydration","RefreshAll","HMRRefresh","promiseForDynamicServerResponse","fetchServerResponse","flightRouterState","result","redirectUrl","URL","location","origin","transportData","couldBeIntercepted","supportsPerSegmentPrefetching","dynamicStaleTime","staticStageData","runtimePrefetchStream","responseHeaders","convertServerPatchToFullTree","discoverKnownRoute","search","createHrefFromUrl","response","staticStageResponse","isResponsePartial","resolveStaleAt","s","then","staleAt","buildId","get","NEXT_NAV_DEPLOYMENT_ID_HEADER","b","writePrerenderResponseIntoCache","t","r","processRuntimePrefetchStream","processed","writeDynamicRenderResponseIntoCache","PPRRuntime","rootVaryParamsIterable","revealAfter","isJavaScriptURLString","newState","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","cache","previousNextUrl","oldState","referringNextUrl","collectedDebugInfo","changedPath","computeChangedPath","nextUrlForNewRoute","oldUrl","onlyHashChange","activeScrollRef","forceScroll","ScrollBehavior","NoScroll","current","oldScrollRef","hashFragment","decodeURIComponent","slice","beginNavigationLockPrefetch","navigationLockPrefetch","prefetchTask","schedulePrefetchTask","PrefetchPriority","promise","updateCapturedSPAToTree"],"mappings":";;;;;;;;;;;;;;;;;;IAspBgBA,sBAAsB;eAAtBA;;IAmCAC,sBAAsB;eAAtBA;;IA0IAC,0BAA0B;eAA1BA;;IA7wBAC,QAAQ;eAARA;;IAwKAC,oBAAoB;eAApBA;;;gCAzNa;qCACO;gCAQ7B;mCAC2B;2BACY;uBAYvC;kCAC4B;0BACmB;2BAEjB;uBACW;uBACJ;oCAEb;oCACI;+BACG;yBACyB;iCAChB;sCAIxC;AAUA,SAASD,SACdE,KAAqB,EACrBC,GAAQ,EACRC,UAAe,EACfC,qBAA6B,EAC7BC,gBAAkC,EAClCC,wBAA2C,EAC3CC,OAAsB,EACtBC,eAAgC,EAChCC,cAA8B,EAC9BC,YAAgC;IAEhC,IAAIC,iBAAwC;IAE5C,oEAAoE;IACpE,0EAA0E;IAC1E,wEAAwE;IACxE,sEAAsE;IACtE,6DAA6D;IAC7D,aAAa;IACb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E,uEAAuE;IACvE,uCAAuC;IACvC,MAAM,EAAE2J,2BAA2B,EAAE,GACnClJ,QAAQ;IACV,MAAMmJ,yBAAyBD;IAC/B,MAAME,eAAeC,IAAAA,+BAAoB,EACvC5I,UACAnB,0BACA0C,eACAsH,uBAAgB,CAACzE,OAAO,EACxB,MACAsE;IAEF,IAAIA,2BAA2B,MAAM;QACnC,MAAMA,uBAAuBI,OAAO;IACtC;IAEA,uEAAuE;IACvE,2EAA2E;IAC3E,2EAA2E;IAC3E,2EAA2E;IAC3E,+BAA+B;IAC/B,MAAMlE,SAAS,MAAMlF,aACnBlB,OACAC,KACAC,YACAC,uBACAC,kBACAC,0BACAC,SACAC,iBACAC,gBACAC,cACAC,gBACAyJ,aAAahJ,eAAe;IAG9B,6EAA6E;IAC7E,+EAA+E;IAC/E,+CAA+C;IAC/C,IAAI,CAACiF,OAAOsC,OAAO,CAACE,aAAa,EAAE;QACjC,MAAM,EAAE2B,uBAAuB,EAAE,GAC/BxJ,QAAQ;QACVwJ,wBAAwBlK,0BAA0B+F,OAAOnB,IAAI;IAC/D;IAEA,OAAOmB;AACT","ignoreList":[0]} |
| import type { FlightRouterState } from '../../../shared/lib/app-router-types'; | ||
| import { EntryStatus } from './cache'; | ||
| import { EntryStatus, type SegmentCacheEntry } from './cache'; | ||
| import type { RouteCacheKey } from './cache-key'; | ||
| import { FetchStrategy, type PrefetchTaskFetchStrategy, PrefetchPriority } from './types'; | ||
| import type { CacheMap } from './cache-map'; | ||
| import type { NavigationLockPrefetch } from './navigation-testing-lock'; | ||
@@ -24,2 +25,13 @@ import type { SegmentRequestKey } from '../../../shared/lib/segment-cache/segment-value-encoding'; | ||
| /** | ||
| * The segment cache map this task operates in, captured when the task was | ||
| * scheduled. Every segment read the task performs and every write its | ||
| * responses perform target this map. Almost always the shared map; a task | ||
| * scheduled while the Instant Navigation Testing lock is held gets the | ||
| * lock scope's private map instead. Binding the map to the task means | ||
| * tasks queued before a lock scope never leak entries into (or read out | ||
| * of) the scope's map, and a scope task's late responses never leak into | ||
| * the shared map. See `segmentCacheMap` in cache.ts. | ||
| */ | ||
| segmentCacheMap: CacheMap<SegmentCacheEntry>; | ||
| /** | ||
| * Whether to prefetch dynamic data, in addition to static data. This is | ||
@@ -127,5 +139,4 @@ * used by `<Link prefetch={true}>`. | ||
| * a locked navigation (the `ensurePrefetchThenNavigate` path). Holds that | ||
| * navigation's "wait for prefetch to fulfill" state: each spawned pending entry | ||
| * is tracked against it (see `upgradeToPendingSegment`), and the scheduler | ||
| * signals it when done spawning. See navigation-testing-lock.ts. | ||
| * navigation's "wait for prefetch to fulfill" state, resolved when the task | ||
| * completes. See navigation-testing-lock.ts. | ||
| */ | ||
@@ -132,0 +143,0 @@ _navigationLockPrefetch?: NavigationLockPrefetch | null; |
@@ -63,3 +63,3 @@ /* global location */ // imports polyfill from `@next/polyfill-module` after build. | ||
| const _isnextroutererror = require("./components/is-next-router-error"); | ||
| const version = "16.3.1-canary.10"; | ||
| const version = "16.3.1-canary.11"; | ||
| let router; | ||
@@ -66,0 +66,0 @@ const emitter = (0, _mitt.default)(); |
@@ -50,3 +50,3 @@ --- | ||
| A cache directive gives a result a lifetime, information Next.js uses to apply rendering optimizations. See [Prerendering](#prerendering) for how cached results become part of the static shell and may be included in a [prefetch](#runtime-prefetching). | ||
| A cache directive gives a result a lifetime, information Next.js uses to apply rendering optimizations. See [Prerendering](#prerendering) for how cached results become part of the static shell and may be included in a [prefetch](#prefetching). | ||
@@ -201,3 +201,3 @@ > **Good to know:** We recommend pairing every cache directive with a [`cacheLife`](/docs/app/api-reference/functions/cacheLife). Without one, the implicit `default` profile applies. | ||
| Runtime-dependent data can still be given a cache lifetime with [`"use cache: private"`](/docs/app/api-reference/directives/use-cache-private), another variant that ships with Cache Components. It gives a lifetime to a function that reads cookies, headers, or `searchParams` directly, so it can be included in a [prefetch](#runtime-prefetching). | ||
| Runtime-dependent data can still be given a cache lifetime with [`"use cache: private"`](/docs/app/api-reference/directives/use-cache-private), another variant that ships with Cache Components. It gives a lifetime to a function that reads cookies, headers, or `searchParams` directly, so it can be included in a [prefetch](#prefetching). | ||
@@ -241,3 +241,3 @@ The following section shows an alternative to `use cache: private`: extracting a runtime value and passing it to a shared cached function. | ||
| With this pattern, [runtime prefetching](#runtime-prefetching) can prerender `<CachedContent />` with the user's actual session during a client transition and have the result ready before the click. This works even when server-side entries rarely survive between requests, because the lifetime you assign is what lets the result join the prefetch, where the client treats it as fresh for its [`cacheLife`](/docs/app/api-reference/functions/cacheLife) `stale` window. | ||
| With this pattern, [prefetching](#prefetching) can prerender `<CachedContent />` with the user's actual session during a client transition and have the result ready before the click. This works even when server-side entries rarely survive between requests, because the lifetime you assign is what lets the result join the prefetch, where the client treats it as fresh for its [`cacheLife`](/docs/app/api-reference/functions/cacheLife) `stale` window. | ||
@@ -475,3 +475,3 @@ ## Static, cached, and streaming | ||
| The deeper your async work sits in the tree, the more of the page can be prerendered. This is the structural pattern Cache Components rewards: a general practice worth applying everywhere, and the foundation for the instant navigation and runtime prefetching that follow. It applies to all [runtime APIs](#working-with-runtime-apis) and async operations like data fetches. | ||
| The deeper your async work sits in the tree, the more of the page can be prerendered. This is the structural pattern Cache Components rewards: a general practice worth applying everywhere, and the foundation for the instant navigation and prefetching that follow. It applies to all [runtime APIs](#working-with-runtime-apis) and async operations like data fetches. | ||
@@ -538,13 +538,13 @@ Consider a layout that destructures `params` at the top level: | ||
| ### Runtime prefetching | ||
| ### Prefetching | ||
| With [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching) enabled, the router prefetches each route's [App Shell](/docs/app/glossary#app-shell) by default, which already includes static content and the session data derived from `cookies()` and `headers()`. Runtime prefetching extends the prefetch with **URL data**: the `searchParams` and dynamic `params` that vary per destination link. | ||
| With [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching) enabled, the router prefetches each route's [App Shell](/docs/app/glossary#app-shell) by default. The App Shell includes static content and session data derived from `cookies()` and `headers()`. To also prefetch cached content that depends on a link's **URL data**, such as `searchParams` or dynamic `params`, set `prefetch={true}` on that link. | ||
| With [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch) pointing at a [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching) route, Next.js renders that route's component tree again at prefetch time, this time with the destination URL resolved. The same rules apply, but more of the tree resolves now that its `searchParams` and `params` are in scope: | ||
| - [`use cache`](#usage) called with values extracted from runtime APIs (passed as arguments) joins the runtime prerender | ||
| - [`use cache: private`](/docs/app/api-reference/directives/use-cache-private) executes on the server, reads runtime data directly, and caches the result in the browser, joining the runtime prerender | ||
| - [`<Suspense>`](#streaming-uncached-data) fallbacks stay in the runtime prerender while uncached content streams at request time | ||
| - [`use cache`](#usage) called with values extracted from runtime APIs (passed as arguments) joins the per-link prefetch | ||
| - [`use cache: private`](/docs/app/api-reference/directives/use-cache-private) executes on the server, reads runtime data directly, and caches the result in the browser as part of the per-link prefetch | ||
| - [`<Suspense>`](#streaming-uncached-data) fallbacks stay in the prefetched UI while uncached content streams at request time | ||
| This generates a **runtime prerender** that extends past the static shell with content the destination URL unlocks. Because it happens during the prefetch, the navigation has nothing to wait on. The cost is a server invocation per prefetchable link. | ||
| This per-link prefetch includes cached content that resolves after the destination URL is known. It costs a server invocation per prefetchable link. | ||
@@ -590,3 +590,3 @@ For example, take a search page that reads `searchParams` from the URL: | ||
| See the [Runtime prefetching guide](/docs/app/guides/runtime-prefetching) for full patterns and the [`prefetch` reference](/docs/app/api-reference/file-conventions/route-segment-config/prefetch) for all modes. | ||
| See the [Optimizing prefetching guide](/docs/app/guides/optimizing-prefetching) for full patterns and the [`prefetch` reference](/docs/app/api-reference/file-conventions/route-segment-config/prefetch) for all modes. | ||
@@ -599,3 +599,3 @@ ## Where cached content is stored | ||
| - **Shared store.** By default the result stays in a per-instance, in-memory store that is ephemeral on serverless. [`use cache: remote`](/docs/app/api-reference/directives/use-cache-remote) moves it to a durable [cache handler](/docs/app/api-reference/config/next-config-js/cacheHandlers) shared across instances, a network roundtrip that pays off only at a **high hit rate**. | ||
| - **Browser.** The payload is included in the RSC sent for a client navigation or [prefetch](#runtime-prefetching), where the browser keeps it fresh for its [`stale`](/docs/app/api-reference/functions/cacheLife#stale) window. [`use cache: private`](/docs/app/api-reference/directives/use-cache-private) results live only here. | ||
| - **Browser.** The payload is included in the RSC sent for a client navigation or [prefetch](#prefetching), where the browser keeps it fresh for its [`stale`](/docs/app/api-reference/functions/cacheLife#stale) window. [`use cache: private`](/docs/app/api-reference/directives/use-cache-private) results live only here. | ||
@@ -602,0 +602,0 @@ > **Good to know:** An [App Shell](/docs/app/glossary#app-shell) that reads `cookies()` or `headers()` is session-specific, cached per session on the client rather than in the shared server cache. |
@@ -10,3 +10,3 @@ --- | ||
| - app/guides/instant-navigation | ||
| - app/guides/runtime-prefetching | ||
| - app/guides/optimizing-prefetching | ||
| - app/api-reference/config/next-config-js/partialPrefetching | ||
@@ -18,3 +18,3 @@ - app/api-reference/file-conventions/route-segment-config/prefetch | ||
| To prefetch more than the App Shell, a link can opt into [runtime prefetching](/docs/app/guides/runtime-prefetching) with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch). The prefetch then also resolves the per-link runtime data (`params`, `searchParams`, and the full URL) and the cached content behind it. | ||
| To prefetch more than the App Shell, a link can opt into [per-link prefetching](/docs/app/guides/optimizing-prefetching) with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch). The prefetch then also resolves URL-specific content that depends on `params`, `searchParams`, or the full URL. | ||
@@ -70,7 +70,7 @@ Along the way, Next.js surfaces [instant navigation](/docs/app/guides/instant-navigation) insights in development, naming the link or route to change. | ||
| | `<Link>` prop | Before (Cache Components default) | After Partial Prefetching | | ||
| | ----------------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | ||
| | `<Link href="/x">` | Prefetched the cached page render. | Loads the shared App Shell for `/x`. | | ||
| | `<Link href="/x" prefetch>` | Prefetched the cached page render **and** any dynamic content. | Loads the App Shell, plus per-link runtime data through [runtime prefetching](/docs/app/guides/runtime-prefetching) when `/x` reads it. | | ||
| | `<Link href="/x" prefetch={false}>` | Disabled prefetching for this link. | Unchanged. Still disabled. | | ||
| | `<Link>` prop | Before (Cache Components default) | After Partial Prefetching | | ||
| | ----------------------------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | ||
| | `<Link href="/x">` | Prefetched the cached page render. | Loads the shared App Shell for `/x`. | | ||
| | `<Link href="/x" prefetch>` | Prefetched the cached page render **and** any dynamic content. | Loads the App Shell, plus URL-specific content through [per-link prefetching](/docs/app/guides/optimizing-prefetching) when `/x` reads it. | | ||
| | `<Link href="/x" prefetch={false}>` | Disabled prefetching for this link. | Unchanged. Still disabled. | | ||
@@ -85,9 +85,9 @@ The App Shell is shared across every link to a given route, regardless of dynamic params, so rendering many `<Link>`s to the same destination doesn't multiply the work. | ||
| | Destination | Recommendation | | ||
| | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | | ||
| | [Fully static, or content already cached](#static-or-cached-content) | Remove the now-redundant `prefetch={true}`. | | ||
| | [Delivered uncached content you want kept ahead of the click](#uncached-content) | Cache it with `use cache`, then remove `prefetch={true}`. | | ||
| | [Delivered content that depends on `cookies()` or `headers()`](#session-content) | Cache the lookup behind the session value, then remove `prefetch={true}`. | | ||
| | [Reads URL data, or has cached content that depends on it](#url-data) | Keep `prefetch={true}`, and prefetch the content later with runtime prefetching. | | ||
| | [Delivers real-time content that must stay fresh per request](#real-time-content) | Remove `prefetch={true}` and let the content stream in. | | ||
| | Destination | Recommendation | | ||
| | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | | ||
| | [Fully static, or content already cached](#static-or-cached-content) | Remove the now-redundant `prefetch={true}`. | | ||
| | [Delivered uncached content you want kept ahead of the click](#uncached-content) | Cache it with `use cache`, then remove `prefetch={true}`. | | ||
| | [Delivered content that depends on `cookies()` or `headers()`](#session-content) | Cache the lookup behind the session value, then remove `prefetch={true}`. | | ||
| | [Reads URL data, or has cached content that depends on it](#url-data) | Keep `prefetch={true}` to resolve the content ahead of the click. | | ||
| | [Delivers real-time content that must stay fresh per request](#real-time-content) | Remove `prefetch={true}` and let the content stream in. | | ||
@@ -155,3 +155,3 @@ ### Static or cached content | ||
| Content behind [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers) varies per session, not per link, and [session data resolves in the App Shell](/docs/app/guides/runtime-prefetching#session-data-resolves-in-the-shell), so cached session content still gets included. Read the session value outside the cached function and pass it in, then remove `prefetch={true}` from the links: | ||
| Content behind [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers) varies per session, not per link, and [session data resolves in the App Shell](/docs/app/guides/optimizing-prefetching#include-session-data-in-the-shell), so cached session content still gets included. Read the session value outside the cached function and pass it in, then remove `prefetch={true}` from the links: | ||
@@ -445,3 +445,3 @@ ```tsx filename="app/dashboard/page.tsx" switcher | ||
| Content that depends on [URL data](/docs/app/glossary#url-data) (`params`, `searchParams`) can't be included in the shared App Shell, so it streams in after navigation. [Runtime prefetching](/docs/app/guides/runtime-prefetching) resolves it ahead of the click for links with `prefetch={true}`, at the cost of a server invocation per prefetchable link. To make the content resolvable at prefetch time, cache it behind the read with [`use cache`](/docs/app/api-reference/directives/use-cache). For a search page that reads `searchParams`: | ||
| Content that depends on [URL data](/docs/app/glossary#url-data) (`params`, `searchParams`) can't be included in the shared App Shell, so it streams in after navigation. [Per-link prefetching](/docs/app/guides/optimizing-prefetching) resolves it ahead of the click for links with `prefetch={true}`, at the cost of a server invocation per prefetchable link. To make the content resolvable at prefetch time, cache it behind the read with [`use cache`](/docs/app/api-reference/directives/use-cache). For a search page that reads `searchParams`: | ||
@@ -546,2 +546,2 @@ ```tsx filename="app/search/page.tsx" switcher | ||
| The [runtime prefetching guide](/docs/app/guides/runtime-prefetching) covers when the cost pays off and the caching patterns behind runtime reads. | ||
| The [Optimizing prefetching guide](/docs/app/guides/optimizing-prefetching) covers when the cost pays off and the caching patterns behind runtime reads. |
@@ -12,3 +12,3 @@ --- | ||
| - app/getting-started/fetching-data | ||
| - app/guides/runtime-prefetching | ||
| - app/guides/optimizing-prefetching | ||
| - app/api-reference/directives/use-cache-private | ||
@@ -300,3 +300,3 @@ - app/api-reference/functions/cacheTag | ||
| - If you tune the lifetime with [`cacheLife`](/docs/app/api-reference/functions/cacheLife), keep `stale` at 30 seconds or more. Below that, the scope drops out of prefetching. See [`cacheLife` client cache behavior](/docs/app/api-reference/functions/cacheLife#client-cache-behavior). | ||
| - A route that _also_ depends on the URL (a `params` or `searchParams` value) needs [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch) on the links pointing at it. That opts into [runtime prefetching](/docs/app/guides/runtime-prefetching), which resolves the per-link data ahead of the click. | ||
| - A route that _also_ depends on the URL (a `params` or `searchParams` value) needs [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch) on the links pointing at it. That opts into [per-link prefetching](/docs/app/guides/optimizing-prefetching), which resolves the per-link data ahead of the click. | ||
@@ -309,3 +309,3 @@ ```tsx filename="app/page.tsx" | ||
| The destination needs [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for this, so enable the [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) flag or set `prefetch = 'partial'` on the segment. Add the prop where the wait is worth it: a runtime prefetch costs one server invocation per link, so a sidebar of `/chat/[id]` links pays that cost per item. | ||
| The destination needs [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for this, so enable the [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) flag or set `prefetch = 'partial'` on the segment. Add the prop where the wait is worth it: that prefetch costs one server invocation per link, so a sidebar of `/chat/[id]` links pays that cost per item. | ||
@@ -312,0 +312,0 @@ ## Common pitfalls |
@@ -58,3 +58,3 @@ --- | ||
| For new projects, we recommend creating a dedicated **Data Access Layer (DAL)**. This is a internal library that controls how and when data is fetched, and what gets passed to your render context. | ||
| For new projects, we recommend creating a dedicated **Data Access Layer (DAL)**. This is an internal library that controls how and when data is fetched, and what gets passed to your render context. | ||
@@ -61,0 +61,0 @@ A Data Access Layer should: |
@@ -10,3 +10,3 @@ --- | ||
| - app/api-reference/file-conventions/route-segment-config/instant | ||
| - app/guides/runtime-prefetching | ||
| - app/guides/optimizing-prefetching | ||
| - app/getting-started/caching | ||
@@ -40,3 +40,3 @@ - app/getting-started/revalidating | ||
| Runtime prefetching extends the static shell with a link's URL data (`searchParams` and `params`) by invoking the route at prefetch time. Ensuring navigations are instant is the foundation: a route that doesn't navigate instantly without runtime prefetching won't navigate instantly with it either. See [Runtime prefetching](/docs/app/guides/runtime-prefetching) for the patterns. | ||
| With `prefetch={true}`, per-link prefetching resolves a link's URL data (`searchParams` and `params`) before navigation. First make the route instant with its App Shell. Per-link prefetching cannot fix a route that blocks without it. See [Optimizing prefetching](/docs/app/guides/optimizing-prefetching) for the patterns. | ||
@@ -83,13 +83,13 @@ ## Quick start | ||
| > **Good to know:** [`"use cache: private"`](/docs/app/api-reference/directives/use-cache-private) is a variant for caching functions that read runtime APIs like `cookies()` and `headers()`. The result is cached in the browser only, not on the server. **It can't be part of the static shell.** See [`"use cache: private"`](/docs/app/guides/runtime-prefetching#use-cache-private) in the runtime prefetching guide for how it pairs with prefetching. | ||
| > **Good to know:** [`"use cache: private"`](/docs/app/api-reference/directives/use-cache-private) is a variant for caching functions that read runtime APIs like `cookies()` and `headers()`. The result is cached in the browser only, not on the server. **It can't be part of the static shell.** See [`"use cache: private"`](/docs/app/guides/optimizing-prefetching#use-cache-private) in the Optimizing prefetching guide for how it pairs with prefetching. | ||
| **`<Suspense>`** declares fallback UI for parts of the tree that read uncached data or runtime APIs like `cookies()` and `headers()`; the content streams into the fallback when it resolves. | ||
| > **Good to know:** A fallback may access `cookies()`, `headers()`, or the full URL. At build time, the fallback itself suspends, and a `<Suspense>` boundary further up the tree is needed. With [runtime prefetching](/docs/app/guides/runtime-prefetching), the information is available and such a fallback becomes part of the instant UI. Cached values like timestamps or data fetches can sit directly inside the fallback. | ||
| > **Good to know:** A fallback may access `cookies()`, `headers()`, or the full URL. At build time, the fallback itself suspends, and a `<Suspense>` boundary further up the tree is needed. For a link with `prefetch={true}`, [per-link prefetching](/docs/app/guides/optimizing-prefetching) makes URL data available before navigation, so the fallback can become part of the prefetched UI. Cached values like timestamps or data fetches can sit directly inside the fallback. | ||
| Next.js can also generate an [**App Shell**](/docs/app/glossary#app-shell) per route: a fallback that renders instantly during client navigations when nothing else is ready. [Runtime prefetching](/docs/app/guides/runtime-prefetching) builds on it, resolving a link's URL data on top. | ||
| Next.js can also generate an [**App Shell**](/docs/app/glossary#app-shell) per route, which renders during client navigations while remaining content streams. Partial Prefetching uses the App Shell as the default `<Link>` prefetch. A link with `prefetch={true}` can also resolve cached content that depends on that link's URL data. | ||
| ### Tune what `<Link>` prefetches | ||
| ### Prefetch URL data for a link | ||
| Under [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching), each visible `<Link>` prefetches the destination's App Shell by default. The shell is shared across every link to the same route, so rendering a `<Link>` is effectively free. | ||
| Under [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching), each visible `<Link>` prefetches the destination's App Shell by default. Links to the same route share one App Shell instead of triggering a separate App Shell request for each link. | ||
@@ -104,3 +104,3 @@ To prefetch the page content alongside the shell for a specific link, set [`prefetch={true}`](/docs/app/api-reference/components/link#prefetch): | ||
| With Partial Prefetching enabled, `prefetch={true}` also opts the link into [runtime prefetching](/docs/app/guides/runtime-prefetching), which resolves the per-link URL data (`params`, `searchParams`, the full URL) ahead of the click. | ||
| With Partial Prefetching enabled, `prefetch={true}` also opts the link into [per-link prefetching](/docs/app/guides/optimizing-prefetching), which resolves the per-link URL data (`params`, `searchParams`, the full URL) ahead of the click. | ||
@@ -339,3 +339,3 @@ ### Validate instant navigation | ||
| - **Initial page load**: Use `page.goto()` to test the static UI from the document response. | ||
| - **Client navigation**: Click a `<Link>` to test the destination's prefetched UI. [Runtime prefetching](/docs/app/guides/runtime-prefetching) can add request-specific content to this UI. | ||
| - **Client navigation**: Click a `<Link>` to test the destination's prefetched UI. [Per-link prefetching](/docs/app/guides/optimizing-prefetching) can add request-specific content to this UI. | ||
@@ -547,3 +547,3 @@ ```typescript filename="e2e/navigation.test.ts" highlight={6-14,20-25} | ||
| - **Cache**: pair `'use cache'` with [`cacheLife`](/docs/app/api-reference/functions/cacheLife) to assign a freshness profile. | ||
| - **Runtime prefetching** (nav-only): when a route reads URL data (`searchParams` or `params`), opt it into [runtime prefetching](/docs/app/guides/runtime-prefetching) so the framework resolves that data at link-prefetch time. Session data from `cookies()` or `headers()` already lands in the App Shell without it. | ||
| - **Per-link prefetching** (nav-only): when a route reads URL data (`searchParams` or `params`), opt it into [per-link prefetching](/docs/app/guides/optimizing-prefetching) so the framework resolves that data at link-prefetch time. Session data from `cookies()` or `headers()` already lands in the App Shell without it. | ||
@@ -588,4 +588,4 @@ Each refactor should pair with a before/after capture to verify the change actually landed. Identical-looking captures mean the refactor didn't take effect. | ||
| - [`instant` API reference](/docs/app/api-reference/file-conventions/route-segment-config/instant) for the full configuration | ||
| - [Runtime prefetching](/docs/app/guides/runtime-prefetching) when parts of your route depend on URL data (`searchParams` or `params`) and you want it in the shell | ||
| - [Optimizing prefetching](/docs/app/guides/optimizing-prefetching) when parts of your route depend on URL data (`searchParams` or `params`) and should resolve before navigation | ||
| - [Caching](/docs/app/getting-started/caching) for background on `use cache`, Suspense, and Partial Prerendering | ||
| - [Revalidating](/docs/app/getting-started/revalidating) for how to expire cached data with `cacheLife` and `updateTag` |
@@ -741,3 +741,3 @@ --- | ||
| Under [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) (Next.js 16.3 and later), `<Link>` prefetches the destination's [App Shell](/docs/app/glossary#app-shell): the route output that is shared across links for the current user. The shell does not include [URL data](/docs/app/glossary#url-data), because `params` and `searchParams` are link-specific. Opt the link into [runtime prefetching](/docs/app/guides/runtime-prefetching) with `prefetch={true}` to resolve that URL data ahead of the click: | ||
| Under [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) (Next.js 16.3 and later), `<Link>` prefetches the destination's [App Shell](/docs/app/glossary#app-shell): the route output that is shared across links for the current user. The shell does not include [URL data](/docs/app/glossary#url-data), because `params` and `searchParams` are link-specific. Opt the link into [per-link prefetching](/docs/app/guides/optimizing-prefetching) with `prefetch={true}` to resolve that URL data ahead of the click: | ||
@@ -750,3 +750,3 @@ ```tsx filename="features/task/components/task-card.tsx" | ||
| Runtime prefetching is most valuable when the destination has URL-specific work that users are likely to need next. Cached reads make the prefetched output reusable and tag-invalidatable in the [Client Cache](/docs/app/glossary#client-cache); dynamic reads can still resolve before the click, but each prefetch can do real server work. In the companion app, the task cards prefetch the detail page as they scroll into view, so it paints instantly by the time the user clicks. | ||
| Per-link prefetching is most valuable when the destination has URL-specific work that users are likely to need next. Cached reads make the prefetched output reusable and tag-invalidatable in the [Client Cache](/docs/app/glossary#client-cache); dynamic reads can still resolve before the click, but each prefetch can do real server work. In the companion app, the task cards prefetch the detail page as they scroll into view, so it paints instantly by the time the user clicks. | ||
@@ -765,3 +765,3 @@ ## Next steps | ||
| | Reusable reads should survive across requests and stay fresh after writes | [`'use cache'`](/docs/app/api-reference/directives/use-cache) with [`cacheTag`](/docs/app/api-reference/functions/cacheTag), revalidated by [`updateTag`](/docs/app/api-reference/functions/updateTag) or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) | | ||
| | Navigation between pages of an interactive app should feel instant | [`<Link>`](/docs/app/api-reference/components/link) prefetching with [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching), and [Runtime prefetching](/docs/app/guides/runtime-prefetching) via `prefetch={true}` for content that depends on URL data | | ||
| | Navigation between pages of an interactive app should feel instant | [`<Link>`](/docs/app/api-reference/components/link) prefetching with [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching), and [per-link prefetching](/docs/app/guides/optimizing-prefetching) via `prefetch={true}` for content that depends on URL data | | ||
@@ -768,0 +768,0 @@ Most patterns mix two or more of these. Reach for whichever primitive fits the constraint you're solving. |
@@ -77,3 +77,3 @@ --- | ||
| By default, `next/mdx` only compiles files with the `.mdx` extension. To handle `.md` files with webpack, update the `extension` option: | ||
| By default, `@next/mdx` only compiles files with the `.mdx` extension. To handle `.md` files with webpack, update the `extension` option: | ||
@@ -80,0 +80,0 @@ ```js filename="next.config.mjs" |
@@ -358,3 +358,3 @@ --- | ||
| Next, we’ll embed your CRA’s root App component inside a [Client Component](/docs/app/getting-started/server-and-client-components) so that all logic remains client-side. If this is your first time using Next.js, it's worth knowing that clients components (by default) are still prerendered on the server. You can think about them as having the additional capability of running client-side JavaScript. | ||
| Next, we’ll embed your CRA’s root App component inside a [Client Component](/docs/app/getting-started/server-and-client-components) so that all logic remains client-side. If this is your first time using Next.js, it's worth knowing that Client Components (by default) are still prerendered on the server. You can think about them as having the additional capability of running client-side JavaScript. | ||
@@ -361,0 +361,0 @@ Create a `client.tsx` (or `client.js`) in `app/[[...slug]]/`: |
@@ -310,3 +310,3 @@ --- | ||
| If the route also prefetches its per-link URL data ahead of the click, `/chats/42` renders its messages from that prefetch immediately, even offline, instead of waiting for the connection to return. See [runtime prefetching](/docs/app/guides/runtime-prefetching) to learn more. | ||
| If the route also prefetches its per-link URL data ahead of the click, `/chats/42` renders its messages from that prefetch immediately, even offline, instead of waiting for the connection to return. See [Optimizing prefetching](/docs/app/guides/optimizing-prefetching) to learn more. | ||
@@ -313,0 +313,0 @@ ## Retry Server Actions after the network returns |
@@ -88,6 +88,6 @@ --- | ||
| - **One shell per route, shared across links.** `<Link>` prefetches the route's App Shell, which holds its static and session output. Any number of links to the same route reuse that one shell, fetched once as the first link enters the viewport, so a page with many links makes fewer prefetch requests than prefetching each route in full. | ||
| - **The rest streams in.** Uncached data streams in after navigation, behind the shell's `<Suspense>` boundaries. A link can also resolve its URL data (`searchParams`, `params`) at prefetch time with [`prefetch={true}`](/docs/app/guides/runtime-prefetching). | ||
| - **The rest streams in.** Uncached data streams in after navigation, behind the shell's `<Suspense>` boundaries. A link can also resolve its URL data (`searchParams`, `params`) at prefetch time with [`prefetch={true}`](/docs/app/guides/optimizing-prefetching). | ||
| - **Invalidations refresh prefetches.** Data invalidations (`revalidateTag`, `revalidatePath`) silently refresh associated prefetches. | ||
| See [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the behavior change and the recommended adoption path. | ||
| See [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the behavior change and the recommended adoption path. See [Optimizing prefetching](/docs/app/guides/optimizing-prefetching) to resolve cached URL-specific content before navigation with `prefetch={true}`. | ||
@@ -94,0 +94,0 @@ ## Controlling prefetching |
@@ -154,3 +154,3 @@ --- | ||
| > **Good to know**: The `stale` time must be at least 30 seconds for runtime prefetching to work, and at least 5 minutes for the content to be included in the route's [App Shell](/docs/app/glossary#app-shell). See [`cacheLife` prerendering behavior](/docs/app/api-reference/functions/cacheLife#prerendering-behavior) for details. | ||
| > **Good to know**: The `stale` time must be at least 30 seconds for per-link prefetching to work, and at least 5 minutes for the content to be included in the route's [App Shell](/docs/app/glossary#app-shell). See [`cacheLife` prerendering behavior](/docs/app/api-reference/functions/cacheLife#prerendering-behavior) for details. | ||
@@ -157,0 +157,0 @@ ## Request APIs allowed in private caches |
@@ -303,3 +303,3 @@ --- | ||
| - **`"auto"` or `null` (default)**: Prefetch behavior depends on whether the route is static or dynamic. For static routes, the full route will be prefetched (including all its data). For dynamic routes, the partial route down to the nearest segment with a [`loading.js`](/docs/app/api-reference/file-conventions/loading#instant-loading-states) boundary will be prefetched. | ||
| - **`true`**: The full route is prefetched for both static and dynamic routes. With [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) enabled, the prefetch is the [App Shell](/docs/app/glossary#app-shell) plus the per-link runtime data and the cached content behind it. See [Runtime prefetching](/docs/app/guides/runtime-prefetching). | ||
| - **`true`**: The full route is prefetched for both static and dynamic routes. With [Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) enabled, the prefetch includes the [App Shell](/docs/app/glossary#app-shell) and cached content that depends on the link's URL data. See [Optimizing prefetching](/docs/app/guides/optimizing-prefetching). | ||
| - `false`: Prefetching will never happen both on entering the viewport and on hover. | ||
@@ -337,3 +337,3 @@ | ||
| Prefetching happens when a `<Link />` component enters the user's viewport (initially or through scroll). Next.js prefetches and loads the linked route (denoted by the `href`) and data in the background to improve the performance of client-side navigation's. **Prefetching is only enabled in production**. | ||
| Prefetching happens when a `<Link />` component enters the user's viewport (initially or through scroll). Next.js prefetches and loads the linked route (denoted by the `href`) and data in the background to improve the performance of client-side navigation. **Prefetching is only enabled in production**. | ||
@@ -340,0 +340,0 @@ The following values can be passed to the `prefetch` prop: |
@@ -42,7 +42,7 @@ --- | ||
| For links that opt into a wider prefetch with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch), Next.js may also prefetch the segment at runtime. The server renders a fresh response that resolves per-link runtime data (`params`, `searchParams`, and the full URL). On pages where all the content is statically renderable, Next.js serves prefetches from the static cache. If a page accesses non-static data, it's prefetched at runtime. | ||
| For links that opt into a wider prefetch with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch), Next.js uses per-link prefetching. The server renders a fresh response that resolves URL data (`params`, `searchParams`, and the full URL). On pages where all the content is statically renderable, Next.js serves prefetches from the static cache. If a page accesses non-static data, it's prefetched at runtime. | ||
| Use this for incremental adoption when you can't enable `partialPrefetching` for the entire app at once. Once every route in scope has `prefetch = 'partial'`, enable the global flag and remove the per-route exports. | ||
| > **Good to know**: When Next.js runtime-prefetches a segment, all downstream segments are included in the same runtime prefetch request. Segments deeper in the tree that are configured with `'force-disabled'` will still be prefetched as part of the runtime response. | ||
| > **Good to know**: When Next.js performs a per-link prefetch for a segment, all downstream segments are included in the same request. Segments deeper in the tree that are configured with `'force-disabled'` will still be prefetched as part of the response. | ||
@@ -65,3 +65,3 @@ ```tsx filename="page.tsx" | ||
| - [`'partial'`](#partial): App Shell for default links; a `<Link prefetch={true}>` additionally resolves per-link runtime data (`params`, `searchParams`, the full URL). | ||
| - [`'partial'`](#partial): App Shell for default links; a `<Link prefetch={true}>` additionally resolves URL data (`params`, `searchParams`, and the full URL) and the cached content behind it. | ||
| - [`'force-disabled'`](#force-disabled): skip segment data entirely. | ||
@@ -68,0 +68,0 @@ |
@@ -11,6 +11,6 @@ --- | ||
| - app/api-reference/components/link | ||
| - app/guides/runtime-prefetching | ||
| - app/guides/optimizing-prefetching | ||
| --- | ||
| `partialPrefetching` enables Partial Prefetching at the app level. The framework prefetches the static parts of each route by default; opt individual routes into [runtime prefetching](/docs/app/guides/runtime-prefetching) to fetch more. | ||
| `partialPrefetching` enables Partial Prefetching at the app level. The framework prefetches the static parts of each route by default; set `prefetch={true}` on individual links to use [per-link prefetching](/docs/app/guides/optimizing-prefetching) and fetch more. | ||
@@ -50,3 +50,3 @@ ## Usage | ||
| With `partialPrefetching: true`, Next.js prefetches one reusable [App Shell](/docs/app/glossary#app-shell) per route instead. The shell carries the route's rendered output minus per-link data; specifics like params and search-bound data fill in after navigation. Shells are cached on the client, so a route is fetched once even if many links on the page point at it. | ||
| With `partialPrefetching: true`, Next.js prefetches one reusable [App Shell](/docs/app/glossary#app-shell) per route instead. The App Shell contains rendered output that does not depend on a link's URL. URL-specific content, including content that depends on `params` or `searchParams`, resolves after navigation by default. App Shells are cached on the client, so links to the same route reuse one prefetch. | ||
@@ -57,3 +57,3 @@ The pattern is similar to per-route code splitting in single-page apps: one artifact per route, shared by every link that points to it. | ||
| A link can ask for more than the App Shell with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch). The prefetch also resolves per-link runtime data like `params`, `searchParams`, and the full URL. See [Runtime prefetching](/docs/app/guides/runtime-prefetching). | ||
| A link can ask for more than the App Shell with [`<Link prefetch={true}>`](/docs/app/api-reference/components/link#prefetch). The prefetch also resolves URL data like `params`, `searchParams`, and the full URL, and the cached content behind it. See [Optimizing prefetching](/docs/app/guides/optimizing-prefetching). | ||
@@ -60,0 +60,0 @@ > **Good to know**: If you use `<Link prefetch={true}>` to a route that hasn't opted into Partial Prefetching, a dev console error suggests enabling `partialPrefetching` app-wide or `prefetch = 'partial'` on the segment. The [dev warning Insight](/docs/messages/instant-link-prefetch-partial) covers each fix in detail. |
@@ -145,3 +145,3 @@ --- | ||
| To create a new app using any public GitHub example, use the `--example` option with the GitHub repo's URL. For example: | ||
| To create a new app using any public GitHub example, use the `--example` option with the GitHub repository's URL. For example: | ||
@@ -148,0 +148,0 @@ ```bash package="pnpm" |
@@ -15,3 +15,3 @@ --- | ||
| A per-route prerender containing the parts of a page that don't depend on URL data. Cached content is included when its [`stale`](/docs/app/api-reference/functions/cacheLife#stale) time is at least 5 minutes, since the shell is reused for longer than shorter-lived content stays fresh. Routes that read `cookies()` or `headers()` produce one that also includes session data, cached per session on the client. Used as the prefetch payload during client navigations, the loading state during [runtime prefetching](/docs/app/guides/runtime-prefetching), and the fallback for [ISR with Cache Components](/docs/app/guides/incremental-static-regeneration-cache-components). | ||
| A per-route prerender containing the parts of a page that don't depend on URL data. Cached content is included when its [`stale`](/docs/app/api-reference/functions/cacheLife#stale) time is at least 5 minutes, since the shell is reused for longer than shorter-lived content stays fresh. Routes that read `cookies()` or `headers()` produce one that also includes session data, cached per session on the client. Used as the default prefetch payload during client navigations, the loading state when a [per-link prefetch](/docs/app/guides/optimizing-prefetching) is not ready, and the fallback for [ISR with Cache Components](/docs/app/guides/incremental-static-regeneration-cache-components). | ||
@@ -18,0 +18,0 @@ # B |
@@ -14,3 +14,3 @@ import path from 'path'; | ||
| }({}); | ||
| const nextVersion = "16.3.1-canary.10"; | ||
| const nextVersion = "16.3.1-canary.11"; | ||
| const ArchName = arch(); | ||
@@ -17,0 +17,0 @@ const PlatformName = platform(); |
@@ -96,3 +96,2 @@ var _self___RSC_MANIFEST; | ||
| enableTainting: nextConfig.experimental.taint, | ||
| htmlLimitedBots: nextConfig.htmlLimitedBots, | ||
| reactMaxHeadersLength: nextConfig.reactMaxHeadersLength, | ||
@@ -99,0 +98,0 @@ multiZoneDraftMode: false, |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/build/templates/edge-ssr-app.ts"],"sourcesContent":["import '../../server/web/globals'\nimport {\n adapter,\n type EdgeHandler,\n type NextRequestHint,\n} from '../../server/web/adapter'\nimport { IncrementalCache } from '../../server/lib/incremental-cache'\n\nimport * as pageMod from 'VAR_USERLAND'\n\nimport { setManifestsSingleton } from '../../server/app-render/manifests-singleton'\nimport * as cacheHandlers from '../../server/use-cache/handlers'\nimport { BaseServerSpan } from '../../server/lib/trace/constants'\nimport {\n getTracer,\n SpanKind,\n SpanStatusCode,\n type Span,\n} from '../../server/lib/trace/tracer'\nimport { WebNextRequest, WebNextResponse } from '../../server/base-http/web'\nimport type { NextFetchEvent } from '../../server/web/spec-extension/fetch-event'\nimport type {\n AppPageRouteHandlerContext,\n AppPageRouteModule,\n} from '../../server/route-modules/app-page/module.compiled'\nimport type { AppPageRenderResultMetadata } from '../../server/render-result'\nimport type RenderResult from '../../server/render-result'\nimport { getIsPossibleServerAction } from '../../server/lib/server-action-request-meta'\nimport { getBotType } from '../../shared/lib/router/utils/is-bot'\nimport { interopDefault } from '../../lib/interop-default'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport { checkIsOnDemandRevalidate } from '../../server/api-utils'\nimport { CloseController } from '../../server/web/web-on-close'\nimport { parseMaxPostponedStateSize } from '../../shared/lib/size-limit'\nimport { toNodeOutgoingHttpHeaders } from '../../server/web/utils'\nimport type { RequestMeta } from '../../server/request-meta'\n\ndeclare const incrementalCacheHandler: any\n// OPTIONAL_IMPORT:incrementalCacheHandler\n// INJECT_RAW:cacheHandlerImports\n\nconst maybeJSONParse = (str?: string) => (str ? JSON.parse(str) : undefined)\n\nconst rscManifest = self.__RSC_MANIFEST?.['VAR_PAGE']\nconst rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST)\n\nif (rscManifest && rscServerManifest) {\n setManifestsSingleton({\n page: 'VAR_PAGE',\n clientReferenceManifest: rscManifest,\n serverActionsManifest: rscServerManifest,\n })\n}\n\nexport const ComponentMod = pageMod\n\nasync function requestHandler(\n req: NextRequestHint,\n event: NextFetchEvent\n): Promise<Response> {\n let srcPage = 'VAR_PAGE'\n\n const normalizedSrcPage = normalizeAppPath(srcPage)\n const relativeUrl = `${req.nextUrl.pathname}${req.nextUrl.search}`\n const baseReq = new WebNextRequest(req)\n const baseRes = new WebNextResponse(undefined)\n\n const pageRouteModule = pageMod.routeModule as AppPageRouteModule\n const prepareResult = await pageRouteModule.prepare(baseReq, null, {\n srcPage,\n multiZoneDraftMode: false,\n })\n\n if (!prepareResult) {\n return new Response('Bad Request', {\n status: 400,\n })\n }\n const {\n query,\n params,\n buildId,\n nextConfig,\n buildManifest,\n prerenderManifest,\n reactLoadableManifest,\n subresourceIntegrityManifest,\n dynamicCssManifest,\n nextFontManifest,\n resolvedPathname,\n interceptionRoutePatterns,\n routerServerContext,\n deploymentId,\n clientAssetToken,\n } = prepareResult\n\n // Initialize the cache handlers interface.\n cacheHandlers.initializeCacheHandlers(nextConfig.cacheMaxMemorySize)\n // INJECT_RAW:cacheHandlerRegistration\n\n const isPossibleServerAction = getIsPossibleServerAction(req)\n const botType = getBotType(req.headers.get('User-Agent') || '')\n const { isOnDemandRevalidate } = checkIsOnDemandRevalidate(\n req.headers,\n prerenderManifest.preview\n )\n\n const closeController = new CloseController()\n\n const renderContext: AppPageRouteHandlerContext = {\n page: normalizedSrcPage,\n query,\n params,\n\n sharedContext: {\n buildId,\n deploymentId,\n clientAssetToken,\n },\n fallbackRouteParams: null,\n\n renderOpts: {\n App: () => null,\n Document: () => null,\n pageConfig: {},\n ComponentMod,\n Component: interopDefault(ComponentMod),\n routeModule: pageRouteModule,\n\n params,\n page: srcPage,\n postponed: undefined,\n serveStreamingMetadata: true,\n supportsDynamicResponse: true,\n buildManifest,\n nextFontManifest,\n reactLoadableManifest,\n subresourceIntegrityManifest,\n dynamicCssManifest,\n setIsrStatus: routerServerContext?.setIsrStatus,\n\n dir: pageRouteModule.relativeProjectDir,\n botType,\n isDraftMode: false,\n isOnDemandRevalidate,\n isPossibleServerAction,\n assetPrefix: nextConfig.assetPrefix,\n nextConfigOutput: nextConfig.output,\n crossOrigin: nextConfig.crossOrigin,\n trailingSlash: nextConfig.trailingSlash,\n images: nextConfig.images,\n previewProps: prerenderManifest.preview,\n enableTainting: nextConfig.experimental.taint,\n htmlLimitedBots: nextConfig.htmlLimitedBots,\n reactMaxHeadersLength: nextConfig.reactMaxHeadersLength,\n\n multiZoneDraftMode: false,\n cacheLifeProfiles: nextConfig.cacheLife,\n staticPageGenerationTimeout: nextConfig.staticPageGenerationTimeout,\n basePath: nextConfig.basePath,\n serverActions: nextConfig.experimental.serverActions,\n logServerFunctions:\n typeof nextConfig.logging === 'object' &&\n Boolean(nextConfig.logging.serverFunctions),\n cacheComponents: Boolean(nextConfig.cacheComponents),\n validationLevel: nextConfig.experimental.instantInsights.validationLevel,\n experimental: {\n isRoutePPREnabled: false,\n expireTime: nextConfig.expireTime,\n staleTimes: nextConfig.experimental.staleTimes,\n dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover),\n optimisticRouting: Boolean(nextConfig.experimental.optimisticRouting),\n inlineCss: Boolean(nextConfig.experimental.inlineCss),\n prefetchInlining: nextConfig.experimental.prefetchInlining ?? false,\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts),\n // Edge has no Node response-close signal, so HMR cancellation is a\n // no-op.\n serverComponentsHmrCancellation: false,\n useCacheTimeout: nextConfig.experimental.useCacheTimeout,\n cachedNavigations: nextConfig.experimental.cachedNavigations ?? false,\n clientTraceMetadata:\n nextConfig.experimental.clientTraceMetadata || ([] as any),\n clientParamParsingOrigins:\n nextConfig.experimental.clientParamParsingOrigins,\n maxPostponedStateSizeBytes: parseMaxPostponedStateSize(\n nextConfig.experimental.maxPostponedStateSize\n ),\n exposeTestingApi:\n nextConfig.cacheComponents === true &&\n (pageRouteModule.isDev === true ||\n nextConfig.experimental.exposeTestingApiInProductionBuild === true),\n },\n\n incrementalCache: await pageRouteModule.getIncrementalCache(\n baseReq,\n nextConfig,\n prerenderManifest,\n true\n ),\n\n waitUntil: event.waitUntil.bind(event),\n onClose: (cb) => {\n closeController.onClose(cb)\n },\n onAfterTaskError: () => {},\n\n onInstrumentationRequestError: (\n error,\n _request,\n errorContext,\n silenceLog\n ) =>\n pageRouteModule.onRequestError(\n baseReq,\n error,\n errorContext,\n silenceLog,\n routerServerContext\n ),\n },\n }\n let finalStatus = 200\n\n const renderResultToResponse = (\n result: RenderResult<AppPageRenderResultMetadata>\n ): Response => {\n const varyHeader = pageRouteModule.getVaryHeader(\n resolvedPathname,\n interceptionRoutePatterns\n )\n // Handle null responses\n if (result.isNull) {\n finalStatus = 500\n closeController.dispatchClose()\n return new Response(null, { status: 500 })\n }\n\n // Extract metadata\n const { metadata } = result\n const headers = new Headers()\n finalStatus = metadata.statusCode || baseRes.statusCode || 200\n // Pull any fetch metrics from the render onto the request.\n ;(req as any).fetchMetrics = metadata.fetchMetrics\n\n // Set content type\n const contentType = result.contentType || 'text/html; charset=utf-8'\n headers.set('Content-Type', contentType)\n headers.set('x-edge-runtime', '1')\n\n if (varyHeader) {\n headers.set('Vary', varyHeader)\n }\n\n // Add existing headers\n for (const [key, value] of Object.entries({\n ...baseRes.getHeaders(),\n ...metadata.headers,\n })) {\n if (value !== undefined) {\n if (Array.isArray(value)) {\n // Handle multiple header values\n for (const v of value) {\n headers.append(key, String(v))\n }\n } else {\n headers.set(key, String(value))\n }\n }\n }\n\n // Handle static response\n if (!result.isDynamic) {\n const body = result.toUnchunkedString()\n headers.set(\n 'Content-Length',\n String(new TextEncoder().encode(body).length)\n )\n closeController.dispatchClose()\n return new Response(body, {\n status: finalStatus,\n headers,\n })\n }\n\n // Handle dynamic/streaming response\n // For edge runtime, we need to create a readable stream that pipes from the result\n const { readable, writable } = new TransformStream()\n\n // Start piping the result to the writable stream\n // This is done asynchronously to avoid blocking the response creation\n result\n .pipeTo(writable)\n .catch((err: unknown) => {\n console.error('Error piping RenderResult to response:', err)\n })\n .finally(() => closeController.dispatchClose())\n\n return new Response(readable, {\n status: finalStatus,\n headers,\n })\n }\n\n const invokeRender = async (span?: Span): Promise<Response> => {\n try {\n const result = await pageRouteModule\n .render(baseReq, baseRes, renderContext)\n .finally(() => {\n if (!span) return\n\n span.setAttributes({\n 'http.status_code': finalStatus,\n 'next.rsc': false,\n })\n\n if (finalStatus && finalStatus >= 500) {\n // For 5xx status codes: SHOULD be set to 'Error' span status.\n // x-ref: https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status\n span.setStatus({\n code: SpanStatusCode.ERROR,\n })\n // For span status 'Error', SHOULD set 'error.type' attribute.\n span.setAttribute('error.type', finalStatus.toString())\n }\n\n const rootSpanAttributes = tracer.getRootSpanAttributes()\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return\n }\n\n if (\n rootSpanAttributes.get('next.span_type') !==\n BaseServerSpan.handleRequest\n ) {\n console.warn(\n `Unexpected root span type '${rootSpanAttributes.get(\n 'next.span_type'\n )}'. Please report this Next.js issue https://github.com/vercel/next.js`\n )\n return\n }\n\n const route = normalizedSrcPage\n if (route) {\n const name = `${req.method} ${route}`\n\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name,\n })\n span.updateName(name)\n } else {\n span.updateName(`${req.method} ${srcPage}`)\n }\n })\n\n return renderResultToResponse(result)\n } catch (err) {\n const silenceLog = false\n await pageRouteModule.onRequestError(\n baseReq,\n err,\n {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'render',\n revalidateReason: undefined,\n },\n silenceLog\n )\n // rethrow so that we can handle serving error page\n throw err\n }\n }\n\n const tracer = getTracer()\n\n return tracer.withPropagatedContext(req.headers, () =>\n tracer.trace(\n BaseServerSpan.handleRequest,\n {\n spanName: `${req.method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': req.method,\n 'http.target': relativeUrl,\n 'http.route': normalizedSrcPage,\n },\n },\n invokeRender\n )\n )\n}\n\nconst internalHandler: EdgeHandler = (opts) => {\n return adapter({\n ...opts,\n IncrementalCache,\n handler: requestHandler,\n incrementalCacheHandler,\n page: 'VAR_PAGE',\n })\n}\n\nexport async function handler(\n request: Request,\n ctx: {\n waitUntil?: (prom: Promise<void>) => void\n signal?: AbortSignal\n requestMeta?: RequestMeta\n }\n): Promise<Response> {\n const result = await internalHandler({\n request: {\n url: request.url,\n method: request.method,\n headers: toNodeOutgoingHttpHeaders(request.headers),\n nextConfig: {\n basePath: process.env.__NEXT_BASE_PATH,\n i18n: process.env.__NEXT_I18N_CONFIG as any,\n trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),\n experimental: {\n cacheLife: process.env.__NEXT_CACHE_LIFE as any,\n authInterrupts: Boolean(\n process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS\n ),\n clientParamParsingOrigins: process.env\n .__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any,\n },\n },\n page: {\n name: 'VAR_PAGE',\n },\n body:\n request.method !== 'GET' && request.method !== 'HEAD'\n ? (request.body ?? undefined)\n : undefined,\n waitUntil: ctx.waitUntil,\n requestMeta: ctx.requestMeta,\n signal: ctx.signal || new AbortController().signal,\n },\n })\n\n ctx.waitUntil?.(result.waitUntil)\n\n return result.response\n}\n\n// backwards compat\nexport default internalHandler\n"],"names":["self","adapter","IncrementalCache","pageMod","setManifestsSingleton","cacheHandlers","BaseServerSpan","getTracer","SpanKind","SpanStatusCode","WebNextRequest","WebNextResponse","getIsPossibleServerAction","getBotType","interopDefault","normalizeAppPath","checkIsOnDemandRevalidate","CloseController","parseMaxPostponedStateSize","toNodeOutgoingHttpHeaders","maybeJSONParse","str","JSON","parse","undefined","rscManifest","__RSC_MANIFEST","rscServerManifest","__RSC_SERVER_MANIFEST","page","clientReferenceManifest","serverActionsManifest","ComponentMod","requestHandler","req","event","srcPage","normalizedSrcPage","relativeUrl","nextUrl","pathname","search","baseReq","baseRes","pageRouteModule","routeModule","prepareResult","prepare","multiZoneDraftMode","Response","status","query","params","buildId","nextConfig","buildManifest","prerenderManifest","reactLoadableManifest","subresourceIntegrityManifest","dynamicCssManifest","nextFontManifest","resolvedPathname","interceptionRoutePatterns","routerServerContext","deploymentId","clientAssetToken","initializeCacheHandlers","cacheMaxMemorySize","isPossibleServerAction","botType","headers","get","isOnDemandRevalidate","preview","closeController","renderContext","sharedContext","fallbackRouteParams","renderOpts","App","Document","pageConfig","Component","postponed","serveStreamingMetadata","supportsDynamicResponse","setIsrStatus","dir","relativeProjectDir","isDraftMode","assetPrefix","nextConfigOutput","output","crossOrigin","trailingSlash","images","previewProps","enableTainting","experimental","taint","htmlLimitedBots","reactMaxHeadersLength","cacheLifeProfiles","cacheLife","staticPageGenerationTimeout","basePath","serverActions","logServerFunctions","logging","Boolean","serverFunctions","cacheComponents","validationLevel","instantInsights","isRoutePPREnabled","expireTime","staleTimes","dynamicOnHover","optimisticRouting","inlineCss","prefetchInlining","authInterrupts","serverComponentsHmrCancellation","useCacheTimeout","cachedNavigations","clientTraceMetadata","clientParamParsingOrigins","maxPostponedStateSizeBytes","maxPostponedStateSize","exposeTestingApi","isDev","exposeTestingApiInProductionBuild","incrementalCache","getIncrementalCache","waitUntil","bind","onClose","cb","onAfterTaskError","onInstrumentationRequestError","error","_request","errorContext","silenceLog","onRequestError","finalStatus","renderResultToResponse","result","varyHeader","getVaryHeader","isNull","dispatchClose","metadata","Headers","statusCode","fetchMetrics","contentType","set","key","value","Object","entries","getHeaders","Array","isArray","v","append","String","isDynamic","body","toUnchunkedString","TextEncoder","encode","length","readable","writable","TransformStream","pipeTo","catch","err","console","finally","invokeRender","span","render","setAttributes","setStatus","code","ERROR","setAttribute","toString","rootSpanAttributes","tracer","getRootSpanAttributes","handleRequest","warn","route","name","method","updateName","routerKind","routePath","routeType","revalidateReason","withPropagatedContext","trace","spanName","kind","SERVER","attributes","internalHandler","opts","handler","incrementalCacheHandler","request","ctx","url","process","env","__NEXT_BASE_PATH","i18n","__NEXT_I18N_CONFIG","__NEXT_TRAILING_SLASH","__NEXT_CACHE_LIFE","__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS","__NEXT_CLIENT_PARAM_PARSING_ORIGINS","requestMeta","signal","AbortController","response"],"mappings":"IA2CoBA;AA3CpB,OAAO,2BAA0B;AACjC,SACEC,OAAO,QAGF,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,qCAAoC;AAErE,YAAYC,aAAa,eAAc;AAEvC,SAASC,qBAAqB,QAAQ,8CAA6C;AACnF,YAAYC,mBAAmB,kCAAiC;AAChE,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SACEC,SAAS,EACTC,QAAQ,EACRC,cAAc,QAET,gCAA+B;AACtC,SAASC,cAAc,EAAEC,eAAe,QAAQ,6BAA4B;AAQ5E,SAASC,yBAAyB,QAAQ,8CAA6C;AACvF,SAASC,UAAU,QAAQ,uCAAsC;AACjE,SAASC,cAAc,QAAQ,4BAA2B;AAC1D,SAASC,gBAAgB,QAAQ,0CAAyC;AAC1E,SAASC,yBAAyB,QAAQ,yBAAwB;AAClE,SAASC,eAAe,QAAQ,gCAA+B;AAC/D,SAASC,0BAA0B,QAAQ,8BAA6B;AACxE,SAASC,yBAAyB,QAAQ,yBAAwB;AAIlE,0CAA0C;AAC1C,iCAAiC;AAEjC,MAAMC,iBAAiB,CAACC,MAAkBA,MAAMC,KAAKC,KAAK,CAACF,OAAOG;AAElE,MAAMC,eAAczB,uBAAAA,KAAK0B,cAAc,qBAAnB1B,oBAAqB,CAAC,WAAW;AACrD,MAAM2B,oBAAoBP,eAAepB,KAAK4B,qBAAqB;AAEnE,IAAIH,eAAeE,mBAAmB;IACpCvB,sBAAsB;QACpByB,MAAM;QACNC,yBAAyBL;QACzBM,uBAAuBJ;IACzB;AACF;AAEA,OAAO,MAAMK,eAAe7B,QAAO;AAEnC,eAAe8B,eACbC,GAAoB,EACpBC,KAAqB;IAErB,IAA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hC,OAAOa,OAAOkF,QAAQ;AACxB;AAEA,mBAAmB;AACnB,eAAenB,gBAAe","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/build/templates/edge-ssr-app.ts"],"sourcesContent":["import '../../server/web/globals'\nimport {\n adapter,\n type EdgeHandler,\n type NextRequestHint,\n} from '../../server/web/adapter'\nimport { IncrementalCache } from '../../server/lib/incremental-cache'\n\nimport * as pageMod from 'VAR_USERLAND'\n\nimport { setManifestsSingleton } from '../../server/app-render/manifests-singleton'\nimport * as cacheHandlers from '../../server/use-cache/handlers'\nimport { BaseServerSpan } from '../../server/lib/trace/constants'\nimport {\n getTracer,\n SpanKind,\n SpanStatusCode,\n type Span,\n} from '../../server/lib/trace/tracer'\nimport { WebNextRequest, WebNextResponse } from '../../server/base-http/web'\nimport type { NextFetchEvent } from '../../server/web/spec-extension/fetch-event'\nimport type {\n AppPageRouteHandlerContext,\n AppPageRouteModule,\n} from '../../server/route-modules/app-page/module.compiled'\nimport type { AppPageRenderResultMetadata } from '../../server/render-result'\nimport type RenderResult from '../../server/render-result'\nimport { getIsPossibleServerAction } from '../../server/lib/server-action-request-meta'\nimport { getBotType } from '../../shared/lib/router/utils/is-bot'\nimport { interopDefault } from '../../lib/interop-default'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport { checkIsOnDemandRevalidate } from '../../server/api-utils'\nimport { CloseController } from '../../server/web/web-on-close'\nimport { parseMaxPostponedStateSize } from '../../shared/lib/size-limit'\nimport { toNodeOutgoingHttpHeaders } from '../../server/web/utils'\nimport type { RequestMeta } from '../../server/request-meta'\n\ndeclare const incrementalCacheHandler: any\n// OPTIONAL_IMPORT:incrementalCacheHandler\n// INJECT_RAW:cacheHandlerImports\n\nconst maybeJSONParse = (str?: string) => (str ? JSON.parse(str) : undefined)\n\nconst rscManifest = self.__RSC_MANIFEST?.['VAR_PAGE']\nconst rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST)\n\nif (rscManifest && rscServerManifest) {\n setManifestsSingleton({\n page: 'VAR_PAGE',\n clientReferenceManifest: rscManifest,\n serverActionsManifest: rscServerManifest,\n })\n}\n\nexport const ComponentMod = pageMod\n\nasync function requestHandler(\n req: NextRequestHint,\n event: NextFetchEvent\n): Promise<Response> {\n let srcPage = 'VAR_PAGE'\n\n const normalizedSrcPage = normalizeAppPath(srcPage)\n const relativeUrl = `${req.nextUrl.pathname}${req.nextUrl.search}`\n const baseReq = new WebNextRequest(req)\n const baseRes = new WebNextResponse(undefined)\n\n const pageRouteModule = pageMod.routeModule as AppPageRouteModule\n const prepareResult = await pageRouteModule.prepare(baseReq, null, {\n srcPage,\n multiZoneDraftMode: false,\n })\n\n if (!prepareResult) {\n return new Response('Bad Request', {\n status: 400,\n })\n }\n const {\n query,\n params,\n buildId,\n nextConfig,\n buildManifest,\n prerenderManifest,\n reactLoadableManifest,\n subresourceIntegrityManifest,\n dynamicCssManifest,\n nextFontManifest,\n resolvedPathname,\n interceptionRoutePatterns,\n routerServerContext,\n deploymentId,\n clientAssetToken,\n } = prepareResult\n\n // Initialize the cache handlers interface.\n cacheHandlers.initializeCacheHandlers(nextConfig.cacheMaxMemorySize)\n // INJECT_RAW:cacheHandlerRegistration\n\n const isPossibleServerAction = getIsPossibleServerAction(req)\n const botType = getBotType(req.headers.get('User-Agent') || '')\n const { isOnDemandRevalidate } = checkIsOnDemandRevalidate(\n req.headers,\n prerenderManifest.preview\n )\n\n const closeController = new CloseController()\n\n const renderContext: AppPageRouteHandlerContext = {\n page: normalizedSrcPage,\n query,\n params,\n\n sharedContext: {\n buildId,\n deploymentId,\n clientAssetToken,\n },\n fallbackRouteParams: null,\n\n renderOpts: {\n App: () => null,\n Document: () => null,\n pageConfig: {},\n ComponentMod,\n Component: interopDefault(ComponentMod),\n routeModule: pageRouteModule,\n\n params,\n page: srcPage,\n postponed: undefined,\n serveStreamingMetadata: true,\n supportsDynamicResponse: true,\n buildManifest,\n nextFontManifest,\n reactLoadableManifest,\n subresourceIntegrityManifest,\n dynamicCssManifest,\n setIsrStatus: routerServerContext?.setIsrStatus,\n\n dir: pageRouteModule.relativeProjectDir,\n botType,\n isDraftMode: false,\n isOnDemandRevalidate,\n isPossibleServerAction,\n assetPrefix: nextConfig.assetPrefix,\n nextConfigOutput: nextConfig.output,\n crossOrigin: nextConfig.crossOrigin,\n trailingSlash: nextConfig.trailingSlash,\n images: nextConfig.images,\n previewProps: prerenderManifest.preview,\n enableTainting: nextConfig.experimental.taint,\n reactMaxHeadersLength: nextConfig.reactMaxHeadersLength,\n\n multiZoneDraftMode: false,\n cacheLifeProfiles: nextConfig.cacheLife,\n staticPageGenerationTimeout: nextConfig.staticPageGenerationTimeout,\n basePath: nextConfig.basePath,\n serverActions: nextConfig.experimental.serverActions,\n logServerFunctions:\n typeof nextConfig.logging === 'object' &&\n Boolean(nextConfig.logging.serverFunctions),\n cacheComponents: Boolean(nextConfig.cacheComponents),\n validationLevel: nextConfig.experimental.instantInsights.validationLevel,\n experimental: {\n isRoutePPREnabled: false,\n expireTime: nextConfig.expireTime,\n staleTimes: nextConfig.experimental.staleTimes,\n dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover),\n optimisticRouting: Boolean(nextConfig.experimental.optimisticRouting),\n inlineCss: Boolean(nextConfig.experimental.inlineCss),\n prefetchInlining: nextConfig.experimental.prefetchInlining ?? false,\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts),\n // Edge has no Node response-close signal, so HMR cancellation is a\n // no-op.\n serverComponentsHmrCancellation: false,\n useCacheTimeout: nextConfig.experimental.useCacheTimeout,\n cachedNavigations: nextConfig.experimental.cachedNavigations ?? false,\n clientTraceMetadata:\n nextConfig.experimental.clientTraceMetadata || ([] as any),\n clientParamParsingOrigins:\n nextConfig.experimental.clientParamParsingOrigins,\n maxPostponedStateSizeBytes: parseMaxPostponedStateSize(\n nextConfig.experimental.maxPostponedStateSize\n ),\n exposeTestingApi:\n nextConfig.cacheComponents === true &&\n (pageRouteModule.isDev === true ||\n nextConfig.experimental.exposeTestingApiInProductionBuild === true),\n },\n\n incrementalCache: await pageRouteModule.getIncrementalCache(\n baseReq,\n nextConfig,\n prerenderManifest,\n true\n ),\n\n waitUntil: event.waitUntil.bind(event),\n onClose: (cb) => {\n closeController.onClose(cb)\n },\n onAfterTaskError: () => {},\n\n onInstrumentationRequestError: (\n error,\n _request,\n errorContext,\n silenceLog\n ) =>\n pageRouteModule.onRequestError(\n baseReq,\n error,\n errorContext,\n silenceLog,\n routerServerContext\n ),\n },\n }\n let finalStatus = 200\n\n const renderResultToResponse = (\n result: RenderResult<AppPageRenderResultMetadata>\n ): Response => {\n const varyHeader = pageRouteModule.getVaryHeader(\n resolvedPathname,\n interceptionRoutePatterns\n )\n // Handle null responses\n if (result.isNull) {\n finalStatus = 500\n closeController.dispatchClose()\n return new Response(null, { status: 500 })\n }\n\n // Extract metadata\n const { metadata } = result\n const headers = new Headers()\n finalStatus = metadata.statusCode || baseRes.statusCode || 200\n // Pull any fetch metrics from the render onto the request.\n ;(req as any).fetchMetrics = metadata.fetchMetrics\n\n // Set content type\n const contentType = result.contentType || 'text/html; charset=utf-8'\n headers.set('Content-Type', contentType)\n headers.set('x-edge-runtime', '1')\n\n if (varyHeader) {\n headers.set('Vary', varyHeader)\n }\n\n // Add existing headers\n for (const [key, value] of Object.entries({\n ...baseRes.getHeaders(),\n ...metadata.headers,\n })) {\n if (value !== undefined) {\n if (Array.isArray(value)) {\n // Handle multiple header values\n for (const v of value) {\n headers.append(key, String(v))\n }\n } else {\n headers.set(key, String(value))\n }\n }\n }\n\n // Handle static response\n if (!result.isDynamic) {\n const body = result.toUnchunkedString()\n headers.set(\n 'Content-Length',\n String(new TextEncoder().encode(body).length)\n )\n closeController.dispatchClose()\n return new Response(body, {\n status: finalStatus,\n headers,\n })\n }\n\n // Handle dynamic/streaming response\n // For edge runtime, we need to create a readable stream that pipes from the result\n const { readable, writable } = new TransformStream()\n\n // Start piping the result to the writable stream\n // This is done asynchronously to avoid blocking the response creation\n result\n .pipeTo(writable)\n .catch((err: unknown) => {\n console.error('Error piping RenderResult to response:', err)\n })\n .finally(() => closeController.dispatchClose())\n\n return new Response(readable, {\n status: finalStatus,\n headers,\n })\n }\n\n const invokeRender = async (span?: Span): Promise<Response> => {\n try {\n const result = await pageRouteModule\n .render(baseReq, baseRes, renderContext)\n .finally(() => {\n if (!span) return\n\n span.setAttributes({\n 'http.status_code': finalStatus,\n 'next.rsc': false,\n })\n\n if (finalStatus && finalStatus >= 500) {\n // For 5xx status codes: SHOULD be set to 'Error' span status.\n // x-ref: https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status\n span.setStatus({\n code: SpanStatusCode.ERROR,\n })\n // For span status 'Error', SHOULD set 'error.type' attribute.\n span.setAttribute('error.type', finalStatus.toString())\n }\n\n const rootSpanAttributes = tracer.getRootSpanAttributes()\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return\n }\n\n if (\n rootSpanAttributes.get('next.span_type') !==\n BaseServerSpan.handleRequest\n ) {\n console.warn(\n `Unexpected root span type '${rootSpanAttributes.get(\n 'next.span_type'\n )}'. Please report this Next.js issue https://github.com/vercel/next.js`\n )\n return\n }\n\n const route = normalizedSrcPage\n if (route) {\n const name = `${req.method} ${route}`\n\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name,\n })\n span.updateName(name)\n } else {\n span.updateName(`${req.method} ${srcPage}`)\n }\n })\n\n return renderResultToResponse(result)\n } catch (err) {\n const silenceLog = false\n await pageRouteModule.onRequestError(\n baseReq,\n err,\n {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'render',\n revalidateReason: undefined,\n },\n silenceLog\n )\n // rethrow so that we can handle serving error page\n throw err\n }\n }\n\n const tracer = getTracer()\n\n return tracer.withPropagatedContext(req.headers, () =>\n tracer.trace(\n BaseServerSpan.handleRequest,\n {\n spanName: `${req.method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': req.method,\n 'http.target': relativeUrl,\n 'http.route': normalizedSrcPage,\n },\n },\n invokeRender\n )\n )\n}\n\nconst internalHandler: EdgeHandler = (opts) => {\n return adapter({\n ...opts,\n IncrementalCache,\n handler: requestHandler,\n incrementalCacheHandler,\n page: 'VAR_PAGE',\n })\n}\n\nexport async function handler(\n request: Request,\n ctx: {\n waitUntil?: (prom: Promise<void>) => void\n signal?: AbortSignal\n requestMeta?: RequestMeta\n }\n): Promise<Response> {\n const result = await internalHandler({\n request: {\n url: request.url,\n method: request.method,\n headers: toNodeOutgoingHttpHeaders(request.headers),\n nextConfig: {\n basePath: process.env.__NEXT_BASE_PATH,\n i18n: process.env.__NEXT_I18N_CONFIG as any,\n trailingSlash: Boolean(process.env.__NEXT_TRAILING_SLASH),\n experimental: {\n cacheLife: process.env.__NEXT_CACHE_LIFE as any,\n authInterrupts: Boolean(\n process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS\n ),\n clientParamParsingOrigins: process.env\n .__NEXT_CLIENT_PARAM_PARSING_ORIGINS as any,\n },\n },\n page: {\n name: 'VAR_PAGE',\n },\n body:\n request.method !== 'GET' && request.method !== 'HEAD'\n ? (request.body ?? undefined)\n : undefined,\n waitUntil: ctx.waitUntil,\n requestMeta: ctx.requestMeta,\n signal: ctx.signal || new AbortController().signal,\n },\n })\n\n ctx.waitUntil?.(result.waitUntil)\n\n return result.response\n}\n\n// backwards compat\nexport default internalHandler\n"],"names":["self","adapter","IncrementalCache","pageMod","setManifestsSingleton","cacheHandlers","BaseServerSpan","getTracer","SpanKind","SpanStatusCode","WebNextRequest","WebNextResponse","getIsPossibleServerAction","getBotType","interopDefault","normalizeAppPath","checkIsOnDemandRevalidate","CloseController","parseMaxPostponedStateSize","toNodeOutgoingHttpHeaders","maybeJSONParse","str","JSON","parse","undefined","rscManifest","__RSC_MANIFEST","rscServerManifest","__RSC_SERVER_MANIFEST","page","clientReferenceManifest","serverActionsManifest","ComponentMod","requestHandler","req","event","srcPage","normalizedSrcPage","relativeUrl","nextUrl","pathname","search","baseReq","baseRes","pageRouteModule","routeModule","prepareResult","prepare","multiZoneDraftMode","Response","status","query","params","buildId","nextConfig","buildManifest","prerenderManifest","reactLoadableManifest","subresourceIntegrityManifest","dynamicCssManifest","nextFontManifest","resolvedPathname","interceptionRoutePatterns","routerServerContext","deploymentId","clientAssetToken","initializeCacheHandlers","cacheMaxMemorySize","isPossibleServerAction","botType","headers","get","isOnDemandRevalidate","preview","closeController","renderContext","sharedContext","fallbackRouteParams","renderOpts","App","Document","pageConfig","Component","postponed","serveStreamingMetadata","supportsDynamicResponse","setIsrStatus","dir","relativeProjectDir","isDraftMode","assetPrefix","nextConfigOutput","output","crossOrigin","trailingSlash","images","previewProps","enableTainting","experimental","taint","reactMaxHeadersLength","cacheLifeProfiles","cacheLife","staticPageGenerationTimeout","basePath","serverActions","logServerFunctions","logging","Boolean","serverFunctions","cacheComponents","validationLevel","instantInsights","isRoutePPREnabled","expireTime","staleTimes","dynamicOnHover","optimisticRouting","inlineCss","prefetchInlining","authInterrupts","serverComponentsHmrCancellation","useCacheTimeout","cachedNavigations","clientTraceMetadata","clientParamParsingOrigins","maxPostponedStateSizeBytes","maxPostponedStateSize","exposeTestingApi","isDev","exposeTestingApiInProductionBuild","incrementalCache","getIncrementalCache","waitUntil","bind","onClose","cb","onAfterTaskError","onInstrumentationRequestError","error","_request","errorContext","silenceLog","onRequestError","finalStatus","renderResultToResponse","result","varyHeader","getVaryHeader","isNull","dispatchClose","metadata","Headers","statusCode","fetchMetrics","contentType","set","key","value","Object","entries","getHeaders","Array","isArray","v","append","String","isDynamic","body","toUnchunkedString","TextEncoder","encode","length","readable","writable","TransformStream","pipeTo","catch","err","console","finally","invokeRender","span","render","setAttributes","setStatus","code","ERROR","setAttribute","toString","rootSpanAttributes","tracer","getRootSpanAttributes","handleRequest","warn","route","name","method","updateName","routerKind","routePath","routeType","revalidateReason","withPropagatedContext","trace","spanName","kind","SERVER","attributes","internalHandler","opts","handler","incrementalCacheHandler","request","ctx","url","process","env","__NEXT_BASE_PATH","i18n","__NEXT_I18N_CONFIG","__NEXT_TRAILING_SLASH","__NEXT_CACHE_LIFE","__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS","__NEXT_CLIENT_PARAM_PARSING_ORIGINS","requestMeta","signal","AbortController","response"],"mappings":"IA2CoBA;AA3CpB,OAAO,2BAA0B;AACjC,SACEC,OAAO,QAGF,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,qCAAoC;AAErE,YAAYC,aAAa,eAAc;AAEvC,SAASC,qBAAqB,QAAQ,8CAA6C;AACnF,YAAYC,mBAAmB,kCAAiC;AAChE,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SACEC,SAAS,EACTC,QAAQ,EACRC,cAAc,QAET,gCAA+B;AACtC,SAASC,cAAc,EAAEC,eAAe,QAAQ,6BAA4B;AAQ5E,SAASC,yBAAyB,QAAQ,8CAA6C;AACvF,SAASC,UAAU,QAAQ,uCAAsC;AACjE,SAASC,cAAc,QAAQ,4BAA2B;AAC1D,SAASC,gBAAgB,QAAQ,0CAAyC;AAC1E,SAASC,yBAAyB,QAAQ,yBAAwB;AAClE,SAASC,eAAe,QAAQ,gCAA+B;AAC/D,SAASC,0BAA0B,QAAQ,8BAA6B;AACxE,SAASC,yBAAyB,QAAQ,yBAAwB;AAIlE,0CAA0C;AAC1C,iCAAiC;AAEjC,MAAMC,iBAAiB,CAACC,MAAkBA,MAAMC,KAAKC,KAAK,CAACF,OAAOG;AAElE,MAAMC,eAAczB,uBAAAA,KAAK0B,cAAc,qBAAnB1B,oBAAqB,CAAC,WAAW;AACrD,MAAM2B,oBAAoBP,eAAepB,KAAK4B,qBAAqB;AAEnE,IAAIH,eAAeE,mBAAmB;IACpCvB,sBAAsB;QACpByB,MAAM;QACNC,yBAAyBL;QACzBM,uBAAuBJ;IACzB;AACF;AAEA,OAAO,MAAMK,eAAe7B,QAAO;AAEnC,eAAe8B,eACbC,GAAoB,EACpBC,KAAqB;IAErB,IAAIC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AEA,mBAAmB;AACnB,eAAenB,gBAAe","ignoreList":[0]} |
@@ -69,3 +69,3 @@ import path from 'path'; | ||
| isPersistentCachingEnabled: persistentCaching, | ||
| nextVersion: "16.3.1-canary.10" | ||
| nextVersion: "16.3.1-canary.11" | ||
| }, { | ||
@@ -72,0 +72,0 @@ turbopackMemoryEviction: config.experimental.turbopackMemoryEvictionMode, |
@@ -88,3 +88,3 @@ // Import cpu-profile first to start profiling early if enabled | ||
| deferredEntries: config.experimental.deferredEntries, | ||
| nextVersion: "16.3.1-canary.10" | ||
| nextVersion: "16.3.1-canary.11" | ||
| }; | ||
@@ -91,0 +91,0 @@ if (config.experimental.turbopackSeedCacheFromWorktree) { |
@@ -8,3 +8,3 @@ /** | ||
| import { setAttributesFromProps } from './set-attributes-from-props'; | ||
| const version = "16.3.1-canary.10"; | ||
| const version = "16.3.1-canary.11"; | ||
| window.next = { | ||
@@ -11,0 +11,0 @@ version, |
@@ -330,3 +330,3 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime"; | ||
| }, []); | ||
| const { cache, tree, nextUrl, focusAndScrollRef, previousNextUrl } = state; | ||
| const { cache, tree, nextUrl, scrollRef, previousNextUrl } = state; | ||
| const matchingHead = useMemo(()=>{ | ||
@@ -376,3 +376,3 @@ return findHeadInCache(cache, tree[1]); | ||
| tree, | ||
| focusAndScrollRef, | ||
| scrollRef, | ||
| nextUrl, | ||
@@ -383,3 +383,3 @@ previousNextUrl | ||
| tree, | ||
| focusAndScrollRef, | ||
| scrollRef, | ||
| nextUrl, | ||
@@ -386,0 +386,0 @@ previousNextUrl |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/client/components/app-router.tsx"],"sourcesContent":["import 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 { CacheNode } from '../../shared/lib/app-router-types'\nimport { ACTION_RESTORE } from './router-reducer/router-reducer-types'\nimport type {\n AppHistoryState,\n AppRouterState,\n} from './router-reducer/router-reducer-types'\nimport { createHrefFromUrl } from './router-reducer/create-href-from-url'\nimport {\n SearchParamsContext,\n PathnameContext,\n PathParamsContext,\n NavigationPromisesContext,\n type NavigationPromises,\n} from '../../shared/lib/hooks-client-context.shared-runtime'\nimport { dispatchAppRouterAction, useActionQueue } from './use-action-queue'\nimport { setLastCommittedTree } from './router-reducer/reducers/committed-state'\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 {\n extractSourcePageFromFlightRouterState,\n getSelectedParams,\n} 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 } 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'\nimport { getAssetTokenQuery } from '../../shared/lib/deployment-id'\n\nconst globalMutable: {\n pendingMpaPath?: string\n} = {}\n\n// A Back/Forward press before the router's popstate listener exists moves the\n// browser to a different history entry than the one the document was activated\n// on, and the resulting popstate fires with nobody listening. The activation\n// entry is fixed for the document's lifetime and entry keys are stable across\n// replaceState, so until the listener is installed a key mismatch means a\n// traversal went unobserved.\nfunction hasMissedTraversal(): boolean {\n if (typeof window.navigation === 'undefined') {\n return false\n }\n const activationEntry = window.navigation.activation?.entry\n const currentEntry = window.navigation.currentEntry\n return (\n activationEntry != null &&\n currentEntry != null &&\n activationEntry.key !== currentEntry.key &&\n // Only entries written by the app router can be restored; on any other\n // entry the traversal is left unhandled, as before.\n window.history.state?.__NA === true\n )\n}\n\nlet checkedMissedTraversalBeforeHistoryWrite = false\nlet checkedMissedTraversalBeforeReplay = false\n\n/**\n * Handles a popstate event (or one that was missed before hydration).\n * By default dispatches ACTION_RESTORE, however if the history entry was not\n * pushed/replaced by app-router it will reload the page.\n * That case can happen when the old router injected the history entry.\n */\nfunction handlePopState(state: PopStateEvent['state']): void {\n if (!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 (!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 state.__PRIVATE_NEXTJS_INTERNALS_TREE\n )\n })\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, renderedSearch } = appRouterState\n\n if (!checkedMissedTraversalBeforeHistoryWrite) {\n checkedMissedTraversalBeforeHistoryWrite = true\n if (hasMissedTraversal()) {\n // Skip the write: it would overwrite the traversed-to entry's state.\n // The tree was rendered even though the history write is skipped.\n setLastCommittedTree(tree)\n return\n }\n }\n\n const appHistoryState: AppHistoryState = {\n tree,\n renderedSearch,\n }\n\n // TODO: Use Navigation API if available\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: appHistoryState,\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\n setLastCommittedTree(tree)\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 pingVisibleLinks(appRouterState.nextUrl, appRouterState.tree)\n }, [appRouterState.nextUrl, appRouterState.tree])\n\n return null\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 const { cache, 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 tree,\n }\n }, [cache, tree])\n }\n\n useEffect(() => {\n const sourcePage = extractSourcePageFromFlightRouterState(state.tree)\n\n if (sourcePage !== undefined) {\n window.next.__internal_src_page = sourcePage\n } else {\n delete window.next.__internal_src_page\n }\n }, [state.tree])\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 historyState: 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 === '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 appHistoryState: AppHistoryState | 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 historyState: appHistoryState,\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 // TODO: Warn when Navigation API is available (navigation.navigate() should be used)\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 // TODO: Warn when Navigation API is available (navigation.navigate() should be used)\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 const onPopState = (event: PopStateEvent) => handlePopState(event.state)\n\n window.addEventListener('popstate', onPopState)\n\n if (!checkedMissedTraversalBeforeReplay) {\n checkedMissedTraversalBeforeReplay = true\n if (hasMissedTraversal()) {\n handlePopState(window.history.state)\n }\n }\n\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, previousNextUrl } = 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 // Create instrumented promises for navigation hooks (dev-only)\n // These are specially instrumented promises to show in the Suspense DevTools\n // Promises are cached outside of render to survive suspense retries.\n let instrumentedNavigationPromises: NavigationPromises | null = null\n if (process.env.NODE_ENV !== 'production') {\n const { createRootNavigationPromises } =\n require('./navigation-devtools') as typeof import('./navigation-devtools')\n\n instrumentedNavigationPromises = createRootNavigationPromises(\n tree,\n pathname,\n searchParams,\n pathParams\n )\n }\n\n const layoutRouterContext = useMemo(() => {\n return {\n parentTree: tree,\n parentCacheNode: cache,\n parentSegmentPath: null,\n parentParams: {},\n parentLoadingData: null,\n // This is the <Activity> \"name\" that shows up in the Suspense DevTools.\n // It represents the root of the app.\n debugNameContext: '/',\n // Root node always has `url`\n // Provided in AppTreeContext to ensure it can be overwritten in layout-router\n url: canonicalUrl,\n // Root segment is always active\n isActive: true,\n }\n }, [tree, cache, canonicalUrl])\n\n const globalLayoutRouterContext = useMemo(() => {\n return {\n tree,\n focusAndScrollRef,\n nextUrl,\n previousNextUrl,\n }\n }, [tree, focusAndScrollRef, nextUrl, previousNextUrl])\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.__NEXT_DEV_SERVER) {\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 // TODO(browser-variant): migrate to a .ts/.browser.ts split so the browser bundle drops the server branch; see scripts/generate-browser-variant-aliases.mjs\n // ast-grep-ignore: no-typeof-window-require-tsx\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 if (process.env.__NEXT_USE_OFFLINE) {\n const { OfflineProvider } =\n require('./use-offline') as typeof import('./use-offline')\n content = <OfflineProvider>{content}</OfflineProvider>\n }\n\n return (\n <>\n <HistoryUpdater appRouterState={state} />\n {process.env.TURBOPACK ? null : <RuntimeStylesForWebpack />}\n <NavigationPromisesContext.Provider\n value={instrumentedNavigationPromises}\n >\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 </NavigationPromisesContext.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\nlet runtimeStyles: Set<string> | undefined\nlet runtimeStyleChanged: Set<() => void> | undefined\nif (!process.env.TURBOPACK && typeof window !== 'undefined') {\n runtimeStyles = new Set<string>()\n runtimeStyleChanged = new Set<() => void>()\n\n globalThis._N_E_STYLE_LOAD = function (href: string) {\n if (!runtimeStyles || !runtimeStyleChanged) return Promise.resolve()\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}\n\nfunction RuntimeStylesForWebpack() {\n const [, forceUpdate] = React.useState(0)\n const renderedStylesSize = runtimeStyles?.size ?? 0\n useEffect(() => {\n if (!runtimeStyles || !runtimeStyleChanged) return\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 query = getAssetTokenQuery()\n return [...(runtimeStyles || [])].map((href, i) => (\n <link\n key={i}\n rel=\"stylesheet\"\n href={`${href}${query}`}\n // @ts-ignore\n precedence=\"next\"\n // TODO figure out crossOrigin and nonce\n // crossOrigin={TODO}\n // nonce={TODO}\n />\n ))\n}\n"],"names":["React","useEffect","useMemo","startTransition","useInsertionEffect","useDeferredValue","AppRouterContext","LayoutRouterContext","GlobalLayoutRouterContext","ACTION_RESTORE","createHrefFromUrl","SearchParamsContext","PathnameContext","PathParamsContext","NavigationPromisesContext","dispatchAppRouterAction","useActionQueue","setLastCommittedTree","AppRouterAnnouncer","RedirectBoundary","findHeadInCache","unresolvedThenable","removeBasePath","hasBasePath","extractSourcePageFromFlightRouterState","getSelectedParams","useNavFailureHandler","dispatchTraverseAction","publicAppRouterInstance","getRedirectTypeFromError","getURLFromRedirectError","isRedirectError","pingVisibleLinks","RootErrorBoundary","DefaultGlobalError","RootLayoutBoundary","getAssetTokenQuery","globalMutable","hasMissedTraversal","window","navigation","activationEntry","activation","entry","currentEntry","key","history","state","__NA","checkedMissedTraversalBeforeHistoryWrite","checkedMissedTraversalBeforeReplay","handlePopState","location","reload","href","__PRIVATE_NEXTJS_INTERNALS_TREE","HistoryUpdater","appRouterState","process","env","__NEXT_APP_NAV_FAIL_HANDLING","next","__pendingUrl","undefined","tree","pushRef","canonicalUrl","renderedSearch","appHistoryState","historyState","preserveCustomHistoryState","pendingPush","URL","pushState","replaceState","nextUrl","copyNextJsInternalHistoryState","data","currentState","Head","headCacheNode","head","prefetchHead","resolvedPrefetchRsc","Router","actionQueue","globalError","webSocket","staticIndicatorState","searchParams","pathname","url","NODE_ENV","cache","nd","router","sourcePage","__internal_src_page","handlePageShow","event","persisted","pendingMpaPath","type","addEventListener","removeEventListener","handleUnhandledRedirect","error","reason","preventDefault","redirectType","push","replace","mpaNavigation","assign","originalPushState","bind","originalReplaceState","applyUrlFromHistoryPushReplace","_unused","_N","onPopState","focusAndScrollRef","previousNextUrl","matchingHead","pathParams","instrumentedNavigationPromises","createRootNavigationPromises","require","layoutRouterContext","parentTree","parentCacheNode","parentSegmentPath","parentParams","parentLoadingData","debugNameContext","isActive","globalLayoutRouterContext","headKey","headKeyWithoutSearchParams","content","rsc","__NEXT_DEV_SERVER","DevRootHTTPAccessFallbackBoundary","HotReloader","default","errorComponent","errorStyles","__NEXT_USE_OFFLINE","OfflineProvider","TURBOPACK","RuntimeStylesForWebpack","Provider","value","AppRouter","globalErrorState","runtimeStyles","runtimeStyleChanged","Set","globalThis","_N_E_STYLE_LOAD","Promise","resolve","len","size","add","forEach","cb","forceUpdate","useState","renderedStylesSize","changed","c","delete","query","map","i","link","rel","precedence"],"mappings":";AAAA,OAAOA,SACLC,SAAS,EACTC,OAAO,EACPC,eAAe,EACfC,kBAAkB,EAClBC,gBAAgB,QACX,QAAO;AACd,SACEC,gBAAgB,EAChBC,mBAAmB,EACnBC,yBAAyB,QACpB,qDAAoD;AAE3D,SAASC,cAAc,QAAQ,wCAAuC;AAKtE,SAASC,iBAAiB,QAAQ,wCAAuC;AACzE,SACEC,mBAAmB,EACnBC,eAAe,EACfC,iBAAiB,EACjB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AQ;IAClDlK,UAAU;QACR,IAAI,CAAC0J,iBAAiB,CAACC,qBAAqB;QAC5C,MAAMc,UAAU,IAAMH,YAAY,CAACI,IAAMA,IAAI;QAC7Cf,oBAAoBQ,GAAG,CAACM;QACxB,IAAID,uBAAuBd,cAAcQ,IAAI,EAAE;YAC7CO;QACF;QACA,OAAO;YACLd,oBAAoBgB,MAAM,CAACF;QAC7B;IACF,GAAG;QAACD;QAAoBF;KAAY;IAEpC,MAAMM,QAAQzI;IACd,OAAO;WAAKuH,iBAAiB,EAAE;KAAE,CAACmB,GAAG,CAAC,CAACxH,MAAMyH,kBAC3C,KAACC;YAECC,KAAI;YACJ3H,MAAM,GAAGA,OAAOuH,OAAO;YACvB,aAAa;YACbK,YAAW;WAJNH;AAUX","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/client/components/app-router.tsx"],"sourcesContent":["import 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 { CacheNode } from '../../shared/lib/app-router-types'\nimport { ACTION_RESTORE } from './router-reducer/router-reducer-types'\nimport type {\n AppHistoryState,\n AppRouterState,\n} from './router-reducer/router-reducer-types'\nimport { createHrefFromUrl } from './router-reducer/create-href-from-url'\nimport {\n SearchParamsContext,\n PathnameContext,\n PathParamsContext,\n NavigationPromisesContext,\n type NavigationPromises,\n} from '../../shared/lib/hooks-client-context.shared-runtime'\nimport { dispatchAppRouterAction, useActionQueue } from './use-action-queue'\nimport { setLastCommittedTree } from './router-reducer/reducers/committed-state'\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 {\n extractSourcePageFromFlightRouterState,\n getSelectedParams,\n} 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 } 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'\nimport { getAssetTokenQuery } from '../../shared/lib/deployment-id'\n\nconst globalMutable: {\n pendingMpaPath?: string\n} = {}\n\n// A Back/Forward press before the router's popstate listener exists moves the\n// browser to a different history entry than the one the document was activated\n// on, and the resulting popstate fires with nobody listening. The activation\n// entry is fixed for the document's lifetime and entry keys are stable across\n// replaceState, so until the listener is installed a key mismatch means a\n// traversal went unobserved.\nfunction hasMissedTraversal(): boolean {\n if (typeof window.navigation === 'undefined') {\n return false\n }\n const activationEntry = window.navigation.activation?.entry\n const currentEntry = window.navigation.currentEntry\n return (\n activationEntry != null &&\n currentEntry != null &&\n activationEntry.key !== currentEntry.key &&\n // Only entries written by the app router can be restored; on any other\n // entry the traversal is left unhandled, as before.\n window.history.state?.__NA === true\n )\n}\n\nlet checkedMissedTraversalBeforeHistoryWrite = false\nlet checkedMissedTraversalBeforeReplay = false\n\n/**\n * Handles a popstate event (or one that was missed before hydration).\n * By default dispatches ACTION_RESTORE, however if the history entry was not\n * pushed/replaced by app-router it will reload the page.\n * That case can happen when the old router injected the history entry.\n */\nfunction handlePopState(state: PopStateEvent['state']): void {\n if (!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 (!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 state.__PRIVATE_NEXTJS_INTERNALS_TREE\n )\n })\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, renderedSearch } = appRouterState\n\n if (!checkedMissedTraversalBeforeHistoryWrite) {\n checkedMissedTraversalBeforeHistoryWrite = true\n if (hasMissedTraversal()) {\n // Skip the write: it would overwrite the traversed-to entry's state.\n // The tree was rendered even though the history write is skipped.\n setLastCommittedTree(tree)\n return\n }\n }\n\n const appHistoryState: AppHistoryState = {\n tree,\n renderedSearch,\n }\n\n // TODO: Use Navigation API if available\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: appHistoryState,\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\n setLastCommittedTree(tree)\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 pingVisibleLinks(appRouterState.nextUrl, appRouterState.tree)\n }, [appRouterState.nextUrl, appRouterState.tree])\n\n return null\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 const { cache, 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 tree,\n }\n }, [cache, tree])\n }\n\n useEffect(() => {\n const sourcePage = extractSourcePageFromFlightRouterState(state.tree)\n\n if (sourcePage !== undefined) {\n window.next.__internal_src_page = sourcePage\n } else {\n delete window.next.__internal_src_page\n }\n }, [state.tree])\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 historyState: 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 === '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 appHistoryState: AppHistoryState | 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 historyState: appHistoryState,\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 // TODO: Warn when Navigation API is available (navigation.navigate() should be used)\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 // TODO: Warn when Navigation API is available (navigation.navigate() should be used)\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 const onPopState = (event: PopStateEvent) => handlePopState(event.state)\n\n window.addEventListener('popstate', onPopState)\n\n if (!checkedMissedTraversalBeforeReplay) {\n checkedMissedTraversalBeforeReplay = true\n if (hasMissedTraversal()) {\n handlePopState(window.history.state)\n }\n }\n\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, scrollRef, previousNextUrl } = 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 // Create instrumented promises for navigation hooks (dev-only)\n // These are specially instrumented promises to show in the Suspense DevTools\n // Promises are cached outside of render to survive suspense retries.\n let instrumentedNavigationPromises: NavigationPromises | null = null\n if (process.env.NODE_ENV !== 'production') {\n const { createRootNavigationPromises } =\n require('./navigation-devtools') as typeof import('./navigation-devtools')\n\n instrumentedNavigationPromises = createRootNavigationPromises(\n tree,\n pathname,\n searchParams,\n pathParams\n )\n }\n\n const layoutRouterContext = useMemo(() => {\n return {\n parentTree: tree,\n parentCacheNode: cache,\n parentSegmentPath: null,\n parentParams: {},\n parentLoadingData: null,\n // This is the <Activity> \"name\" that shows up in the Suspense DevTools.\n // It represents the root of the app.\n debugNameContext: '/',\n // Root node always has `url`\n // Provided in AppTreeContext to ensure it can be overwritten in layout-router\n url: canonicalUrl,\n // Root segment is always active\n isActive: true,\n }\n }, [tree, cache, canonicalUrl])\n\n const globalLayoutRouterContext = useMemo(() => {\n return {\n tree,\n scrollRef,\n nextUrl,\n previousNextUrl,\n }\n }, [tree, scrollRef, nextUrl, previousNextUrl])\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.__NEXT_DEV_SERVER) {\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 // TODO(browser-variant): migrate to a .ts/.browser.ts split so the browser bundle drops the server branch; see scripts/generate-browser-variant-aliases.mjs\n // ast-grep-ignore: no-typeof-window-require-tsx\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 if (process.env.__NEXT_USE_OFFLINE) {\n const { OfflineProvider } =\n require('./use-offline') as typeof import('./use-offline')\n content = <OfflineProvider>{content}</OfflineProvider>\n }\n\n return (\n <>\n <HistoryUpdater appRouterState={state} />\n {process.env.TURBOPACK ? null : <RuntimeStylesForWebpack />}\n <NavigationPromisesContext.Provider\n value={instrumentedNavigationPromises}\n >\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 </NavigationPromisesContext.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\nlet runtimeStyles: Set<string> | undefined\nlet runtimeStyleChanged: Set<() => void> | undefined\nif (!process.env.TURBOPACK && typeof window !== 'undefined') {\n runtimeStyles = new Set<string>()\n runtimeStyleChanged = new Set<() => void>()\n\n globalThis._N_E_STYLE_LOAD = function (href: string) {\n if (!runtimeStyles || !runtimeStyleChanged) return Promise.resolve()\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}\n\nfunction RuntimeStylesForWebpack() {\n const [, forceUpdate] = React.useState(0)\n const renderedStylesSize = runtimeStyles?.size ?? 0\n useEffect(() => {\n if (!runtimeStyles || !runtimeStyleChanged) return\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 query = getAssetTokenQuery()\n return [...(runtimeStyles || [])].map((href, i) => (\n <link\n key={i}\n rel=\"stylesheet\"\n href={`${href}${query}`}\n // @ts-ignore\n precedence=\"next\"\n // TODO figure out crossOrigin and nonce\n // crossOrigin={TODO}\n // nonce={TODO}\n />\n ))\n}\n"],"names":["React","useEffect","useMemo","startTransition","useInsertionEffect","useDeferredValue","AppRouterContext","LayoutRouterContext","GlobalLayoutRouterContext","ACTION_RESTORE","createHrefFromUrl","SearchParamsContext","PathnameContext","PathParamsContext","NavigationPromisesContext","dispatchAppRouterAction","useActionQueue","setLastCommittedTree","AppRouterAnnouncer","RedirectBoundary","findHeadInCache","unresolvedThenable","removeBasePath","hasBasePath","extractSourcePageFromFlightRouterState","getSelectedParams","useNavFailureHandler","dispatchTraverseAction","publicAppRouterInstance","getRedirectTypeFromError","getURLFromRedirectError","isRedirectError","pingVisibleLinks","RootErrorBoundary","DefaultGlobalError","RootLayoutBoundary","getAssetTokenQuery","globalMutable","hasMissedTraversal","window","navigation","activationEntry","activation","entry","currentEntry","key","history","state","__NA","checkedMissedTraversalBeforeHistoryWrite","checkedMissedTraversalBeforeReplay","handlePopState","location","reload","href","__PRIVATE_NEXTJS_INTERNALS_TREE","HistoryUpdater","appRouterState","process","env","__NEXT_APP_NAV_FAIL_HANDLING","next","__pendingUrl","undefined","tree","pushRef","canonicalUrl","renderedSearch","appHistoryState","historyState","preserveCustomHistoryState","pendingPush","URL","pushState","replaceState","nextUrl","copyNextJsInternalHistoryState","data","currentState","Head","headCacheNode","head","prefetchHead","resolvedPrefetchRsc","Router","actionQueue","globalError","webSocket","staticIndicatorState","searchParams","pathname","url","NODE_ENV","cache","nd","router","sourcePage","__internal_src_page","handlePageShow","event","persisted","pendingMpaPath","type","addEventListener","removeEventListener","handleUnhandledRedirect","error","reason","preventDefault","redirectType","push","replace","mpaNavigation","assign","originalPushState","bind","originalReplaceState","applyUrlFromHistoryPushReplace","_unused","_N","onPopState","scrollRef","previousNextUrl","matchingHead","pathParams","instrumentedNavigationPromises","createRootNavigationPromises","require","layoutRouterContext","parentTree","parentCacheNode","parentSegmentPath","parentParams","parentLoadingData","debugNameContext","isActive","globalLayoutRouterContext","headKey","headKeyWithoutSearchParams","content","rsc","__NEXT_DEV_SERVER","DevRootHTTPAccessFallbackBoundary","HotReloader","default","errorComponent","errorStyles","__NEXT_USE_OFFLINE","OfflineProvider","TURBOPACK","RuntimeStylesForWebpack","Provider","value","AppRouter","globalErrorState","runtimeStyles","runtimeStyleChanged","Set","globalThis","_N_E_STYLE_LOAD","Promise","resolve","len","size","add","forEach","cb","forceUpdate","useState","renderedStylesSize","changed","c","delete","query","map","i","link","rel","precedence"],"mappings":";AAAA,OAAOA,SACLC,SAAS,EACTC,OAAO,EACPC,eAAe,EACfC,kBAAkB,EAClBC,gBAAgB,QACX,QAAO;AACd,SACEC,gBAAgB,EAChBC,mBAAmB,EACnBC,yBAAyB,QACpB,qDAAoD;AAE3D,SAASC,cAAc,QAAQ,wCAAuC;AAKtE,SAASC,iBAAiB,QAAQ,wCAAuC;AACzE,SACEC,mBAAmB,EACnBC,eAAe,EACfC,iBAAiB,EACjBC,yBAAyB,QAEpB,uDAAsD;AAC7D,SAASC,uBAAuB,EAAEC,cAAc,QAAQ,qBAAoB;AAC5E,SAASC,oBAAoB,QAAQ,4CAA2C;AAChF,SAASC,kBAAkB,QAAQ,yBAAwB;AAC3D,SAASC,gBAAgB,QAAQ,sBAAqB;AACtD,SAASC,eAAe,QAAQ,+CAA8C;AAC9E,SAASC,kBAAkB,QAAQ,wBAAuB;AAC1D,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SACEC,sCAAsC,EACtCC,iBAAiB,QACZ,wCAAuC;AAC9C,SAASC,oBAAoB,QAAQ,wBAAuB;AAC5D,SACEC,sBAAsB,EACtBC,uBAAuB,QAGlB,wBAAuB;AAC9B,SAASC,wBAAwB,EAAEC,uBAAuB,QAAQ,aAAY;AAC9E,SAASC,eAAe,QAAQ,mBAAkB;A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sBAAsBA;;IAI1B,sFAAsF;IACtF,uGAAuG;IACvG,qBACE,KAACvD;QAAkBgH,gBAAgB/G;kBAChC6D;;AAGP;AAEA,IAAI4D;AACJ,IAAIC;AACJ,IAAI,CAAClG,QAAQC,GAAG,CAAC0F,SAAS,IAAI,OAAO9G,WAAW,aAAa;IAC3DoH,gBAAgB,IAAIE;IACpBD,sBAAsB,IAAIC;IAE1BC,WAAWC,eAAe,GAAG,SAAUzG,IAAY;QACjD,IAAI,CAACqG,iBAAiB,CAACC,qBAAqB,OAAOI,QAAQC,OAAO;QAClE,IAAIC,MAAMP,cAAcQ,IAAI;QAC5BR,cAAcS,GAAG,CAAC9G;QAClB,IAAIqG,cAAcQ,IAAI,KAAKD,KAAK;YAC9BN,oBAAoBS,OAAO,CAAC,CAACC,KAAOA;QACtC;QACA,4CAA4C;QAC5C,gFAAgF;QAChF,OAAON,QAAQC,OAAO;IACxB;AACF;AAEA,SAASX;IACP,MAAM,GAAGiB,YAAY,GAAGvK,MAAMwK,QAAQ,CAAC;IACvC,MAAMC,qBAAqBd,eAAeQ,QAAQ;IAClDlK,UAAU;QACR,IAAI,CAAC0J,iBAAiB,CAACC,qBAAqB;QAC5C,MAAMc,UAAU,IAAMH,YAAY,CAACI,IAAMA,IAAI;QAC7Cf,oBAAoBQ,GAAG,CAACM;QACxB,IAAID,uBAAuBd,cAAcQ,IAAI,EAAE;YAC7CO;QACF;QACA,OAAO;YACLd,oBAAoBgB,MAAM,CAACF;QAC7B;IACF,GAAG;QAACD;QAAoBF;KAAY;IAEpC,MAAMM,QAAQzI;IACd,OAAO;WAAKuH,iBAAiB,EAAE;KAAE,CAACmB,GAAG,CAAC,CAACxH,MAAMyH,kBAC3C,KAACC;YAECC,KAAI;YACJ3H,MAAM,GAAGA,OAAOuH,OAAO;YACvB,aAAa;YACbK,YAAW;WAJNH;AAUX","ignoreList":[0]} |
@@ -74,10 +74,10 @@ 'use client'; | ||
| * Does not focus the first host descendant. | ||
| */ function InnerScrollAndMaybeFocusHandler(props) { | ||
| */ function InnerScrollHandler(props) { | ||
| const childrenRef = React.useRef(null); | ||
| useLayoutEffect(()=>{ | ||
| const { focusAndScrollRef, cacheNode } = props; | ||
| const scrollRef = focusAndScrollRef.forceScroll ? focusAndScrollRef.scrollRef : cacheNode.scrollRef; | ||
| const { scrollRef: scrollHandlerRef, cacheNode } = props; | ||
| const scrollRef = scrollHandlerRef.forceScroll ? scrollHandlerRef.scrollRef : cacheNode.scrollRef; | ||
| if (scrollRef === null || !scrollRef.current) return; | ||
| let instance = null; | ||
| const hashFragment = focusAndScrollRef.hashFragment; | ||
| const hashFragment = scrollHandlerRef.hashFragment; | ||
| if (hashFragment) { | ||
@@ -89,4 +89,4 @@ instance = getHashFragmentDomNode(hashFragment); | ||
| scrollRef.current = false; | ||
| focusAndScrollRef.onlyHashChange = false; | ||
| focusAndScrollRef.hashFragment = null; | ||
| scrollHandlerRef.onlyHashChange = false; | ||
| scrollHandlerRef.hashFragment = null; | ||
| return; | ||
@@ -153,3 +153,3 @@ } | ||
| dontForceLayout: true, | ||
| onlyHashChange: focusAndScrollRef.onlyHashChange | ||
| onlyHashChange: scrollHandlerRef.onlyHashChange | ||
| }); | ||
@@ -160,4 +160,4 @@ if (!didHandleScroll) { | ||
| // Mutate after scrolling so that it can be read by `disableSmoothScrollDuringRouteTransition` | ||
| focusAndScrollRef.onlyHashChange = false; | ||
| focusAndScrollRef.hashFragment = null; | ||
| scrollHandlerRef.onlyHashChange = false; | ||
| scrollHandlerRef.hashFragment = null; | ||
| }, // Used to run on every commit. We may be able to be smarter about this | ||
@@ -171,3 +171,3 @@ // but be prepared for lots of manual testing. | ||
| } | ||
| function ScrollAndMaybeFocusHandler({ children, cacheNode }) { | ||
| function ScrollHandler({ children, cacheNode }) { | ||
| const context = useContext(GlobalLayoutRouterContext); | ||
@@ -181,4 +181,4 @@ if (!context) { | ||
| } | ||
| return /*#__PURE__*/ _jsx(InnerScrollAndMaybeFocusHandler, { | ||
| focusAndScrollRef: context.focusAndScrollRef, | ||
| return /*#__PURE__*/ _jsx(InnerScrollHandler, { | ||
| scrollRef: context.scrollRef, | ||
| cacheNode: cacheNode, | ||
@@ -455,3 +455,3 @@ children: children | ||
| const debugNameToDisplay = isVirtual ? undefined : debugNameContext; | ||
| let templateValue = /*#__PURE__*/ _jsxs(ScrollAndMaybeFocusHandler, { | ||
| let templateValue = /*#__PURE__*/ _jsxs(ScrollHandler, { | ||
| cacheNode: cacheNode, | ||
@@ -458,0 +458,0 @@ children: [ |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/client/components/layout-router.tsx"],"sourcesContent":["'use client'\n\nimport type { CacheNode } from '../../shared/lib/app-router-types'\nimport type { LoadingModuleData } from '../../shared/lib/app-router-types'\nimport type {\n FlightRouterState,\n FlightSegmentPath,\n Segment,\n} from '../../shared/lib/app-router-types'\nimport type { ErrorComponent } from './error-boundary'\nimport type { FocusAndScrollRef } from './router-reducer/router-reducer-types'\n\nimport React, {\n Activity,\n Fragment,\n useContext,\n use,\n Suspense,\n useDeferredValue,\n useLayoutEffect,\n type FragmentInstance,\n type JSX,\n type ActivityProps,\n} from 'react'\nimport {\n LayoutRouterContext,\n GlobalLayoutRouterContext,\n TemplateContext,\n} from '../../shared/lib/app-router-context.shared-runtime'\nimport { unresolvedThenable } from './unresolved-thenable'\nimport { ErrorBoundary } from './error-boundary'\nimport { disableSmoothScrollDuringRouteTransition } from '../../shared/lib/router/utils/disable-smooth-scroll'\nimport { RedirectBoundary } from './redirect-boundary'\nimport { HTTPAccessFallbackBoundary } from './http-access-fallback/error-boundary'\nimport {\n InstantValidationBoundaryContext,\n RenderValidationBoundaryAtThisLevel,\n} from './instant-validation/boundary'\nimport { createRouterCacheKey } from './router-reducer/create-router-cache-key'\nimport {\n useRouterBFCache,\n type RouterBFCacheEntry,\n} from './bfcache-state-manager'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport {\n NavigationPromisesContext,\n type NavigationPromises,\n} from '../../shared/lib/hooks-client-context.shared-runtime'\nimport { getParamValueFromCacheKey } from '../route-params'\nimport type { Params } from '../../server/request/params'\nimport { isDeferredRsc } from './router-reducer/ppr-navigations'\n\nconst enum ScrollTargetState {\n NoClientRects,\n InViewport,\n OutOfViewport,\n}\n\n/**\n * Resolve the root scroll padding used by the viewport check.\n *\n * Computed lengths serialize as pixels, but percentages remain relative to\n * the scrollport. Preserve the existing behavior for values that still\n * contain unresolved CSS math.\n */\nfunction getScrollPaddingTopInPixels(\n htmlElement: HTMLElement,\n viewportHeight: number\n): number {\n const scrollPaddingTop = getComputedStyle(htmlElement).scrollPaddingTop\n const value = Number.parseFloat(scrollPaddingTop)\n\n if (!Number.isFinite(value) || value < 0) {\n return 0\n }\n\n if (scrollPaddingTop.endsWith('px')) {\n return value\n }\n\n if (scrollPaddingTop.endsWith('%')) {\n return (value / 100) * viewportHeight\n }\n\n return 0\n}\n\n/**\n * Check where the top corner of the HTMLElement is relative to the usable\n * viewport.\n *\n * Scroll padding is resolved lazily so an empty Fragment does not trigger a\n * computed style read. The caller caches the value for the second check.\n */\nfunction getScrollTargetState(\n instance: HTMLElement | FragmentInstance,\n viewportHeight: number,\n getScrollPaddingTop: () => number\n): ScrollTargetState {\n const rects = instance.getClientRects()\n if (rects.length === 0) {\n return ScrollTargetState.NoClientRects\n }\n let elementTop = Number.POSITIVE_INFINITY\n for (let i = 0; i < rects.length; i++) {\n const rect = rects[i]\n if (rect.top < elementTop) {\n elementTop = rect.top\n }\n }\n return elementTop >= getScrollPaddingTop() && elementTop <= viewportHeight\n ? ScrollTargetState.InViewport\n : ScrollTargetState.OutOfViewport\n}\n\n/**\n * Find the DOM node for a hash fragment.\n * If `top` the page has to scroll to the top of the page. This mirrors the browser's behavior.\n * If the hash fragment is an id, the page has to scroll to the element with that id.\n * If the hash fragment is a name, the page has to scroll to the first element with that name.\n */\nfunction getHashFragmentDomNode(hashFragment: string) {\n // If the hash fragment is `top` the page has to scroll to the top of the page.\n if (hashFragment === 'top') {\n return document.body\n }\n\n // If the hash fragment is an id, the page has to scroll to the element with that id.\n return (\n document.getElementById(hashFragment) ??\n // If the hash fragment is a name, the page has to scroll to the first element with that name.\n document.getElementsByName(hashFragment)[0] ??\n null\n )\n}\ninterface ScrollAndMaybeFocusHandlerProps {\n focusAndScrollRef: FocusAndScrollRef\n children: React.ReactNode\n cacheNode: CacheNode\n}\n\n/**\n * Uses Fragment refs for scrolling.\n * Does not focus the first host descendant.\n */\nfunction InnerScrollAndMaybeFocusHandler(\n props: ScrollAndMaybeFocusHandlerProps\n) {\n const childrenRef = React.useRef<FragmentInstance>(null)\n\n useLayoutEffect(\n () => {\n const { focusAndScrollRef, cacheNode } = props\n\n const scrollRef = focusAndScrollRef.forceScroll\n ? focusAndScrollRef.scrollRef\n : cacheNode.scrollRef\n if (scrollRef === null || !scrollRef.current) return\n\n let instance: FragmentInstance | HTMLElement | null = null\n const hashFragment = focusAndScrollRef.hashFragment\n\n if (hashFragment) {\n instance = getHashFragmentDomNode(hashFragment)\n if (instance === null) {\n // A missing hash target is still a handled scroll intent. Do not\n // fall back to the route Fragment or leave the intent pending.\n scrollRef.current = false\n focusAndScrollRef.onlyHashChange = false\n focusAndScrollRef.hashFragment = null\n return\n }\n } else {\n instance = childrenRef.current\n }\n\n // If there is no DOM node this layout-router level is skipped. It'll be handled higher-up in the tree.\n if (instance === null) {\n return\n }\n\n let didHandleScroll = false\n\n disableSmoothScrollDuringRouteTransition(\n () => {\n const htmlElement = document.documentElement\n let viewportHeight: number | null = null\n let initialTargetState: ScrollTargetState | null = null\n let scrollPaddingTop: number | null = null\n const getScrollPaddingTop = () => {\n if (scrollPaddingTop === null) {\n // Reuse the style and layout update from the geometry read.\n scrollPaddingTop = getScrollPaddingTopInPixels(\n htmlElement,\n viewportHeight!\n )\n }\n return scrollPaddingTop\n }\n\n if (!hashFragment) {\n // Store the current viewport height because reading `clientHeight` causes a reflow,\n // and it won't change during this function.\n viewportHeight = htmlElement.clientHeight\n initialTargetState = getScrollTargetState(\n instance,\n viewportHeight,\n getScrollPaddingTop\n )\n\n // An empty Fragment is not a scroll target. In particular, avoid\n // React's sibling fallback and leave the scroll signal available\n // for another changed segment.\n if (initialTargetState === ScrollTargetState.NoClientRects) {\n return\n }\n }\n\n didHandleScroll = true\n\n // Mark as scrolled so no other segment scrolls for this navigation.\n scrollRef.current = false\n\n // This handler intentionally leaves focus untouched; resetting focus on\n // navigation is deferred.\n\n // In case of hash scroll, we only need to scroll the element into view\n if (hashFragment) {\n instance.scrollIntoView()\n\n return\n }\n\n // If the element's top edge is already in the viewport, exit early.\n if (initialTargetState === ScrollTargetState.InViewport) {\n return\n }\n\n // Otherwise, try scrolling go the top of the document to be backward compatible with pages\n // scrollIntoView() called on `<html/>` element scrolls horizontally on chrome and firefox (that shouldn't happen)\n // We could use it to scroll horizontally following RTL but that also seems to be broken - it will always scroll left\n // scrollLeft = 0 also seems to ignore RTL and manually checking for RTL is too much hassle so we will scroll just vertically\n htmlElement.scrollTop = 0\n\n // Scroll to domNode if domNode is not in viewport when scrolled to top of document\n if (\n getScrollTargetState(\n instance,\n viewportHeight!,\n getScrollPaddingTop\n ) === ScrollTargetState.OutOfViewport\n ) {\n // Scroll into view doesn't scroll horizontally by default when not needed\n instance.scrollIntoView()\n }\n },\n {\n // We will force layout by querying domNode position\n dontForceLayout: true,\n onlyHashChange: focusAndScrollRef.onlyHashChange,\n }\n )\n\n if (!didHandleScroll) {\n return\n }\n\n // Mutate after scrolling so that it can be read by `disableSmoothScrollDuringRouteTransition`\n focusAndScrollRef.onlyHashChange = false\n focusAndScrollRef.hashFragment = null\n },\n // Used to run on every commit. We may be able to be smarter about this\n // but be prepared for lots of manual testing.\n undefined\n )\n\n return <Fragment ref={childrenRef}>{props.children}</Fragment>\n}\n\nfunction ScrollAndMaybeFocusHandler({\n children,\n cacheNode,\n}: {\n children: React.ReactNode\n cacheNode: CacheNode\n}) {\n const context = useContext(GlobalLayoutRouterContext)\n if (!context) {\n throw new Error('invariant global layout router not mounted')\n }\n\n return (\n <InnerScrollAndMaybeFocusHandler\n focusAndScrollRef={context.focusAndScrollRef}\n cacheNode={cacheNode}\n >\n {children}\n </InnerScrollAndMaybeFocusHandler>\n )\n}\n\n/**\n * InnerLayoutRouter handles rendering the provided segment based on the cache.\n */\nfunction InnerLayoutRouter({\n tree,\n segmentPath,\n debugNameContext,\n cacheNode: maybeCacheNode,\n params,\n url,\n isActive,\n}: {\n tree: FlightRouterState\n segmentPath: FlightSegmentPath\n debugNameContext: string\n cacheNode: CacheNode | null\n params: Params\n url: string\n isActive: boolean\n}) {\n const context = useContext(GlobalLayoutRouterContext)\n const parentNavPromises = useContext(NavigationPromisesContext)\n\n if (!context) {\n throw new Error('invariant global layout router not mounted')\n }\n\n const cacheNode =\n maybeCacheNode !== null\n ? maybeCacheNode\n : // This segment is not in the cache. Suspend indefinitely.\n //\n // This should only be reachable for inactive/hidden segments, during\n // prerendering The active segment should always be consistent with the\n // CacheNode tree. Regardless, if we don't have a matching CacheNode, we\n // must suspend rather than render nothing, to prevent showing an\n // inconsistent route.\n\n (use(unresolvedThenable) as never)\n\n // `rsc` represents the renderable node for this segment.\n\n // If this segment has a `prefetchRsc`, it's the statically prefetched data.\n // We should use that on initial render instead of `rsc`. Then we'll switch\n // to `rsc` when the dynamic response streams in.\n //\n // If no prefetch data is available, then we go straight to rendering `rsc`.\n const resolvedPrefetchRsc =\n cacheNode.prefetchRsc !== null ? cacheNode.prefetchRsc : cacheNode.rsc\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 const rsc: any = useDeferredValue(cacheNode.rsc, resolvedPrefetchRsc)\n\n // `rsc` is either a React node or a promise for a React node, except we\n // special case `null` to represent that this segment's data is missing. If\n // it's a promise, we need to unwrap it so we can determine whether or not the\n // data is missing.\n let resolvedRsc: React.ReactNode\n if (isDeferredRsc(rsc)) {\n const unwrappedRsc = use(rsc)\n if (unwrappedRsc === null) {\n // If the promise was resolved to `null`, it means the data for this\n // segment was not returned by the server. Suspend indefinitely. When this\n // happens, the router is responsible for triggering a new state update to\n // un-suspend this segment.\n use(unresolvedThenable) as never\n }\n resolvedRsc = unwrappedRsc\n } else {\n // This is not a deferred RSC promise. Don't need to unwrap it.\n if (rsc === null) {\n use(unresolvedThenable) as never\n }\n resolvedRsc = rsc\n }\n\n // In dev, we create a NavigationPromisesContext containing the instrumented promises that provide\n // `useSelectedLayoutSegment` and `useSelectedLayoutSegments`.\n // Promises are cached outside of render to survive suspense retries.\n let navigationPromises: NavigationPromises | null = null\n if (process.env.NODE_ENV !== 'production') {\n const { createNestedLayoutNavigationPromises } =\n require('./navigation-devtools') as typeof import('./navigation-devtools')\n\n navigationPromises = createNestedLayoutNavigationPromises(\n tree,\n parentNavPromises\n )\n }\n\n let children = resolvedRsc\n\n if (navigationPromises) {\n children = (\n <NavigationPromisesContext.Provider value={navigationPromises}>\n {resolvedRsc}\n </NavigationPromisesContext.Provider>\n )\n }\n\n children = (\n // The layout router context narrows down tree and childNodes at each level.\n <LayoutRouterContext.Provider\n value={{\n parentTree: tree,\n parentCacheNode: cacheNode,\n parentSegmentPath: segmentPath,\n parentParams: params,\n // This is always set to null as we enter a child segment. It's\n // populated by LoadingBoundaryProvider the next time we reach a\n // loading boundary.\n parentLoadingData: null,\n debugNameContext: debugNameContext,\n\n // TODO-APP: overriding of url for parallel routes\n url: url,\n isActive: isActive,\n }}\n >\n {children}\n </LayoutRouterContext.Provider>\n )\n\n return children\n}\n\nexport function LoadingBoundaryProvider({\n loading,\n children,\n}: {\n loading: LoadingModuleData\n children: React.ReactNode\n}) {\n // Provides the data needed to render a loading.tsx boundary, via context.\n //\n // loading.tsx creates a Suspense boundary around each of a layout's child\n // slots. (Might be bit confusing to think about the data flow, but: if\n // loading.tsx and layout.tsx are in the same directory, they are assigned\n // to the same CacheNode.)\n //\n // This provider component does not render the Suspense boundary directly;\n // that's handled by LoadingBoundary.\n //\n // TODO: For simplicity, we should combine this provider with LoadingBoundary\n // and render the Suspense boundary directly. The only real benefit of doing\n // it separately is so that when there are multiple parallel routes, we only\n // send the boundary data once, rather than once per child. But that's a\n // negligible benefit and can be achieved via caching instead.\n const parentContext = use(LayoutRouterContext)\n if (parentContext === null) {\n return children\n }\n // All values except for parentLoadingData are the same as the parent context.\n return (\n <LayoutRouterContext.Provider\n value={{\n parentTree: parentContext.parentTree,\n parentCacheNode: parentContext.parentCacheNode,\n parentSegmentPath: parentContext.parentSegmentPath,\n parentParams: parentContext.parentParams,\n parentLoadingData: loading,\n debugNameContext: parentContext.debugNameContext,\n url: parentContext.url,\n isActive: parentContext.isActive,\n }}\n >\n {children}\n </LayoutRouterContext.Provider>\n )\n}\n\n/**\n * Renders suspense boundary with the provided \"loading\" property as the fallback.\n * If no loading property is provided it renders the children without a suspense boundary.\n */\nfunction LoadingBoundary({\n name,\n loading,\n children,\n}: {\n name: ActivityProps['name']\n loading: LoadingModuleData | null\n children: React.ReactNode\n}): JSX.Element {\n // TODO: For LoadingBoundary, and the other built-in boundary types, don't\n // wrap in an extra function component if no user-defined boundary is\n // provided. In other words, inline this conditional wrapping logic into\n // the parent component. More efficient and keeps unnecessary junk out of\n // the component stack.\n if (loading !== null) {\n const loadingRsc = loading[0]\n const loadingStyles = loading[1]\n const loadingScripts = loading[2]\n return (\n <Suspense\n name={name}\n fallback={\n <>\n {loadingStyles}\n {loadingScripts}\n {loadingRsc}\n </>\n }\n >\n {children}\n </Suspense>\n )\n }\n\n return <>{children}</>\n}\n\n/**\n * OuterLayoutRouter handles the current segment as well as <Offscreen> rendering of other segments.\n * It can be rendered next to each other with a different `parallelRouterKey`, allowing for Parallel routes.\n */\nexport default function OuterLayoutRouter({\n parallelRouterKey,\n error,\n errorStyles,\n errorScripts,\n templateStyles,\n templateScripts,\n template,\n notFound,\n forbidden,\n unauthorized,\n segmentViewBoundaries,\n}: {\n parallelRouterKey: string\n error: ErrorComponent | undefined\n errorStyles: React.ReactNode | undefined\n errorScripts: React.ReactNode | undefined\n templateStyles: React.ReactNode | undefined\n templateScripts: React.ReactNode | undefined\n template: React.ReactNode\n notFound: React.ReactNode | undefined\n forbidden: React.ReactNode | undefined\n unauthorized: React.ReactNode | undefined\n segmentViewBoundaries?: React.ReactNode\n}) {\n const context = useContext(LayoutRouterContext)\n if (!context) {\n throw new Error('invariant expected layout router to be mounted')\n }\n\n const {\n parentTree,\n parentCacheNode,\n parentSegmentPath,\n parentParams,\n parentLoadingData,\n url,\n isActive,\n debugNameContext,\n } = context\n\n // Get the CacheNode for this segment by reading it from the parent segment's\n // child map.\n const parentTreeSegment = parentTree[0]\n const segmentPath =\n parentSegmentPath === null\n ? // TODO: The root segment value is currently omitted from the segment\n // path. This has led to a bunch of special cases scattered throughout\n // the code. We should clean this up.\n [parallelRouterKey]\n : parentSegmentPath.concat([parentTreeSegment, parallelRouterKey])\n\n // The \"state\" key of a segment is the one passed to React — it represents the\n // identity of the UI tree. Whenever the state key changes, the tree is\n // recreated and the state is reset. In the App Router model, search params do\n // not cause state to be lost, so two segments with the same segment path but\n // different search params should have the same state key.\n //\n // The \"cache\" key of a segment, however, *does* include the search params, if\n // it's possible that the segment accessed the search params on the server.\n // (This only applies to page segments; layout segments cannot access search\n // params on the server.)\n const activeTree = parentTree[1][parallelRouterKey]\n const maybeParentSlots = parentCacheNode.slots\n if (activeTree === undefined || maybeParentSlots === null) {\n // Could not find a matching segment. The client tree is inconsistent with\n // the server tree. Suspend indefinitely; the router will have already\n // detected the inconsistency when handling the server response, and\n // triggered a refresh of the page to recover.\n use(unresolvedThenable) as never\n }\n\n let maybeValidationBoundaryId: string | null = null\n if (typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS) {\n maybeValidationBoundaryId = use(InstantValidationBoundaryContext)\n }\n\n const activeSegment = activeTree[0]\n const activeCacheNode = maybeParentSlots![parallelRouterKey] ?? null\n const activeStateKey = createRouterCacheKey(activeSegment, true) // no search params\n\n // At each level of the route tree, not only do we render the currently\n // active segment — we also render the last N segments that were active at\n // this level inside a hidden <Activity> boundary, to preserve their state\n // if or when the user navigates to them again.\n //\n // bfcacheEntry is a linked list of FlightRouterStates.\n let bfcacheEntry: RouterBFCacheEntry | null = useRouterBFCache(\n activeTree,\n activeCacheNode,\n activeStateKey\n )\n let children: Array<React.ReactNode> = []\n do {\n const tree = bfcacheEntry.tree\n const cacheNode = bfcacheEntry.cacheNode\n const stateKey = bfcacheEntry.stateKey\n const segment = tree[0]\n\n /*\n - Error boundary\n - Only renders error boundary if error component is provided.\n - Rendered for each segment to ensure they have their own error state.\n - When gracefully degrade for bots, skip rendering error boundary.\n - Loading boundary\n - Only renders suspense boundary if loading components is provided.\n - Rendered for each segment to ensure they have their own loading state.\n - Passed to the router during rendering to ensure it can be immediately rendered when suspending on a Flight fetch.\n */\n\n let segmentBoundaryTriggerNode: React.ReactNode = null\n let segmentViewStateNode: React.ReactNode = null\n if (process.env.NODE_ENV !== 'production') {\n const { SegmentBoundaryTriggerNode, SegmentViewStateNode } =\n require('../../next-devtools/userspace/app/segment-explorer-node') as typeof import('../../next-devtools/userspace/app/segment-explorer-node')\n\n const pagePrefix = normalizeAppPath(url)\n segmentViewStateNode = (\n <SegmentViewStateNode key={pagePrefix} page={pagePrefix} />\n )\n\n segmentBoundaryTriggerNode = (\n <>\n <SegmentBoundaryTriggerNode />\n </>\n )\n }\n\n let params = parentParams\n if (Array.isArray(segment)) {\n // This segment contains a route param. Accumulate these as we traverse\n // down the router tree. The result represents the set of params that\n // the layout/page components are permitted to access below this point.\n const paramName = segment[0]\n const paramCacheKey = segment[1]\n const paramType = segment[2]\n const paramValue = getParamValueFromCacheKey(paramCacheKey, paramType)\n if (paramValue !== null) {\n params = {\n ...parentParams,\n [paramName]: paramValue,\n }\n }\n }\n\n const debugName = getBoundaryDebugNameFromSegment(segment)\n // `debugNameContext` represents the nearest non-\"virtual\" parent segment.\n // `getBoundaryDebugNameFromSegment` returns undefined for virtual segments.\n // So if `debugName` is undefined, the context is passed through unchanged.\n const childDebugNameContext = debugName ?? debugNameContext\n\n // In practical terms, clicking this name in the Suspense DevTools\n // should select the child slots of that layout.\n //\n // So the name we apply to the Activity boundary is actually based on\n // the nearest parent segments.\n //\n // We skip over \"virtual\" parents, i.e. ones inserted by Next.js that\n // don't correspond to application-defined code.\n const isVirtual = debugName === undefined\n const debugNameToDisplay = isVirtual ? undefined : debugNameContext\n\n let templateValue = (\n <ScrollAndMaybeFocusHandler cacheNode={cacheNode}>\n <ErrorBoundary\n errorComponent={error}\n errorStyles={errorStyles}\n errorScripts={errorScripts}\n >\n <LoadingBoundary\n name={debugNameToDisplay}\n // TODO: The loading module data for a segment is stored on the\n // parent, then applied to each of that parent segment's\n // parallel route slots. In the simple case where there's only\n // one parallel route (the `children` slot), this is no\n // different from if the loading module data were stored on the\n // child directly. But I'm not sure this actually makes sense\n // when there are multiple parallel routes. It's not a huge\n // issue because you always have the option to define a narrower\n // loading boundary for a particular slot. But this sort of\n // smells like an implementation accident to me.\n loading={parentLoadingData}\n >\n <HTTPAccessFallbackBoundary\n notFound={notFound}\n forbidden={forbidden}\n unauthorized={unauthorized}\n >\n <RedirectBoundary>\n <InnerLayoutRouter\n url={url}\n tree={tree}\n params={params}\n cacheNode={cacheNode}\n segmentPath={segmentPath}\n debugNameContext={childDebugNameContext}\n isActive={isActive && stateKey === activeStateKey}\n />\n {segmentBoundaryTriggerNode}\n </RedirectBoundary>\n </HTTPAccessFallbackBoundary>\n </LoadingBoundary>\n </ErrorBoundary>\n {segmentViewStateNode}\n </ScrollAndMaybeFocusHandler>\n )\n\n if (\n typeof window === 'undefined' &&\n process.env.__NEXT_CACHE_COMPONENTS &&\n typeof maybeValidationBoundaryId === 'string'\n ) {\n templateValue = (\n <RenderValidationBoundaryAtThisLevel id={maybeValidationBoundaryId}>\n {templateValue}\n </RenderValidationBoundaryAtThisLevel>\n )\n }\n\n let child = (\n <TemplateContext.Provider key={stateKey} value={templateValue}>\n {templateStyles}\n {templateScripts}\n {template}\n </TemplateContext.Provider>\n )\n\n if (process.env.NODE_ENV !== 'production') {\n const { SegmentStateProvider } =\n require('../../next-devtools/userspace/app/segment-explorer-node') as typeof import('../../next-devtools/userspace/app/segment-explorer-node')\n\n child = (\n <SegmentStateProvider key={stateKey}>\n {child}\n {segmentViewBoundaries}\n </SegmentStateProvider>\n )\n }\n\n if (process.env.__NEXT_CACHE_COMPONENTS) {\n child = (\n <Activity\n name={debugNameToDisplay}\n key={stateKey}\n mode={stateKey === activeStateKey ? 'visible' : 'hidden'}\n >\n {child}\n </Activity>\n )\n }\n\n children.push(child)\n\n bfcacheEntry = bfcacheEntry.next\n } while (bfcacheEntry !== null)\n\n return children\n}\n\nfunction getBoundaryDebugNameFromSegment(segment: Segment): string | undefined {\n if (segment === '/') {\n // Reached the root\n return '/'\n }\n if (typeof segment === 'string') {\n if (isVirtualLayout(segment)) {\n return undefined\n } else {\n return segment + '/'\n }\n }\n const paramCacheKey = segment[1]\n return paramCacheKey + '/'\n}\n\nfunction isVirtualLayout(segment: string): boolean {\n return (\n // This is inserted by the loader. Uses double-underscore convention\n // (like __PAGE__ and __DEFAULT__) to avoid collisions with\n // user-defined route groups.\n segment === '(__SLOT__)'\n )\n}\n"],"names":["React","Activity","Fragment","useContext","use","Suspense","useDeferredValue","useLayoutEffect","LayoutRouterContext","GlobalLayoutRouterContext","TemplateContext","unresolvedThenable","ErrorBoundary","disableSmoothScrollDuringRouteTransition","RedirectBoundary","HTTPAccessFallbackBoundary","InstantValidationBoundaryContext","RenderValidationBoundaryAtThisLevel","createRouterCacheKey","useRouterBFCache","normalizeAppPath","NavigationPromisesContext","getParamValueFromCacheKey","isDeferredRsc","getScrollPaddingTopInPixels","htmlElement","viewportHeight","scrollPaddingTop","getComputedStyle","value","Number","parseFloat","isFinite","endsWith","getScrollTargetState","instance","getScrollPaddingTop","rects","getClientRects","length","elementTop","POSITIVE_INFINITY","i","rect","top","getHashFragmentDomNode","hashFragment","document","body","getElementById","getElementsByName","InnerScrollAndMaybeFocusHandler","props","childrenRef","useRef","focusAndScrollRef","cacheNode","scrollRef","forceScroll","current","onlyHashChange","didHandleScroll","documentElement","initialTargetState","clientHeight","scrollIntoView","scrollTop","dontForceLayout","undefined","ref","children","ScrollAndMaybeFocusHandler","context","Error","InnerLayoutRouter","tree","segmentPath","debugNameContext","maybeCacheNode","params","url","isActive","parentNavPromises","resolvedPrefetchRsc","prefetchRsc","rsc","resolvedRsc","unwrappedRsc","navigationPromises","process","env","NODE_ENV","createNestedLayoutNavigationPromises","require","Provider","parentTree","parentCacheNode","parentSegmentPath","parentParams","parentLoadingData","LoadingBoundaryProvider","loading","parentContext","LoadingBoundary","name","loadingRsc","loadingStyles","loadingScripts","fallback","OuterLayoutRouter","parallelRouterKey","error","errorStyles","errorScripts","templateStyles","templateScripts","template","notFound","forbidden","unauthorized","segmentViewBoundaries","parentTreeSegment","concat","activeTree","maybeParentSlots","slots","maybeValidationBoundaryId","window","__NEXT_CACHE_COMPONENTS","activeSegment","activeCacheNode","activeStateKey","bfcacheEntry","stateKey","segment","segmentBoundaryTriggerNode","segmentViewStateNode","SegmentBoundaryTriggerNode","SegmentViewStateNode","pagePrefix","page","Array","isArray","paramName","paramCacheKey","paramType","paramValue","debugName","getBoundaryDebugNameFromSegment","childDebugNameContext","isVirtual","debugNameToDisplay","templateValue","errorComponent","id","child","SegmentStateProvider","mode","push","next","isVirtualLayout"],"mappings":"AAAA;;AAYA,OAAOA,SACLC,QAAQ,EACRC,QAAQ,EACRC,UAAU,EACVC,GAAG,EACHC,QAAQ,EACRC,gBAAgB,EAChBC,eAAe,QAIV,QAAO;AACd,SACEC,mBAAmB,EACnBC,yBAAyB,EACzBC,eAAe,QACV,qDAAoD;AAC3D,SAASC,kBAAkB,QAAQ,wBAAuB;AAC1D,SAASC,aAAa,QAAQ,mBAAkB;AAChD,SAASC,wCAAwC,QAAQ,sDAAqD;AAC9G,SAASC,gBAAgB,QAAQ,sBAAqB;AACtD,SAASC,0BAA0B,QAAQ,wCAAuC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EAAE;YACvC2B,sBACE,KAAC1J;gBACCuG,MAAM+C;gBAENM,MAAMxB,aAAaF,iBAAiB,YAAY;0BAE/CwB;eAHItB;QAMX;QAEA/D,SAASwF,IAAI,CAACH;QAEdvB,eAAeA,aAAa2B,IAAI;IAClC,QAAS3B,iBAAiB,MAAK;IAE/B,OAAO9D;AACT;AAEA,SAAS8E,gCAAgCd,OAAgB;IACvD,IAAIA,YAAY,KAAK;QACnB,mBAAmB;QACnB,OAAO;IACT;IACA,IAAI,OAAOA,YAAY,UAAU;QAC/B,IAAI0B,gBAAgB1B,UAAU;YAC5B,OAAOlE;QACT,OAAO;YACL,OAAOkE,UAAU;QACnB;IACF;IACA,MAAMU,gBAAgBV,OAAO,CAAC,EAAE;IAChC,OAAOU,gBAAgB;AACzB;AAEA,SAASgB,gBAAgB1B,OAAe;IACtC,OACE,oEAAoE;IACpE,2DAA2D;IAC3D,6BAA6B;IAC7BA,YAAY;AAEhB","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/client/components/layout-router.tsx"],"sourcesContent":["'use client'\n\nimport type { CacheNode } from '../../shared/lib/app-router-types'\nimport type { LoadingModuleData } from '../../shared/lib/app-router-types'\nimport type {\n FlightRouterState,\n FlightSegmentPath,\n Segment,\n} from '../../shared/lib/app-router-types'\nimport type { ErrorComponent } from './error-boundary'\nimport type { ScrollHandlerRef } from './router-reducer/router-reducer-types'\n\nimport React, {\n Activity,\n Fragment,\n useContext,\n use,\n Suspense,\n useDeferredValue,\n useLayoutEffect,\n type FragmentInstance,\n type JSX,\n type ActivityProps,\n} from 'react'\nimport {\n LayoutRouterContext,\n GlobalLayoutRouterContext,\n TemplateContext,\n} from '../../shared/lib/app-router-context.shared-runtime'\nimport { unresolvedThenable } from './unresolved-thenable'\nimport { ErrorBoundary } from './error-boundary'\nimport { disableSmoothScrollDuringRouteTransition } from '../../shared/lib/router/utils/disable-smooth-scroll'\nimport { RedirectBoundary } from './redirect-boundary'\nimport { HTTPAccessFallbackBoundary } from './http-access-fallback/error-boundary'\nimport {\n InstantValidationBoundaryContext,\n RenderValidationBoundaryAtThisLevel,\n} from './instant-validation/boundary'\nimport { createRouterCacheKey } from './router-reducer/create-router-cache-key'\nimport {\n useRouterBFCache,\n type RouterBFCacheEntry,\n} from './bfcache-state-manager'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport {\n NavigationPromisesContext,\n type NavigationPromises,\n} from '../../shared/lib/hooks-client-context.shared-runtime'\nimport { getParamValueFromCacheKey } from '../route-params'\nimport type { Params } from '../../server/request/params'\nimport { isDeferredRsc } from './router-reducer/ppr-navigations'\n\nconst enum ScrollTargetState {\n NoClientRects,\n InViewport,\n OutOfViewport,\n}\n\n/**\n * Resolve the root scroll padding used by the viewport check.\n *\n * Computed lengths serialize as pixels, but percentages remain relative to\n * the scrollport. Preserve the existing behavior for values that still\n * contain unresolved CSS math.\n */\nfunction getScrollPaddingTopInPixels(\n htmlElement: HTMLElement,\n viewportHeight: number\n): number {\n const scrollPaddingTop = getComputedStyle(htmlElement).scrollPaddingTop\n const value = Number.parseFloat(scrollPaddingTop)\n\n if (!Number.isFinite(value) || value < 0) {\n return 0\n }\n\n if (scrollPaddingTop.endsWith('px')) {\n return value\n }\n\n if (scrollPaddingTop.endsWith('%')) {\n return (value / 100) * viewportHeight\n }\n\n return 0\n}\n\n/**\n * Check where the top corner of the HTMLElement is relative to the usable\n * viewport.\n *\n * Scroll padding is resolved lazily so an empty Fragment does not trigger a\n * computed style read. The caller caches the value for the second check.\n */\nfunction getScrollTargetState(\n instance: HTMLElement | FragmentInstance,\n viewportHeight: number,\n getScrollPaddingTop: () => number\n): ScrollTargetState {\n const rects = instance.getClientRects()\n if (rects.length === 0) {\n return ScrollTargetState.NoClientRects\n }\n let elementTop = Number.POSITIVE_INFINITY\n for (let i = 0; i < rects.length; i++) {\n const rect = rects[i]\n if (rect.top < elementTop) {\n elementTop = rect.top\n }\n }\n return elementTop >= getScrollPaddingTop() && elementTop <= viewportHeight\n ? ScrollTargetState.InViewport\n : ScrollTargetState.OutOfViewport\n}\n\n/**\n * Find the DOM node for a hash fragment.\n * If `top` the page has to scroll to the top of the page. This mirrors the browser's behavior.\n * If the hash fragment is an id, the page has to scroll to the element with that id.\n * If the hash fragment is a name, the page has to scroll to the first element with that name.\n */\nfunction getHashFragmentDomNode(hashFragment: string) {\n // If the hash fragment is `top` the page has to scroll to the top of the page.\n if (hashFragment === 'top') {\n return document.body\n }\n\n // If the hash fragment is an id, the page has to scroll to the element with that id.\n return (\n document.getElementById(hashFragment) ??\n // If the hash fragment is a name, the page has to scroll to the first element with that name.\n document.getElementsByName(hashFragment)[0] ??\n null\n )\n}\ninterface ScrollHandlerProps {\n scrollRef: ScrollHandlerRef\n children: React.ReactNode\n cacheNode: CacheNode\n}\n\n/**\n * Uses Fragment refs for scrolling.\n * Does not focus the first host descendant.\n */\nfunction InnerScrollHandler(props: ScrollHandlerProps) {\n const childrenRef = React.useRef<FragmentInstance>(null)\n\n useLayoutEffect(\n () => {\n const { scrollRef: scrollHandlerRef, cacheNode } = props\n\n const scrollRef = scrollHandlerRef.forceScroll\n ? scrollHandlerRef.scrollRef\n : cacheNode.scrollRef\n if (scrollRef === null || !scrollRef.current) return\n\n let instance: FragmentInstance | HTMLElement | null = null\n const hashFragment = scrollHandlerRef.hashFragment\n\n if (hashFragment) {\n instance = getHashFragmentDomNode(hashFragment)\n if (instance === null) {\n // A missing hash target is still a handled scroll intent. Do not\n // fall back to the route Fragment or leave the intent pending.\n scrollRef.current = false\n scrollHandlerRef.onlyHashChange = false\n scrollHandlerRef.hashFragment = null\n return\n }\n } else {\n instance = childrenRef.current\n }\n\n // If there is no DOM node this layout-router level is skipped. It'll be handled higher-up in the tree.\n if (instance === null) {\n return\n }\n\n let didHandleScroll = false\n\n disableSmoothScrollDuringRouteTransition(\n () => {\n const htmlElement = document.documentElement\n let viewportHeight: number | null = null\n let initialTargetState: ScrollTargetState | null = null\n let scrollPaddingTop: number | null = null\n const getScrollPaddingTop = () => {\n if (scrollPaddingTop === null) {\n // Reuse the style and layout update from the geometry read.\n scrollPaddingTop = getScrollPaddingTopInPixels(\n htmlElement,\n viewportHeight!\n )\n }\n return scrollPaddingTop\n }\n\n if (!hashFragment) {\n // Store the current viewport height because reading `clientHeight` causes a reflow,\n // and it won't change during this function.\n viewportHeight = htmlElement.clientHeight\n initialTargetState = getScrollTargetState(\n instance,\n viewportHeight,\n getScrollPaddingTop\n )\n\n // An empty Fragment is not a scroll target. In particular, avoid\n // React's sibling fallback and leave the scroll signal available\n // for another changed segment.\n if (initialTargetState === ScrollTargetState.NoClientRects) {\n return\n }\n }\n\n didHandleScroll = true\n\n // Mark as scrolled so no other segment scrolls for this navigation.\n scrollRef.current = false\n\n // This handler intentionally leaves focus untouched; resetting focus on\n // navigation is deferred.\n\n // In case of hash scroll, we only need to scroll the element into view\n if (hashFragment) {\n instance.scrollIntoView()\n\n return\n }\n\n // If the element's top edge is already in the viewport, exit early.\n if (initialTargetState === ScrollTargetState.InViewport) {\n return\n }\n\n // Otherwise, try scrolling go the top of the document to be backward compatible with pages\n // scrollIntoView() called on `<html/>` element scrolls horizontally on chrome and firefox (that shouldn't happen)\n // We could use it to scroll horizontally following RTL but that also seems to be broken - it will always scroll left\n // scrollLeft = 0 also seems to ignore RTL and manually checking for RTL is too much hassle so we will scroll just vertically\n htmlElement.scrollTop = 0\n\n // Scroll to domNode if domNode is not in viewport when scrolled to top of document\n if (\n getScrollTargetState(\n instance,\n viewportHeight!,\n getScrollPaddingTop\n ) === ScrollTargetState.OutOfViewport\n ) {\n // Scroll into view doesn't scroll horizontally by default when not needed\n instance.scrollIntoView()\n }\n },\n {\n // We will force layout by querying domNode position\n dontForceLayout: true,\n onlyHashChange: scrollHandlerRef.onlyHashChange,\n }\n )\n\n if (!didHandleScroll) {\n return\n }\n\n // Mutate after scrolling so that it can be read by `disableSmoothScrollDuringRouteTransition`\n scrollHandlerRef.onlyHashChange = false\n scrollHandlerRef.hashFragment = null\n },\n // Used to run on every commit. We may be able to be smarter about this\n // but be prepared for lots of manual testing.\n undefined\n )\n\n return <Fragment ref={childrenRef}>{props.children}</Fragment>\n}\n\nfunction ScrollHandler({\n children,\n cacheNode,\n}: {\n children: React.ReactNode\n cacheNode: CacheNode\n}) {\n const context = useContext(GlobalLayoutRouterContext)\n if (!context) {\n throw new Error('invariant global layout router not mounted')\n }\n\n return (\n <InnerScrollHandler scrollRef={context.scrollRef} cacheNode={cacheNode}>\n {children}\n </InnerScrollHandler>\n )\n}\n\n/**\n * InnerLayoutRouter handles rendering the provided segment based on the cache.\n */\nfunction InnerLayoutRouter({\n tree,\n segmentPath,\n debugNameContext,\n cacheNode: maybeCacheNode,\n params,\n url,\n isActive,\n}: {\n tree: FlightRouterState\n segmentPath: FlightSegmentPath\n debugNameContext: string\n cacheNode: CacheNode | null\n params: Params\n url: string\n isActive: boolean\n}) {\n const context = useContext(GlobalLayoutRouterContext)\n const parentNavPromises = useContext(NavigationPromisesContext)\n\n if (!context) {\n throw new Error('invariant global layout router not mounted')\n }\n\n const cacheNode =\n maybeCacheNode !== null\n ? maybeCacheNode\n : // This segment is not in the cache. Suspend indefinitely.\n //\n // This should only be reachable for inactive/hidden segments, during\n // prerendering The active segment should always be consistent with the\n // CacheNode tree. Regardless, if we don't have a matching CacheNode, we\n // must suspend rather than render nothing, to prevent showing an\n // inconsistent route.\n\n (use(unresolvedThenable) as never)\n\n // `rsc` represents the renderable node for this segment.\n\n // If this segment has a `prefetchRsc`, it's the statically prefetched data.\n // We should use that on initial render instead of `rsc`. Then we'll switch\n // to `rsc` when the dynamic response streams in.\n //\n // If no prefetch data is available, then we go straight to rendering `rsc`.\n const resolvedPrefetchRsc =\n cacheNode.prefetchRsc !== null ? cacheNode.prefetchRsc : cacheNode.rsc\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 const rsc: any = useDeferredValue(cacheNode.rsc, resolvedPrefetchRsc)\n\n // `rsc` is either a React node or a promise for a React node, except we\n // special case `null` to represent that this segment's data is missing. If\n // it's a promise, we need to unwrap it so we can determine whether or not the\n // data is missing.\n let resolvedRsc: React.ReactNode\n if (isDeferredRsc(rsc)) {\n const unwrappedRsc = use(rsc)\n if (unwrappedRsc === null) {\n // If the promise was resolved to `null`, it means the data for this\n // segment was not returned by the server. Suspend indefinitely. When this\n // happens, the router is responsible for triggering a new state update to\n // un-suspend this segment.\n use(unresolvedThenable) as never\n }\n resolvedRsc = unwrappedRsc\n } else {\n // This is not a deferred RSC promise. Don't need to unwrap it.\n if (rsc === null) {\n use(unresolvedThenable) as never\n }\n resolvedRsc = rsc\n }\n\n // In dev, we create a NavigationPromisesContext containing the instrumented promises that provide\n // `useSelectedLayoutSegment` and `useSelectedLayoutSegments`.\n // Promises are cached outside of render to survive suspense retries.\n let navigationPromises: NavigationPromises | null = null\n if (process.env.NODE_ENV !== 'production') {\n const { createNestedLayoutNavigationPromises } =\n require('./navigation-devtools') as typeof import('./navigation-devtools')\n\n navigationPromises = createNestedLayoutNavigationPromises(\n tree,\n parentNavPromises\n )\n }\n\n let children = resolvedRsc\n\n if (navigationPromises) {\n children = (\n <NavigationPromisesContext.Provider value={navigationPromises}>\n {resolvedRsc}\n </NavigationPromisesContext.Provider>\n )\n }\n\n children = (\n // The layout router context narrows down tree and childNodes at each level.\n <LayoutRouterContext.Provider\n value={{\n parentTree: tree,\n parentCacheNode: cacheNode,\n parentSegmentPath: segmentPath,\n parentParams: params,\n // This is always set to null as we enter a child segment. It's\n // populated by LoadingBoundaryProvider the next time we reach a\n // loading boundary.\n parentLoadingData: null,\n debugNameContext: debugNameContext,\n\n // TODO-APP: overriding of url for parallel routes\n url: url,\n isActive: isActive,\n }}\n >\n {children}\n </LayoutRouterContext.Provider>\n )\n\n return children\n}\n\nexport function LoadingBoundaryProvider({\n loading,\n children,\n}: {\n loading: LoadingModuleData\n children: React.ReactNode\n}) {\n // Provides the data needed to render a loading.tsx boundary, via context.\n //\n // loading.tsx creates a Suspense boundary around each of a layout's child\n // slots. (Might be bit confusing to think about the data flow, but: if\n // loading.tsx and layout.tsx are in the same directory, they are assigned\n // to the same CacheNode.)\n //\n // This provider component does not render the Suspense boundary directly;\n // that's handled by LoadingBoundary.\n //\n // TODO: For simplicity, we should combine this provider with LoadingBoundary\n // and render the Suspense boundary directly. The only real benefit of doing\n // it separately is so that when there are multiple parallel routes, we only\n // send the boundary data once, rather than once per child. But that's a\n // negligible benefit and can be achieved via caching instead.\n const parentContext = use(LayoutRouterContext)\n if (parentContext === null) {\n return children\n }\n // All values except for parentLoadingData are the same as the parent context.\n return (\n <LayoutRouterContext.Provider\n value={{\n parentTree: parentContext.parentTree,\n parentCacheNode: parentContext.parentCacheNode,\n parentSegmentPath: parentContext.parentSegmentPath,\n parentParams: parentContext.parentParams,\n parentLoadingData: loading,\n debugNameContext: parentContext.debugNameContext,\n url: parentContext.url,\n isActive: parentContext.isActive,\n }}\n >\n {children}\n </LayoutRouterContext.Provider>\n )\n}\n\n/**\n * Renders suspense boundary with the provided \"loading\" property as the fallback.\n * If no loading property is provided it renders the children without a suspense boundary.\n */\nfunction LoadingBoundary({\n name,\n loading,\n children,\n}: {\n name: ActivityProps['name']\n loading: LoadingModuleData | null\n children: React.ReactNode\n}): JSX.Element {\n // TODO: For LoadingBoundary, and the other built-in boundary types, don't\n // wrap in an extra function component if no user-defined boundary is\n // provided. In other words, inline this conditional wrapping logic into\n // the parent component. More efficient and keeps unnecessary junk out of\n // the component stack.\n if (loading !== null) {\n const loadingRsc = loading[0]\n const loadingStyles = loading[1]\n const loadingScripts = loading[2]\n return (\n <Suspense\n name={name}\n fallback={\n <>\n {loadingStyles}\n {loadingScripts}\n {loadingRsc}\n </>\n }\n >\n {children}\n </Suspense>\n )\n }\n\n return <>{children}</>\n}\n\n/**\n * OuterLayoutRouter handles the current segment as well as <Offscreen> rendering of other segments.\n * It can be rendered next to each other with a different `parallelRouterKey`, allowing for Parallel routes.\n */\nexport default function OuterLayoutRouter({\n parallelRouterKey,\n error,\n errorStyles,\n errorScripts,\n templateStyles,\n templateScripts,\n template,\n notFound,\n forbidden,\n unauthorized,\n segmentViewBoundaries,\n}: {\n parallelRouterKey: string\n error: ErrorComponent | undefined\n errorStyles: React.ReactNode | undefined\n errorScripts: React.ReactNode | undefined\n templateStyles: React.ReactNode | undefined\n templateScripts: React.ReactNode | undefined\n template: React.ReactNode\n notFound: React.ReactNode | undefined\n forbidden: React.ReactNode | undefined\n unauthorized: React.ReactNode | undefined\n segmentViewBoundaries?: React.ReactNode\n}) {\n const context = useContext(LayoutRouterContext)\n if (!context) {\n throw new Error('invariant expected layout router to be mounted')\n }\n\n const {\n parentTree,\n parentCacheNode,\n parentSegmentPath,\n parentParams,\n parentLoadingData,\n url,\n isActive,\n debugNameContext,\n } = context\n\n // Get the CacheNode for this segment by reading it from the parent segment's\n // child map.\n const parentTreeSegment = parentTree[0]\n const segmentPath =\n parentSegmentPath === null\n ? // TODO: The root segment value is currently omitted from the segment\n // path. This has led to a bunch of special cases scattered throughout\n // the code. We should clean this up.\n [parallelRouterKey]\n : parentSegmentPath.concat([parentTreeSegment, parallelRouterKey])\n\n // The \"state\" key of a segment is the one passed to React — it represents the\n // identity of the UI tree. Whenever the state key changes, the tree is\n // recreated and the state is reset. In the App Router model, search params do\n // not cause state to be lost, so two segments with the same segment path but\n // different search params should have the same state key.\n //\n // The \"cache\" key of a segment, however, *does* include the search params, if\n // it's possible that the segment accessed the search params on the server.\n // (This only applies to page segments; layout segments cannot access search\n // params on the server.)\n const activeTree = parentTree[1][parallelRouterKey]\n const maybeParentSlots = parentCacheNode.slots\n if (activeTree === undefined || maybeParentSlots === null) {\n // Could not find a matching segment. The client tree is inconsistent with\n // the server tree. Suspend indefinitely; the router will have already\n // detected the inconsistency when handling the server response, and\n // triggered a refresh of the page to recover.\n use(unresolvedThenable) as never\n }\n\n let maybeValidationBoundaryId: string | null = null\n if (typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS) {\n maybeValidationBoundaryId = use(InstantValidationBoundaryContext)\n }\n\n const activeSegment = activeTree[0]\n const activeCacheNode = maybeParentSlots![parallelRouterKey] ?? null\n const activeStateKey = createRouterCacheKey(activeSegment, true) // no search params\n\n // At each level of the route tree, not only do we render the currently\n // active segment — we also render the last N segments that were active at\n // this level inside a hidden <Activity> boundary, to preserve their state\n // if or when the user navigates to them again.\n //\n // bfcacheEntry is a linked list of FlightRouterStates.\n let bfcacheEntry: RouterBFCacheEntry | null = useRouterBFCache(\n activeTree,\n activeCacheNode,\n activeStateKey\n )\n let children: Array<React.ReactNode> = []\n do {\n const tree = bfcacheEntry.tree\n const cacheNode = bfcacheEntry.cacheNode\n const stateKey = bfcacheEntry.stateKey\n const segment = tree[0]\n\n /*\n - Error boundary\n - Only renders error boundary if error component is provided.\n - Rendered for each segment to ensure they have their own error state.\n - When gracefully degrade for bots, skip rendering error boundary.\n - Loading boundary\n - Only renders suspense boundary if loading components is provided.\n - Rendered for each segment to ensure they have their own loading state.\n - Passed to the router during rendering to ensure it can be immediately rendered when suspending on a Flight fetch.\n */\n\n let segmentBoundaryTriggerNode: React.ReactNode = null\n let segmentViewStateNode: React.ReactNode = null\n if (process.env.NODE_ENV !== 'production') {\n const { SegmentBoundaryTriggerNode, SegmentViewStateNode } =\n require('../../next-devtools/userspace/app/segment-explorer-node') as typeof import('../../next-devtools/userspace/app/segment-explorer-node')\n\n const pagePrefix = normalizeAppPath(url)\n segmentViewStateNode = (\n <SegmentViewStateNode key={pagePrefix} page={pagePrefix} />\n )\n\n segmentBoundaryTriggerNode = (\n <>\n <SegmentBoundaryTriggerNode />\n </>\n )\n }\n\n let params = parentParams\n if (Array.isArray(segment)) {\n // This segment contains a route param. Accumulate these as we traverse\n // down the router tree. The result represents the set of params that\n // the layout/page components are permitted to access below this point.\n const paramName = segment[0]\n const paramCacheKey = segment[1]\n const paramType = segment[2]\n const paramValue = getParamValueFromCacheKey(paramCacheKey, paramType)\n if (paramValue !== null) {\n params = {\n ...parentParams,\n [paramName]: paramValue,\n }\n }\n }\n\n const debugName = getBoundaryDebugNameFromSegment(segment)\n // `debugNameContext` represents the nearest non-\"virtual\" parent segment.\n // `getBoundaryDebugNameFromSegment` returns undefined for virtual segments.\n // So if `debugName` is undefined, the context is passed through unchanged.\n const childDebugNameContext = debugName ?? debugNameContext\n\n // In practical terms, clicking this name in the Suspense DevTools\n // should select the child slots of that layout.\n //\n // So the name we apply to the Activity boundary is actually based on\n // the nearest parent segments.\n //\n // We skip over \"virtual\" parents, i.e. ones inserted by Next.js that\n // don't correspond to application-defined code.\n const isVirtual = debugName === undefined\n const debugNameToDisplay = isVirtual ? undefined : debugNameContext\n\n let templateValue = (\n <ScrollHandler cacheNode={cacheNode}>\n <ErrorBoundary\n errorComponent={error}\n errorStyles={errorStyles}\n errorScripts={errorScripts}\n >\n <LoadingBoundary\n name={debugNameToDisplay}\n // TODO: The loading module data for a segment is stored on the\n // parent, then applied to each of that parent segment's\n // parallel route slots. In the simple case where there's only\n // one parallel route (the `children` slot), this is no\n // different from if the loading module data were stored on the\n // child directly. But I'm not sure this actually makes sense\n // when there are multiple parallel routes. It's not a huge\n // issue because you always have the option to define a narrower\n // loading boundary for a particular slot. But this sort of\n // smells like an implementation accident to me.\n loading={parentLoadingData}\n >\n <HTTPAccessFallbackBoundary\n notFound={notFound}\n forbidden={forbidden}\n unauthorized={unauthorized}\n >\n <RedirectBoundary>\n <InnerLayoutRouter\n url={url}\n tree={tree}\n params={params}\n cacheNode={cacheNode}\n segmentPath={segmentPath}\n debugNameContext={childDebugNameContext}\n isActive={isActive && stateKey === activeStateKey}\n />\n {segmentBoundaryTriggerNode}\n </RedirectBoundary>\n </HTTPAccessFallbackBoundary>\n </LoadingBoundary>\n </ErrorBoundary>\n {segmentViewStateNode}\n </ScrollHandler>\n )\n\n if (\n typeof window === 'undefined' &&\n process.env.__NEXT_CACHE_COMPONENTS &&\n typeof maybeValidationBoundaryId === 'string'\n ) {\n templateValue = (\n <RenderValidationBoundaryAtThisLevel id={maybeValidationBoundaryId}>\n {templateValue}\n </RenderValidationBoundaryAtThisLevel>\n )\n }\n\n let child = (\n <TemplateContext.Provider key={stateKey} value={templateValue}>\n {templateStyles}\n {templateScripts}\n {template}\n </TemplateContext.Provider>\n )\n\n if (process.env.NODE_ENV !== 'production') {\n const { SegmentStateProvider } =\n require('../../next-devtools/userspace/app/segment-explorer-node') as typeof import('../../next-devtools/userspace/app/segment-explorer-node')\n\n child = (\n <SegmentStateProvider key={stateKey}>\n {child}\n {segmentViewBoundaries}\n </SegmentStateProvider>\n )\n }\n\n if (process.env.__NEXT_CACHE_COMPONENTS) {\n child = (\n <Activity\n name={debugNameToDisplay}\n key={stateKey}\n mode={stateKey === activeStateKey ? 'visible' : 'hidden'}\n >\n {child}\n </Activity>\n )\n }\n\n children.push(child)\n\n bfcacheEntry = bfcacheEntry.next\n } while (bfcacheEntry !== null)\n\n return children\n}\n\nfunction getBoundaryDebugNameFromSegment(segment: Segment): string | undefined {\n if (segment === '/') {\n // Reached the root\n return '/'\n }\n if (typeof segment === 'string') {\n if (isVirtualLayout(segment)) {\n return undefined\n } else {\n return segment + '/'\n }\n }\n const paramCacheKey = segment[1]\n return paramCacheKey + '/'\n}\n\nfunction isVirtualLayout(segment: string): boolean {\n return (\n // This is inserted by the loader. Uses double-underscore convention\n // (like __PAGE__ and __DEFAULT__) to avoid collisions with\n // user-defined route groups.\n segment === '(__SLOT__)'\n )\n}\n"],"names":["React","Activity","Fragment","useContext","use","Suspense","useDeferredValue","useLayoutEffect","LayoutRouterContext","GlobalLayoutRouterContext","TemplateContext","unresolvedThenable","ErrorBoundary","disableSmoothScrollDuringRouteTransition","RedirectBoundary","HTTPAccessFallbackBoundary","InstantValidationBoundaryContext","RenderValidationBoundaryAtThisLevel","createRouterCacheKey","useRouterBFCache","normalizeAppPath","NavigationPromisesContext","getParamValueFromCacheKey","isDeferredRsc","getScrollPaddingTopInPixels","htmlElement","viewportHeight","scrollPaddingTop","getComputedStyle","value","Number","parseFloat","isFinite","endsWith","getScrollTargetState","instance","getScrollPaddingTop","rects","getClientRects","length","elementTop","POSITIVE_INFINITY","i","rect","top","getHashFragmentDomNode","hashFragment","document","body","getElementById","getElementsByName","InnerScrollHandler","props","childrenRef","useRef","scrollRef","scrollHandlerRef","cacheNode","forceScroll","current","onlyHashChange","didHandleScroll","documentElement","initialTargetState","clientHeight","scrollIntoView","scrollTop","dontForceLayout","undefined","ref","children","ScrollHandler","context","Error","InnerLayoutRouter","tree","segmentPath","debugNameContext","maybeCacheNode","params","url","isActive","parentNavPromises","resolvedPrefetchRsc","prefetchRsc","rsc","resolvedRsc","unwrappedRsc","navigationPromises","process","env","NODE_ENV","createNestedLayoutNavigationPromises","require","Provider","parentTree","parentCacheNode","parentSegmentPath","parentParams","parentLoadingData","LoadingBoundaryProvider","loading","parentContext","LoadingBoundary","name","loadingRsc","loadingStyles","loadingScripts","fallback","OuterLayoutRouter","parallelRouterKey","error","errorStyles","errorScripts","templateStyles","templateScripts","template","notFound","forbidden","unauthorized","segmentViewBoundaries","parentTreeSegment","concat","activeTree","maybeParentSlots","slots","maybeValidationBoundaryId","window","__NEXT_CACHE_COMPONENTS","activeSegment","activeCacheNode","activeStateKey","bfcacheEntry","stateKey","segment","segmentBoundaryTriggerNode","segmentViewStateNode","SegmentBoundaryTriggerNode","SegmentViewStateNode","pagePrefix","page","Array","isArray","paramName","paramCacheKey","paramType","paramValue","debugName","getBoundaryDebugNameFromSegment","childDebugNameContext","isVirtual","debugNameToDisplay","templateValue","errorComponent","id","child","SegmentStateProvider","mode","push","next","isVirtualLayout"],"mappings":"AAAA;;AAYA,OAAOA,SACLC,QAAQ,EACRC,QAAQ,EACRC,UAAU,EACVC,GAAG,EACHC,QAAQ,EACRC,gBAAgB,EAChBC,eAAe,QAIV,QAAO;AACd,SACEC,mBAAmB,EACnBC,yBAAyB,EACzBC,eAAe,QACV,qDAAoD;AAC3D,SAASC,kBAAkB,QAAQ,wBAAuB;AAC1D,SAASC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iE,oBAAoB,EAAE,GAC5B/D,QAAQ;YAEV8D,sBACE,MAACC;;oBACED;oBACAnC;;eAFwBa;QAK/B;QAEA,IAAI5C,QAAQC,GAAG,CAACsC,uBAAuB,EAAE;YACvC2B,sBACE,KAAC1J;gBACCuG,MAAM+C;gBAENM,MAAMxB,aAAaF,iBAAiB,YAAY;0BAE/CwB;eAHItB;QAMX;QAEA/D,SAASwF,IAAI,CAACH;QAEdvB,eAAeA,aAAa2B,IAAI;IAClC,QAAS3B,iBAAiB,MAAK;IAE/B,OAAO9D;AACT;AAEA,SAAS8E,gCAAgCd,OAAgB;IACvD,IAAIA,YAAY,KAAK;QACnB,mBAAmB;QACnB,OAAO;IACT;IACA,IAAI,OAAOA,YAAY,UAAU;QAC/B,IAAI0B,gBAAgB1B,UAAU;YAC5B,OAAOlE;QACT,OAAO;YACL,OAAOkE,UAAU;QACnB;IACF;IACA,MAAMU,gBAAgBV,OAAO,CAAC,EAAE;IAChC,OAAOU,gBAAgB;AACzB;AAEA,SAASgB,gBAAgB1B,OAAe;IACtC,OACE,oEAAoE;IACpE,2DAA2D;IAC3D,6BAA6B;IAC7BA,YAAY;AAEhB","ignoreList":[0]} |
@@ -5,3 +5,3 @@ import { createHrefFromUrl } from './create-href-from-url'; | ||
| import { createInitialCacheNodeForHydration } from './ppr-navigations'; | ||
| import { resolveStaleAt, processRuntimePrefetchStream, writeDynamicRenderResponseIntoCache, writePrerenderResponseIntoCache } from '../segment-cache/cache'; | ||
| import { resolveStaleAt, processRuntimePrefetchStream, segmentCacheMap, writeDynamicRenderResponseIntoCache, writePrerenderResponseIntoCache } from '../segment-cache/cache'; | ||
| import { decodeTransportTreeIntoRouteTree } from '../segment-cache/decode-server-response'; | ||
@@ -69,3 +69,3 @@ import { FetchStrategy } from '../segment-cache/types'; | ||
| const staleAt = await resolveStaleAt(now, staticStageResponse.s); | ||
| writePrerenderResponseIntoCache(now, FetchStrategy.PPR, staticStageResponse.t, undefined, staticStageResponse.r ?? null, staleAt, initialTree, initialRenderedSearch, true // isResponsePartial | ||
| writePrerenderResponseIntoCache(now, FetchStrategy.PPR, staticStageResponse.t, undefined, staticStageResponse.r ?? null, staleAt, initialTree, initialRenderedSearch, true, segmentCacheMap // hydration writes are bound to the shared map | ||
| ); | ||
@@ -84,3 +84,3 @@ }).catch(()=>{ | ||
| resolveStaleAt(now, initialStaleTime).then((staleAt)=>{ | ||
| writePrerenderResponseIntoCache(now, FetchStrategy.PPR, initialTransportData, undefined, initialRootVaryParams ?? null, staleAt, initialTree, initialRenderedSearch, false // isResponsePartial | ||
| writePrerenderResponseIntoCache(now, FetchStrategy.PPR, initialTransportData, undefined, initialRootVaryParams ?? null, staleAt, initialTree, initialRenderedSearch, false, segmentCacheMap // hydration writes are bound to the shared map | ||
| ); | ||
@@ -105,3 +105,4 @@ }).catch(()=>{ | ||
| if (processed !== null) { | ||
| writeDynamicRenderResponseIntoCache(Date.now(), FetchStrategy.PPRRuntime, processed.buildId, processed.isResponsePartial, processed.headVaryParams, processed.rootVaryParamsIterable, processed.staleAt, processed.navigationSeed, null); | ||
| writeDynamicRenderResponseIntoCache(Date.now(), FetchStrategy.PPRRuntime, processed.buildId, processed.isResponsePartial, processed.headVaryParams, processed.rootVaryParamsIterable, processed.staleAt, processed.navigationSeed, null, segmentCacheMap // hydration writes are bound to the shared map | ||
| ); | ||
| } | ||
@@ -138,3 +139,3 @@ }).catch(()=>{ | ||
| }, | ||
| focusAndScrollRef: { | ||
| scrollRef: { | ||
| scrollRef: null, | ||
@@ -141,0 +142,0 @@ forceScroll: false, |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/client/components/router-reducer/create-initial-router-state.ts"],"sourcesContent":["import type { InitialRSCPayload } from '../../../shared/lib/app-router-types'\n\nimport { createHrefFromUrl } from './create-href-from-url'\nimport { extractPathFromFlightRouterState } from './compute-changed-path'\n\nimport type { AppRouterState } from './router-reducer-types'\nimport { transportNodeToFlightRouterState } from '../../../shared/lib/rsc-transport'\nimport { createInitialCacheNodeForHydration } from './ppr-navigations'\nimport {\n resolveStaleAt,\n processRuntimePrefetchStream,\n writeDynamicRenderResponseIntoCache,\n writePrerenderResponseIntoCache,\n} from '../segment-cache/cache'\nimport { decodeTransportTreeIntoRouteTree } from '../segment-cache/decode-server-response'\nimport { FetchStrategy } from '../segment-cache/types'\nimport {\n UnknownDynamicStaleTime,\n computeDynamicStaleAt,\n} from '../segment-cache/bfcache'\nimport { decodeStageUntilBoundary } from './fetch-server-response'\nimport { discoverKnownRoute } from '../segment-cache/optimistic-routes'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\n\nexport interface InitialRouterStateParameters {\n navigatedAt: number\n initialRSCPayload: InitialRSCPayload\n initialFlightStreamForCache?: ReadableStream<Uint8Array> | null\n location: Location | null\n}\n\nexport function createInitialRouterState({\n navigatedAt,\n initialRSCPayload,\n initialFlightStreamForCache,\n location,\n}: InitialRouterStateParameters): AppRouterState {\n const {\n c: initialCanonicalUrlParts,\n t: initialTransportData,\n q: initialRenderedSearch,\n i: initialCouldBeIntercepted,\n S: initialSupportsPerSegmentPrefetching,\n s: initialStaleTime,\n l: initialStaticStageByteLength,\n r: initialRootVaryParams,\n p: initialRuntimePrefetchStream,\n d: initialDynamicStaleTimeSeconds,\n } = initialRSCPayload\n\n // When initialized on the server, the canonical URL is provided as an array of parts.\n // This is to ensure that when the RSC payload streamed to the client, crawlers don't interpret it\n // as a URL that should be crawled.\n const initialCanonicalUrl = initialCanonicalUrlParts.join('/')\n\n const initialHead = initialTransportData.h.r\n\n // The initial router state tree, derived from the transport tree. Page\n // segments keep their search params, which travel inside the segment\n // string.\n const initialTree = transportNodeToFlightRouterState(initialTransportData.t)\n\n const canonicalUrl =\n // location.href is read as the initial value for canonicalUrl in the browser\n // This is safe to do as canonicalUrl can't be rendered, it's only used to control the history updates in the useEffect further down in this file.\n location\n ? // window.location does not have the same type as URL but has all the fields createHrefFromUrl needs.\n createHrefFromUrl(location)\n : initialCanonicalUrl\n\n // Decode the initial transport tree into the RouteTree type, with the\n // payload's render output embedded on each node. (discoverKnownRoute below\n // stores this tree in the route cache, which strips the data on write —\n // see stripDataFromRouteTree.)\n // NOTE: The metadataVaryPath isn't used for anything currently because the\n // head is embedded into the CacheNode tree, but eventually we'll lift it out\n // and store it on the top-level state object.\n //\n // For statically-generated-at-build-time HTML pages, the tree baked into\n // the initial RSC payload won't have the correct segment inlining hints\n // because those are computed after the pre-render. The server marks these\n // trees with InliningHintsStale, which causes the route cache entry to be\n // immediately expired. The next prefetch will re-fetch the tree with\n // correct hints from the /_tree response.\n const acc = { metadataVaryPath: null }\n const initialRouteTree = decodeTransportTreeIntoRouteTree(\n initialTransportData.t,\n // There's no base tree to overlay onto; the initial payload is a full\n // render from the root.\n null,\n initialRenderedSearch as NormalizedSearch,\n acc\n )\n const metadataVaryPath = acc.metadataVaryPath\n const initialTask = createInitialCacheNodeForHydration(\n navigatedAt,\n initialRouteTree,\n initialHead,\n computeDynamicStaleAt(\n navigatedAt,\n initialDynamicStaleTimeSeconds ?? UnknownDynamicStaleTime\n )\n )\n\n // The following only applies in the browser (location !== null) since neither\n // route learning nor segment cache state persists from SSR to client.\n if (location !== null && metadataVaryPath !== null) {\n // Learn the route pattern so we can predict it for future navigations.\n discoverKnownRoute(\n Date.now(),\n location.pathname,\n location.search as NormalizedSearch,\n null, // nextUrl — initial render is never an interception\n null, // No pending entry\n initialRouteTree,\n metadataVaryPath,\n initialCouldBeIntercepted,\n canonicalUrl,\n initialSupportsPerSegmentPrefetching,\n false // hasDynamicRewrite\n )\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the Cached\n // Navigations behavior should work in combination with App Shells.\n\n // Write the initial seed data into the segment cache so subsequent\n // navigations to the initial page can serve cached segments instantly.\n if (initialStaleTime !== undefined) {\n if (\n initialStaticStageByteLength !== undefined &&\n initialFlightStreamForCache != null\n ) {\n // Partially static page — truncate the cloned Flight stream at the\n // static stage byte boundary, decode, and cache the static subset.\n // Promise.resolve wraps the Flight-deserialized thenable into a\n // native Promise so we can chain `.then` on it safely.\n Promise.resolve(initialStaticStageByteLength)\n .then(async (byteLength) => {\n const staticStageResponse =\n await decodeStageUntilBoundary<InitialRSCPayload>(\n initialFlightStreamForCache,\n byteLength,\n undefined\n )\n const now = Date.now()\n const staleAt = await resolveStaleAt(now, staticStageResponse.s)\n\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.t,\n undefined, // no build ID mismatch check for initial HTML\n staticStageResponse.r ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n true // isResponsePartial\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n } else {\n // Fully static page — cache the entire decoded seed data as-is. We're\n // not using the initial response here (which would allow us to combine\n // the two branches) to avoid unnecessary decoding of the Flight data,\n // since we can just take the seed data that we already decoded during\n // hydration and write it into the cache directly.\n const now = Date.now()\n\n resolveStaleAt(now, initialStaleTime)\n .then((staleAt) => {\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n initialTransportData,\n undefined, // buildId — not applicable for initial HTML\n initialRootVaryParams ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n false // isResponsePartial\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n\n // Cancel the stream clone — fully static path doesn't need it.\n initialFlightStreamForCache?.cancel()\n }\n } else {\n // No caching — cancel the unused stream clone.\n initialFlightStreamForCache?.cancel()\n }\n\n // If the initial RSC payload includes an embedded runtime prefetch stream,\n // decode it and write the runtime data into the segment cache. This allows\n // subsequent navigations to serve runtime-prefetchable content from cache\n // without a separate prefetch request.\n if (initialRuntimePrefetchStream != null) {\n processRuntimePrefetchStream(\n Date.now(),\n initialRuntimePrefetchStream,\n initialTree,\n initialRenderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n Date.now(),\n FetchStrategy.PPRRuntime,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null\n )\n }\n })\n .catch(() => {\n // Runtime prefetch cache write failed. Not fatal — the page rendered\n // normally, we just won't cache runtime data.\n })\n }\n }\n\n // NOTE: We intentionally don't check if any data needs to be fetched from the\n // server. We assume the initial hydration payload is sufficient to render\n // the page.\n //\n // The completeness of the initial data is an important property that we rely\n // on as a last-ditch mechanism for recovering the app; we must always be able\n // to reload a fresh HTML document to get to a consistent state.\n //\n // In the future, there may be cases where the server intentionally sends\n // partial data and expects the client to fill in the rest, in which case this\n // logic may change. (There already is a similar case where the server sends\n // _no_ hydration data in the HTML document at all, and the client fetches it\n // separately, but that's different because we still end up hydrating with a\n // complete tree.)\n\n const initialState = {\n tree: initialTask.route,\n cache: initialTask.node,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // First render needs to preserve the previous window.history.state\n // to avoid it being overwritten on navigation back/forward with MPA Navigation.\n preserveCustomHistoryState: true,\n },\n focusAndScrollRef: {\n scrollRef: null,\n forceScroll: false,\n onlyHashChange: false,\n hashFragment: null,\n },\n canonicalUrl,\n renderedSearch: initialRenderedSearch,\n // the || operator is intentional, the pathname can be an empty string\n nextUrl:\n (extractPathFromFlightRouterState(initialTree) || location?.pathname) ??\n null,\n previousNextUrl: null,\n debugInfo: null,\n }\n\n return initialState\n}\n"],"names":["createHrefFromUrl","extractPathFromFlightRouterState","transportNodeToFlightRouterState","createInitialCacheNodeForHydration","resolveStaleAt","processRuntimePrefetchStream","writeDynamicRenderResponseIntoCache","writePrerenderResponseIntoCache","decodeTransportTreeIntoRouteTree","FetchStrategy","UnknownDynamicStaleTime","computeDynamicStaleAt","decodeStageUntilBoundary","discoverKnownRoute","createInitialRouterState","navigatedAt","initialRSCPayload","initialFlightStreamForCache","location","c","initialCanonicalUrlParts","t","initialTransportData","q","initialRenderedSearch","i","initialCouldBeIntercepted","S","initialSupportsPerSegmentPrefetching","s","initialStaleTime","l","initialStaticStageByteLength","r","initialRootVaryParams","p","initialRuntimePrefetchStream","d","initialDynamicStaleTimeSeconds","initialCanonicalUrl","join","initialHead","h","initialTree","canonicalUrl","acc","metadataVaryPath","initialRouteTree","initialTask","Date","now","pathname","search","undefined","Promise","resolve","then","byteLength","staticStageResponse","staleAt","PPR","catch","cancel","processed","PPRRuntime","buildId","isResponsePartial","headVaryParams","rootVaryParamsIterable","navigationSeed","initialState","tree","route","cache","node","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","scrollRef","forceScroll","onlyHashChange","hashFragment","renderedSearch","nextUrl","previousNextUrl","debugInfo"],"mappings":"AAEA,SAASA,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,gCAAgC,QAAQ,yBAAwB;AAGzE,SAASC,gCAAgC,QAAQ,oCAAmC;AACpF,SAASC,kCAAkC,QAAQ,oBAAmB;AACtE,SACEC,cAAc,EACdC,4BAA4B,EAC5BC,mCAAmC,EACnCC,+BAA+B,QAC1B,yBAAwB;AAC/B,SAASC,gCAAgC,QAAQ,0CAAyC;AAC1F,SAASC,aAAa,QAAQ,yBAAwB;AACtD,SACEC,uBAAuB,EACvBC,qBAAqB,QAChB,2BAA0B;AACjC,SAASC,wBAAwB,QAAQ,0BAAyB;AAClE,SAASC,kBAAkB,QAAQ,qCAAoC;AAUvE,OAAO,SAASC,yBAAyB,EACvCC,WAAW,EACXC,iBAAiB,EACjBC,2BAA2B,EAC3BC,QAAQ,EACqB;IAC7B,MAAM,EACJC,GAAGC,wBAAwB,EAC3BC,GAAGC,oBAAoB,EACvBC,GAAGC,qBAAqB,EACxBC,GAAGC,yBAAyB,EAC5BC,GAAGC,oCAAoC,EACvCC,GAAGC,gBAAgB,EACnBC,GAAGC,4BAA4B,EAC/BC,GAAGC,qBAAqB,EACxBC,GAAGC,4BAA4B,EAC/BC,GAAGC,8BAA8B,EAClC,GAAGtB;IAEJ,sFAAsF;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xB;gBAEJ;YACF,GACCR,KAAK,CAAC;YACL,qEAAqE;YACrE,8CAA8C;YAChD;QACJ;IACF;IAEA,8EAA8E;IAC9E,0EAA0E;IAC1E,YAAY;IACZ,EAAE;IACF,6EAA6E;IAC7E,8EAA8E;IAC9E,gEAAgE;IAChE,EAAE;IACF,yEAAyE;IACzE,8EAA8E;IAC9E,4EAA4E;IAC5E,6EAA6E;IAC7E,4EAA4E;IAC5E,kBAAkB;IAElB,MAAMS,eAAe;QACnBC,MAAMvB,YAAYwB,KAAK;QACvBC,OAAOzB,YAAY0B,IAAI;QACvBC,SAAS;YACPC,aAAa;YACbC,eAAe;YACf,mEAAmE;YACnE,gFAAgF;YAChFC,4BAA4B;QAC9B;QACAC,mBAAmB;YACjBC,WAAW;YACXC,aAAa;YACbC,gBAAgB;YAChBC,cAAc;QAChB;QACAvC;QACAwC,gBAAgB5D;QAChB,sEAAsE;QACtE6D,SACE,AAACpF,CAAAA,iCAAiC0C,gBAAgBzB,UAAUiC,QAAO,KACnE;QACFmC,iBAAiB;QACjBC,WAAW;IACb;IAEA,OAAOjB;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/client/components/router-reducer/create-initial-router-state.ts"],"sourcesContent":["import type { InitialRSCPayload } from '../../../shared/lib/app-router-types'\n\nimport { createHrefFromUrl } from './create-href-from-url'\nimport { extractPathFromFlightRouterState } from './compute-changed-path'\n\nimport type { AppRouterState } from './router-reducer-types'\nimport { transportNodeToFlightRouterState } from '../../../shared/lib/rsc-transport'\nimport { createInitialCacheNodeForHydration } from './ppr-navigations'\nimport {\n resolveStaleAt,\n processRuntimePrefetchStream,\n segmentCacheMap,\n writeDynamicRenderResponseIntoCache,\n writePrerenderResponseIntoCache,\n} from '../segment-cache/cache'\nimport { decodeTransportTreeIntoRouteTree } from '../segment-cache/decode-server-response'\nimport { FetchStrategy } from '../segment-cache/types'\nimport {\n UnknownDynamicStaleTime,\n computeDynamicStaleAt,\n} from '../segment-cache/bfcache'\nimport { decodeStageUntilBoundary } from './fetch-server-response'\nimport { discoverKnownRoute } from '../segment-cache/optimistic-routes'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\n\nexport interface InitialRouterStateParameters {\n navigatedAt: number\n initialRSCPayload: InitialRSCPayload\n initialFlightStreamForCache?: ReadableStream<Uint8Array> | null\n location: Location | null\n}\n\nexport function createInitialRouterState({\n navigatedAt,\n initialRSCPayload,\n initialFlightStreamForCache,\n location,\n}: InitialRouterStateParameters): AppRouterState {\n const {\n c: initialCanonicalUrlParts,\n t: initialTransportData,\n q: initialRenderedSearch,\n i: initialCouldBeIntercepted,\n S: initialSupportsPerSegmentPrefetching,\n s: initialStaleTime,\n l: initialStaticStageByteLength,\n r: initialRootVaryParams,\n p: initialRuntimePrefetchStream,\n d: initialDynamicStaleTimeSeconds,\n } = initialRSCPayload\n\n // When initialized on the server, the canonical URL is provided as an array of parts.\n // This is to ensure that when the RSC payload streamed to the client, crawlers don't interpret it\n // as a URL that should be crawled.\n const initialCanonicalUrl = initialCanonicalUrlParts.join('/')\n\n const initialHead = initialTransportData.h.r\n\n // The initial router state tree, derived from the transport tree. Page\n // segments keep their search params, which travel inside the segment\n // string.\n const initialTree = transportNodeToFlightRouterState(initialTransportData.t)\n\n const canonicalUrl =\n // location.href is read as the initial value for canonicalUrl in the browser\n // This is safe to do as canonicalUrl can't be rendered, it's only used to control the history updates in the useEffect further down in this file.\n location\n ? // window.location does not have the same type as URL but has all the fields createHrefFromUrl needs.\n createHrefFromUrl(location)\n : initialCanonicalUrl\n\n // Decode the initial transport tree into the RouteTree type, with the\n // payload's render output embedded on each node. (discoverKnownRoute below\n // stores this tree in the route cache, which strips the data on write —\n // see stripDataFromRouteTree.)\n // NOTE: The metadataVaryPath isn't used for anything currently because the\n // head is embedded into the CacheNode tree, but eventually we'll lift it out\n // and store it on the top-level state object.\n //\n // For statically-generated-at-build-time HTML pages, the tree baked into\n // the initial RSC payload won't have the correct segment inlining hints\n // because those are computed after the pre-render. The server marks these\n // trees with InliningHintsStale, which causes the route cache entry to be\n // immediately expired. The next prefetch will re-fetch the tree with\n // correct hints from the /_tree response.\n const acc = { metadataVaryPath: null }\n const initialRouteTree = decodeTransportTreeIntoRouteTree(\n initialTransportData.t,\n // There's no base tree to overlay onto; the initial payload is a full\n // render from the root.\n null,\n initialRenderedSearch as NormalizedSearch,\n acc\n )\n const metadataVaryPath = acc.metadataVaryPath\n const initialTask = createInitialCacheNodeForHydration(\n navigatedAt,\n initialRouteTree,\n initialHead,\n computeDynamicStaleAt(\n navigatedAt,\n initialDynamicStaleTimeSeconds ?? UnknownDynamicStaleTime\n )\n )\n\n // The following only applies in the browser (location !== null) since neither\n // route learning nor segment cache state persists from SSR to client.\n if (location !== null && metadataVaryPath !== null) {\n // Learn the route pattern so we can predict it for future navigations.\n discoverKnownRoute(\n Date.now(),\n location.pathname,\n location.search as NormalizedSearch,\n null, // nextUrl — initial render is never an interception\n null, // No pending entry\n initialRouteTree,\n metadataVaryPath,\n initialCouldBeIntercepted,\n canonicalUrl,\n initialSupportsPerSegmentPrefetching,\n false // hasDynamicRewrite\n )\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the Cached\n // Navigations behavior should work in combination with App Shells.\n\n // Write the initial seed data into the segment cache so subsequent\n // navigations to the initial page can serve cached segments instantly.\n if (initialStaleTime !== undefined) {\n if (\n initialStaticStageByteLength !== undefined &&\n initialFlightStreamForCache != null\n ) {\n // Partially static page — truncate the cloned Flight stream at the\n // static stage byte boundary, decode, and cache the static subset.\n // Promise.resolve wraps the Flight-deserialized thenable into a\n // native Promise so we can chain `.then` on it safely.\n Promise.resolve(initialStaticStageByteLength)\n .then(async (byteLength) => {\n const staticStageResponse =\n await decodeStageUntilBoundary<InitialRSCPayload>(\n initialFlightStreamForCache,\n byteLength,\n undefined\n )\n const now = Date.now()\n const staleAt = await resolveStaleAt(now, staticStageResponse.s)\n\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.t,\n undefined, // no build ID mismatch check for initial HTML\n staticStageResponse.r ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n true, // isResponsePartial\n segmentCacheMap // hydration writes are bound to the shared map\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n } else {\n // Fully static page — cache the entire decoded seed data as-is. We're\n // not using the initial response here (which would allow us to combine\n // the two branches) to avoid unnecessary decoding of the Flight data,\n // since we can just take the seed data that we already decoded during\n // hydration and write it into the cache directly.\n const now = Date.now()\n\n resolveStaleAt(now, initialStaleTime)\n .then((staleAt) => {\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n initialTransportData,\n undefined, // buildId — not applicable for initial HTML\n initialRootVaryParams ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n false, // isResponsePartial\n segmentCacheMap // hydration writes are bound to the shared map\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n\n // Cancel the stream clone — fully static path doesn't need it.\n initialFlightStreamForCache?.cancel()\n }\n } else {\n // No caching — cancel the unused stream clone.\n initialFlightStreamForCache?.cancel()\n }\n\n // If the initial RSC payload includes an embedded runtime prefetch stream,\n // decode it and write the runtime data into the segment cache. This allows\n // subsequent navigations to serve runtime-prefetchable content from cache\n // without a separate prefetch request.\n if (initialRuntimePrefetchStream != null) {\n processRuntimePrefetchStream(\n Date.now(),\n initialRuntimePrefetchStream,\n initialTree,\n initialRenderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n Date.now(),\n FetchStrategy.PPRRuntime,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null,\n segmentCacheMap // hydration writes are bound to the shared map\n )\n }\n })\n .catch(() => {\n // Runtime prefetch cache write failed. Not fatal — the page rendered\n // normally, we just won't cache runtime data.\n })\n }\n }\n\n // NOTE: We intentionally don't check if any data needs to be fetched from the\n // server. We assume the initial hydration payload is sufficient to render\n // the page.\n //\n // The completeness of the initial data is an important property that we rely\n // on as a last-ditch mechanism for recovering the app; we must always be able\n // to reload a fresh HTML document to get to a consistent state.\n //\n // In the future, there may be cases where the server intentionally sends\n // partial data and expects the client to fill in the rest, in which case this\n // logic may change. (There already is a similar case where the server sends\n // _no_ hydration data in the HTML document at all, and the client fetches it\n // separately, but that's different because we still end up hydrating with a\n // complete tree.)\n\n const initialState = {\n tree: initialTask.route,\n cache: initialTask.node,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // First render needs to preserve the previous window.history.state\n // to avoid it being overwritten on navigation back/forward with MPA Navigation.\n preserveCustomHistoryState: true,\n },\n scrollRef: {\n scrollRef: null,\n forceScroll: false,\n onlyHashChange: false,\n hashFragment: null,\n },\n canonicalUrl,\n renderedSearch: initialRenderedSearch,\n // the || operator is intentional, the pathname can be an empty string\n nextUrl:\n (extractPathFromFlightRouterState(initialTree) || location?.pathname) ??\n null,\n previousNextUrl: null,\n debugInfo: null,\n }\n\n return initialState\n}\n"],"names":["createHrefFromUrl","extractPathFromFlightRouterState","transportNodeToFlightRouterState","createInitialCacheNodeForHydration","resolveStaleAt","processRuntimePrefetchStream","segmentCacheMap","writeDynamicRenderResponseIntoCache","writePrerenderResponseIntoCache","decodeTransportTreeIntoRouteTree","FetchStrategy","UnknownDynamicStaleTime","computeDynamicStaleAt","decodeStageUntilBoundary","discoverKnownRoute","createInitialRouterState","navigatedAt","initialRSCPayload","initialFlightStreamForCache","location","c","initialCanonicalUrlParts","t","initialTransportData","q","initialRenderedSearch","i","initialCouldBeIntercepted","S","initialSupportsPerSegmentPrefetching","s","initialStaleTime","l","initialStaticStageByteLength","r","initialRootVaryParams","p","initialRuntimePrefetchStream","d","initialDynamicStaleTimeSeconds","initialCanonicalUrl","join","initialHead","h","initialTree","canonicalUrl","acc","metadataVaryPath","initialRouteTree","initialTask","Date","now","pathname","search","undefined","Promise","resolve","then","byteLength","staticStageResponse","staleAt","PPR","catch","cancel","processed","PPRRuntime","buildId","isResponsePartial","headVaryParams","rootVaryParamsIterable","navigationSeed","initialState","tree","route","cache","node","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","scrollRef","forceScroll","onlyHashChange","hashFragment","renderedSearch","nextUrl","previousNextUrl","debugInfo"],"mappings":"AAEA,SAASA,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,gCAAgC,QAAQ,yBAAwB;AAGzE,SAASC,gCAAgC,QAAQ,oCAAmC;AACpF,SAASC,kCAAkC,QAAQ,oBAAmB;AACtE,SACEC,cAAc,EACdC,4BAA4B,EAC5BC,eAAe,EACfC,mCAAmC,EACnCC,+BAA+B,QAC1B,yBAAwB;AAC/B,SAASC,gCAAgC,QAAQ,0CAAyC;AAC1F,SAASC,aAAa,QAAQ,yBAAwB;AACtD,SACEC,uBAAuB,EACvBC,qBAAqB,QAChB,2BAA0B;AACjC,SAASC,wBAAwB,QAAQ,0BAAyB;AAClE,SAASC,kBAAkB,QAAQ,qCAAoC;AAUvE,OAAO,SAASC,yBAAyB,EACvCC,WAAW,EACXC,iBAAiB,EACjBC,2BAA2B,EAC3BC,QAAQ,EACqB;IAC7B,MAAM,EACJC,GAAGC,wBAAwB,EAC3BC,GAAGC,oBAAoB,EACvBC,GAAGC,qBAAqB,EACxBC,GAAGC,yBAAyB,EAC5BC,GAAGC,oCAAoC,EACvCC,GAAGC,gBAAgB,EACnBC,GAAGC,4BAA4B,EAC/BC,GAAGC,qBAAqB,EACxBC,GAAGC,4BAA4B,EAC/BC,GAAGC,8BAA8B,EAClC,GAAGtB;IAEJ,sFAAsF;IACtF,kGAAkG;IAClG,mCAAmC;IACnC,MAAMuB,sBAAsBnB,yBAAyBoB,IAAI,CAAC;IAE1D,MAAMC,cAAcnB,qBAAqBoB,CAAC,CAACT,CAAC;IAE5C,uEAAuE;IACvE,qEAAqE;IACrE,UAAU;IACV,MAAMU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F,6EAA6E;IAC7E,8EAA8E;IAC9E,gEAAgE;IAChE,EAAE;IACF,yEAAyE;IACzE,8EAA8E;IAC9E,4EAA4E;IAC5E,6EAA6E;IAC7E,4EAA4E;IAC5E,kBAAkB;IAElB,MAAMS,eAAe;QACnBC,MAAMvB,YAAYwB,KAAK;QACvBC,OAAOzB,YAAY0B,IAAI;QACvBC,SAAS;YACPC,aAAa;YACbC,eAAe;YACf,mEAAmE;YACnE,gFAAgF;YAChFC,4BAA4B;QAC9B;QACAC,WAAW;YACTA,WAAW;YACXC,aAAa;YACbC,gBAAgB;YAChBC,cAAc;QAChB;QACAtC;QACAuC,gBAAgB3D;QAChB,sEAAsE;QACtE4D,SACE,AAACpF,CAAAA,iCAAiC2C,gBAAgBzB,UAAUiC,QAAO,KACnE;QACFkC,iBAAiB;QACjBC,WAAW;IACb;IAEA,OAAOhB;AACT","ignoreList":[0]} |
| import { ScrollBehavior } from '../router-reducer-types'; | ||
| import { navigateToKnownRoute } from '../../segment-cache/navigation'; | ||
| import { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response'; | ||
| import { invalidateSegmentCacheEntries } from '../../segment-cache/cache'; | ||
| import { invalidateSegmentCacheEntries, segmentCacheMap } from '../../segment-cache/cache'; | ||
| import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'; | ||
@@ -55,3 +55,4 @@ import { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations'; | ||
| const navigateType = state.pushRef.pendingPush ? 'push' : 'replace'; | ||
| return navigateToKnownRoute(now, state, currentUrl, currentCanonicalUrl, refreshSeed, currentUrl, currentRenderedSearch, state.cache, currentFlightRouterState, freshnessPolicy, nextUrlForRefresh, scrollBehavior, navigateType, navigationLock, null, // Refresh navigations don't use route prediction, so there's no route | ||
| return navigateToKnownRoute(now, state, currentUrl, currentCanonicalUrl, refreshSeed, currentUrl, currentRenderedSearch, state.cache, currentFlightRouterState, freshnessPolicy, nextUrlForRefresh, scrollBehavior, navigateType, navigationLock, // A refresh is bound to the shared map. | ||
| segmentCacheMap, null, // Refresh navigations don't use route prediction, so there's no route | ||
| // cache entry to mark as having a dynamic rewrite on mismatch. If a | ||
@@ -58,0 +59,0 @@ // mismatch occurs, the retry handler will traverse the known route tree |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../../src/client/components/router-reducer/reducers/refresh-reducer.ts"],"sourcesContent":["import type {\n ReadonlyReducerState,\n ReducerState,\n RefreshAction,\n} from '../router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer-types'\nimport { navigateToKnownRoute } from '../../segment-cache/navigation'\nimport { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response'\nimport { invalidateSegmentCacheEntries } from '../../segment-cache/cache'\nimport { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'\nimport { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations'\nimport {\n invalidateBfCache,\n UnknownDynamicStaleTime,\n} from '../../segment-cache/bfcache'\n\nexport function refreshReducer(\n state: ReadonlyReducerState,\n action: RefreshAction\n): ReducerState {\n // During a refresh, we invalidate the segment cache but not the route cache.\n // The route cache contains the tree structure (which segments exist at a\n // given URL) which doesn't change during a refresh. The segment cache\n // contains the actual RSC data which needs to be re-fetched.\n //\n // The Instant Navigation Testing API can bypass cache invalidation to\n // preserve prefetched data when refreshing after an MPA navigation. This is\n // only used for testing and is not exposed in production builds by default.\n const bypassCacheInvalidation =\n process.env.__NEXT_EXPOSE_TESTING_API && action.bypassCacheInvalidation\n if (!bypassCacheInvalidation) {\n const currentNextUrl = state.nextUrl\n const currentRouterState = state.tree\n invalidateSegmentCacheEntries(currentNextUrl, currentRouterState)\n }\n // A full refresh has no HMR generation to cancel.\n return refreshDynamicData(state, FreshnessPolicy.RefreshAll, undefined)\n}\n\nexport function refreshDynamicData(\n state: ReadonlyReducerState,\n freshnessPolicy: FreshnessPolicy.RefreshAll | FreshnessPolicy.HMRRefresh,\n signal: AbortSignal | undefined\n): ReducerState {\n // During a refresh, invalidate the BFCache, which may contain dynamic data.\n invalidateBfCache()\n\n const currentNextUrl = state.nextUrl\n\n // We always send the last next-url, not the current when performing a dynamic\n // request. This is because we update the next-url after a navigation, but we\n // want the same interception route to be matched that used the last next-url.\n const nextUrlForRefresh = hasInterceptionRouteInCurrentTree(state.tree)\n ? state.previousNextUrl || currentNextUrl\n : null\n\n // A refresh is modeled as a navigation to the current URL, but where any\n // existing dynamic data (including in shared layouts) is re-fetched.\n const currentCanonicalUrl = state.canonicalUrl\n const currentUrl = new URL(currentCanonicalUrl, location.origin)\n const currentRenderedSearch = state.renderedSearch\n const currentFlightRouterState = state.tree\n const scrollBehavior = ScrollBehavior.NoScroll\n const navigationLock = getCurrentNavigationLock()\n\n // Create a NavigationSeed from the current FlightRouterState.\n // TODO: Eventually we will store this type directly on the state object\n // instead of reconstructing it on demand. Part of a larger series of\n // refactors to unify the various tree types that the client deals with.\n const now = Date.now()\n // TODO: Store the dynamic stale time on the top-level state so it's known\n // during restores and refreshes.\n const refreshSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n null,\n currentRenderedSearch,\n UnknownDynamicStaleTime\n )\n\n // If the previous navigation hasn't pushed its history entry yet (React\n // hasn't committed its state), this refresh may commit in its place, so it\n // takes over the push. If the navigation does commit first, HistoryUpdater\n // sees that the URL already matches and replaces instead.\n const navigateType = state.pushRef.pendingPush ? 'push' : 'replace'\n return navigateToKnownRoute(\n now,\n state,\n currentUrl,\n currentCanonicalUrl,\n refreshSeed,\n currentUrl,\n currentRenderedSearch,\n state.cache,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrlForRefresh,\n scrollBehavior,\n navigateType,\n navigationLock,\n null,\n // Refresh navigations don't use route prediction, so there's no route\n // cache entry to mark as having a dynamic rewrite on mismatch. If a\n // mismatch occurs, the retry handler will traverse the known route tree\n // to find and mark the entry.\n null,\n signal\n )\n}\n"],"names":["ScrollBehavior","navigateToKnownRoute","convertServerPatchToFullTree","invalidateSegmentCacheEntries","hasInterceptionRouteInCurrentTree","FreshnessPolicy","getCurrentNavigationLock","invalidateBfCache","UnknownDynamicStaleTime","refreshReducer","state","action","bypassCacheInvalidation","process","env","__NEXT_EXPOSE_TESTING_API","currentNextUrl","nextUrl","currentRouterState","tree","refreshDynamicData","RefreshAll","undefined","freshnessPolicy","signal","nextUrlForRefresh","previousNextUrl","currentCanonicalUrl","canonicalUrl","currentUrl","URL","location","origin","currentRenderedSearch","renderedSearch","currentFlightRouterState","scrollBehavior","NoScroll","navigationLock","now","Date","refreshSeed","navigateType","pushRef","pendingPush","cache"],"mappings":"AAKA,SAASA,cAAc,QAAQ,0BAAyB;AACxD,SAASC,oBAAoB,QAAQ,iCAAgC;AACrE,SAASC,4BAA4B,QAAQ,6CAA4C;AACzF,SAASC,6BAA6B,QAAQ,4BAA2B;AACzE,SAASC,iCAAiC,QAAQ,2CAA0C;AAC5F,SAASC,eAAe,EAAEC,wBAAwB,QAAQ,qBAAoB;AAC9E,SACEC,iBAAiB,EACjBC,uBAAuB,QAClB,8BAA6B;AAEpC,OAAO,SAASC,eACdC,KAA2B,EAC3BC,MAAqB;IAErB,6EAA6E;IAC7E,yEAAyE;IACzE,sEAAsE;IACtE,6DAA6D;IAC7D,EAAE;IACF,sEAAsE;IACtE,4EAA4E;IAC5E,4EAA4E;IAC5E,MAAMC,0BACJC,QAAQC,GAAG,CAACC,yBAAyB,IAAIJ,OAAOC,uBAAuB;IACzE,IAAI,CAACA,yBAAyB;QAC5B,MAAMI,iBAAiBN,MAAMO,OAAO;QACpC,MAAMC,qBAAqBR,MAAMS,IAAI;QACrChB,8BAA8Ba,gBAAgBE;IAChD;IACA,kDAAkD;IAClD,OAAOE,mBAAmBV,OAAOL,gBAAgBgB,UAAU,EAAEC;AAC/D;AAEA,OAAO,SAASF,mBACdV,KAA2B,EAC3Ba,eAAwE,EACxEC,MAA+B;IAE/B,4EAA4E;IAC5EjB;IAEA,MAAMS,iBAAiBN,MAAMO,OAAO;IAEpC,8EAA8E;IAC9E,6EAA6E;IAC7E,8EAA8E;IAC9E,MAAMQ,oBAAoBrB,kCAAkCM,MAAMS,IAAI,IAClET,MAAMgB,eAAe,IAAIV,iBACzB;IAEJ,yEAAyE;IACzE,qEAAqE;IACrE,MAAMW,sBAAsBjB,MAAMkB,YAAY;IAC9C,MAAMC,aAAa,IAAIC,IAAIH,qBAAqBI,SAASC,MAAM;IAC/D,MAAMC,wBAAwBvB,MAAMwB,cAAc;IAClD,MAAMC,2BAA2BzB,MAAMS,IAAI;IAC3C,MAAMiB,iBAAiBpC,eAAeqC,QAAQ;IAC9C,MAAMC,iBAAiBhC;IAEvB,8DAA8D;IAC9D,wEAAwE;IACxE,qEAAqE;IACrE,wEAAwE;IACxE,MAAMiC,MAAMC,KAAKD,GAAG;IACpB,0EAA0E;IAC1E,iCAAiC;IACjC,MAAME,cAAcvC,6BAClBqC,KACAJ,0BACA,MACAF,uBACAzB;IAGF,wEAAwE;IACxE,2EAA2E;IAC3E,2EAA2E;IAC3E,0DAA0D;IAC1D,MAAMkC,eAAehC,MAAMiC,OAAO,CAACC,WAAW,GAAG,SAAS;IAC1D,OAAO3C,qBACLsC,KACA7B,OACAmB,YACAF,qBACAc,aACAZ,YACAI,uBACAvB,MAAMmC,KAAK,EACXV,0BACAZ,iBACAE,mBACAW,gBACAM,cACAJ,gBACA,MACA,sEAAsE;IACtE,oEAAoE;IACpE,wEAAwE;IACxE,8BAA8B;IAC9B,MACAd;AAEJ","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../../src/client/components/router-reducer/reducers/refresh-reducer.ts"],"sourcesContent":["import type {\n ReadonlyReducerState,\n ReducerState,\n RefreshAction,\n} from '../router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer-types'\nimport { navigateToKnownRoute } from '../../segment-cache/navigation'\nimport { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response'\nimport {\n invalidateSegmentCacheEntries,\n segmentCacheMap,\n} from '../../segment-cache/cache'\nimport { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'\nimport { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations'\nimport {\n invalidateBfCache,\n UnknownDynamicStaleTime,\n} from '../../segment-cache/bfcache'\n\nexport function refreshReducer(\n state: ReadonlyReducerState,\n action: RefreshAction\n): ReducerState {\n // During a refresh, we invalidate the segment cache but not the route cache.\n // The route cache contains the tree structure (which segments exist at a\n // given URL) which doesn't change during a refresh. The segment cache\n // contains the actual RSC data which needs to be re-fetched.\n //\n // The Instant Navigation Testing API can bypass cache invalidation to\n // preserve prefetched data when refreshing after an MPA navigation. This is\n // only used for testing and is not exposed in production builds by default.\n const bypassCacheInvalidation =\n process.env.__NEXT_EXPOSE_TESTING_API && action.bypassCacheInvalidation\n if (!bypassCacheInvalidation) {\n const currentNextUrl = state.nextUrl\n const currentRouterState = state.tree\n invalidateSegmentCacheEntries(currentNextUrl, currentRouterState)\n }\n // A full refresh has no HMR generation to cancel.\n return refreshDynamicData(state, FreshnessPolicy.RefreshAll, undefined)\n}\n\nexport function refreshDynamicData(\n state: ReadonlyReducerState,\n freshnessPolicy: FreshnessPolicy.RefreshAll | FreshnessPolicy.HMRRefresh,\n signal: AbortSignal | undefined\n): ReducerState {\n // During a refresh, invalidate the BFCache, which may contain dynamic data.\n invalidateBfCache()\n\n const currentNextUrl = state.nextUrl\n\n // We always send the last next-url, not the current when performing a dynamic\n // request. This is because we update the next-url after a navigation, but we\n // want the same interception route to be matched that used the last next-url.\n const nextUrlForRefresh = hasInterceptionRouteInCurrentTree(state.tree)\n ? state.previousNextUrl || currentNextUrl\n : null\n\n // A refresh is modeled as a navigation to the current URL, but where any\n // existing dynamic data (including in shared layouts) is re-fetched.\n const currentCanonicalUrl = state.canonicalUrl\n const currentUrl = new URL(currentCanonicalUrl, location.origin)\n const currentRenderedSearch = state.renderedSearch\n const currentFlightRouterState = state.tree\n const scrollBehavior = ScrollBehavior.NoScroll\n const navigationLock = getCurrentNavigationLock()\n\n // Create a NavigationSeed from the current FlightRouterState.\n // TODO: Eventually we will store this type directly on the state object\n // instead of reconstructing it on demand. Part of a larger series of\n // refactors to unify the various tree types that the client deals with.\n const now = Date.now()\n // TODO: Store the dynamic stale time on the top-level state so it's known\n // during restores and refreshes.\n const refreshSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n null,\n currentRenderedSearch,\n UnknownDynamicStaleTime\n )\n\n // If the previous navigation hasn't pushed its history entry yet (React\n // hasn't committed its state), this refresh may commit in its place, so it\n // takes over the push. If the navigation does commit first, HistoryUpdater\n // sees that the URL already matches and replaces instead.\n const navigateType = state.pushRef.pendingPush ? 'push' : 'replace'\n return navigateToKnownRoute(\n now,\n state,\n currentUrl,\n currentCanonicalUrl,\n refreshSeed,\n currentUrl,\n currentRenderedSearch,\n state.cache,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrlForRefresh,\n scrollBehavior,\n navigateType,\n navigationLock,\n // A refresh is bound to the shared map.\n segmentCacheMap,\n null,\n // Refresh navigations don't use route prediction, so there's no route\n // cache entry to mark as having a dynamic rewrite on mismatch. If a\n // mismatch occurs, the retry handler will traverse the known route tree\n // to find and mark the entry.\n null,\n signal\n )\n}\n"],"names":["ScrollBehavior","navigateToKnownRoute","convertServerPatchToFullTree","invalidateSegmentCacheEntries","segmentCacheMap","hasInterceptionRouteInCurrentTree","FreshnessPolicy","getCurrentNavigationLock","invalidateBfCache","UnknownDynamicStaleTime","refreshReducer","state","action","bypassCacheInvalidation","process","env","__NEXT_EXPOSE_TESTING_API","currentNextUrl","nextUrl","currentRouterState","tree","refreshDynamicData","RefreshAll","undefined","freshnessPolicy","signal","nextUrlForRefresh","previousNextUrl","currentCanonicalUrl","canonicalUrl","currentUrl","URL","location","origin","currentRenderedSearch","renderedSearch","currentFlightRouterState","scrollBehavior","NoScroll","navigationLock","now","Date","refreshSeed","navigateType","pushRef","pendingPush","cache"],"mappings":"AAKA,SAASA,cAAc,QAAQ,0BAAyB;AACxD,SAASC,oBAAoB,QAAQ,iCAAg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,qEAAqE;IACrE,wEAAwE;IACxE,MAAMiC,MAAMC,KAAKD,GAAG;IACpB,0EAA0E;IAC1E,iCAAiC;IACjC,MAAME,cAAcxC,6BAClBsC,KACAJ,0BACA,MACAF,uBACAzB;IAGF,wEAAwE;IACxE,2EAA2E;IAC3E,2EAA2E;IAC3E,0DAA0D;IAC1D,MAAMkC,eAAehC,MAAMiC,OAAO,CAACC,WAAW,GAAG,SAAS;IAC1D,OAAO5C,qBACLuC,KACA7B,OACAmB,YACAF,qBACAc,aACAZ,YACAI,uBACAvB,MAAMmC,KAAK,EACXV,0BACAZ,iBACAE,mBACAW,gBACAM,cACAJ,gBACA,wCAAwC;IACxCnC,iBACA,MACA,sEAAsE;IACtE,oEAAoE;IACpE,wEAAwE;IACxE,8BAA8B;IAC9B,MACAqB;AAEJ","ignoreList":[0]} |
@@ -5,2 +5,3 @@ import { extractPathFromFlightRouterState } from '../compute-changed-path'; | ||
| import { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response'; | ||
| import { segmentCacheMap } from '../../segment-cache/cache'; | ||
| import { UnknownDynamicStaleTime } from '../../segment-cache/bfcache'; | ||
@@ -35,3 +36,4 @@ export function restoreReducer(state, action) { | ||
| const restoreSeed = convertServerPatchToFullTree(now, treeToRestore, null, renderedSearch, UnknownDynamicStaleTime); | ||
| const task = startPPRNavigation(now, currentUrl, state.renderedSearch, state.cache, state.tree, restoreSeed.routeTree, restoreSeed.metadataVaryPath, FreshnessPolicy.HistoryTraversal, null, restoreSeed.dynamicStaleAt, false, accumulation, // A history-traversal restore never restricts to the shell. | ||
| const task = startPPRNavigation(now, currentUrl, state.renderedSearch, state.cache, state.tree, restoreSeed.routeTree, restoreSeed.metadataVaryPath, FreshnessPolicy.HistoryTraversal, null, restoreSeed.dynamicStaleAt, false, accumulation, // A history-traversal restore is bound to the shared map. | ||
| segmentCacheMap, // A history-traversal restore never restricts to the shell. | ||
| false); | ||
@@ -49,3 +51,4 @@ if (task === null) { | ||
| // normally rather than being withheld behind the lock. | ||
| null, // Not an HMR refresh, so there's no request generation to cancel. | ||
| null, // A history-traversal restore is bound to the shared map. | ||
| segmentCacheMap, // Not an HMR refresh, so there's no request generation to cancel. | ||
| undefined); | ||
@@ -52,0 +55,0 @@ // Instant Navigation Testing API: a traversal resets the lock to a fresh |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../../src/client/components/router-reducer/reducers/restore-reducer.ts"],"sourcesContent":["import type {\n ReadonlyReducerState,\n ReducerState,\n RestoreAction,\n} from '../router-reducer-types'\nimport { extractPathFromFlightRouterState } from '../compute-changed-path'\nimport {\n FreshnessPolicy,\n resetNavigationLockToPending,\n spawnDynamicRequests,\n startPPRNavigation,\n type NavigationRequestAccumulation,\n} from '../ppr-navigations'\nimport type { FlightRouterState } from '../../../../shared/lib/app-router-types'\nimport {\n completeHardNavigation,\n completeTraverseNavigation,\n} from '../../segment-cache/navigation'\nimport { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response'\nimport { UnknownDynamicStaleTime } from '../../segment-cache/bfcache'\n\nexport function restoreReducer(\n state: ReadonlyReducerState,\n action: RestoreAction\n): ReducerState {\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 let treeToRestore: FlightRouterState | undefined\n let renderedSearch: string | undefined\n const historyState = action.historyState\n if (historyState) {\n treeToRestore = historyState.tree\n renderedSearch = historyState.renderedSearch\n } else {\n treeToRestore = state.tree\n renderedSearch = state.renderedSearch\n }\n\n const currentUrl = new URL(state.canonicalUrl, location.origin)\n const restoredUrl = action.url\n const restoredNextUrl =\n extractPathFromFlightRouterState(treeToRestore) ?? restoredUrl.pathname\n\n const now = Date.now()\n // TODO: Store the dynamic stale time on the top-level state so it's known\n // during restores and refreshes.\n const accumulation: NavigationRequestAccumulation = {\n separateRefreshUrls: null,\n scrollRef: null,\n }\n const restoreSeed = convertServerPatchToFullTree(\n now,\n treeToRestore,\n null,\n renderedSearch,\n UnknownDynamicStaleTime\n )\n const task = startPPRNavigation(\n now,\n currentUrl,\n state.renderedSearch,\n state.cache,\n state.tree,\n restoreSeed.routeTree,\n restoreSeed.metadataVaryPath,\n FreshnessPolicy.HistoryTraversal,\n null,\n restoreSeed.dynamicStaleAt,\n false,\n accumulation,\n // A history-traversal restore never restricts to the shell.\n false\n )\n\n if (task === null) {\n return completeHardNavigation(state, restoredUrl, 'replace')\n }\n spawnDynamicRequests(\n task,\n restoredUrl,\n restoredNextUrl,\n FreshnessPolicy.HistoryTraversal,\n accumulation,\n // History traversal doesn't use route prediction, so there's no route\n // cache entry to mark as having a dynamic rewrite on mismatch. If a\n // mismatch occurs, the retry handler will traverse the known route tree\n // to find and mark the entry.\n null,\n // History traversal always uses 'replace'.\n 'replace',\n // Instant Navigation Testing API: a traversal is not a capture. Spawn its\n // dynamic requests ungated (null lock) so they render from cache or fetch\n // normally rather than being withheld behind the lock.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n // Instant Navigation Testing API: a traversal resets the lock to a fresh\n // pending scope — releasing any data withheld by prior forward navigations and\n // returning the panel to \"awaiting\" — without ending the testing session.\n // No-op when the testing API is disabled or no lock is held.\n resetNavigationLockToPending()\n return completeTraverseNavigation(\n state,\n restoredUrl,\n renderedSearch,\n task.node,\n task.route,\n restoredNextUrl\n )\n}\n"],"names":["extractPathFromFlightRouterState","FreshnessPolicy","resetNavigationLockToPending","spawnDynamicRequests","startPPRNavigation","completeHardNavigation","completeTraverseNavigation","convertServerPatchToFullTree","UnknownDynamicStaleTime","restoreReducer","state","action","treeToRestore","renderedSearch","historyState","tree","currentUrl","URL","canonicalUrl","location","origin","restoredUrl","url","restoredNextUrl","pathname","now","Date","accumulation","separateRefreshUrls","scrollRef","restoreSeed","task","cache","routeTree","metadataVa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,OAAO1B,uBAAuBK,OAAOW,aAAa;IACpD;IACAlB,qBACE4B,MACAV,aACAE,iBACAtB,gBAAgBkC,gBAAgB,EAChCR,cACA,sEAAsE;IACtE,oEAAoE;IACpE,wEAAwE;IACxE,8BAA8B;IAC9B,MACA,2CAA2C;IAC3C,WACA,0EAA0E;IAC1E,0EAA0E;IAC1E,uDAAuD;IACvD,MACA,kEAAkE;IAClEU;IAEF,yEAAyE;IACzE,+EAA+E;IAC/E,0EAA0E;IAC1E,6DAA6D;IAC7DnC;IACA,OAAOI,2BACLI,OACAW,aACAR,gBACAkB,KAAKO,IAAI,EACTP,KAAKQ,KAAK,EACVhB;AAEJ","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../../src/client/components/router-reducer/reducers/restore-reducer.ts"],"sourcesContent":["import type {\n ReadonlyReducerState,\n ReducerState,\n RestoreAction,\n} from '../router-reducer-types'\nimport { extractPathFromFlightRouterState } from '../compute-changed-path'\nimport {\n FreshnessPolicy,\n resetNavigationLockToPending,\n spawnDynamicRequests,\n startPPRNavigation,\n type NavigationRequestAccumulation,\n} from '../ppr-navigations'\nimport type { FlightRouterState } from '../../../../shared/lib/app-router-types'\nimport {\n completeHardNavigation,\n completeTraverseNavigation,\n} from '../../segment-cache/navigation'\nimport { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response'\nimport { segmentCacheMap } from '../../segment-cache/cache'\nimport { UnknownDynamicStaleTime } from '../../segment-cache/bfcache'\n\nexport function restoreReducer(\n state: ReadonlyReducerState,\n action: RestoreAction\n): ReducerState {\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 let treeToRestore: FlightRouterState | undefined\n let renderedSearch: string | undefined\n const historyState = action.historyState\n if (historyState) {\n treeToRestore = historyState.tree\n renderedSearch = historyState.renderedSearch\n } else {\n treeToRestore = state.tree\n renderedSearch = state.renderedSearch\n }\n\n const currentUrl = new URL(state.canonicalUrl, location.origin)\n const restoredUrl = action.url\n const restoredNextUrl =\n extractPathFromFlightRouterState(treeToRestore) ?? restoredUrl.pathname\n\n const now = Date.now()\n // TODO: Store the dynamic stale time on the top-level state so it's known\n // during restores and refreshes.\n const accumulation: NavigationRequestAccumulation = {\n separateRefreshUrls: null,\n scrollRef: null,\n }\n const restoreSeed = convertServerPatchToFullTree(\n now,\n treeToRestore,\n null,\n renderedSearch,\n UnknownDynamicStaleTime\n )\n const task = startPPRNavigation(\n now,\n currentUrl,\n state.renderedSearch,\n state.cache,\n state.tree,\n restoreSeed.routeTree,\n restoreSeed.metadataVaryPath,\n FreshnessPolicy.HistoryTraversal,\n null,\n restoreSeed.dynamicStaleAt,\n false,\n accumulation,\n // A history-traversal restore is bound to the shared map.\n segmentCacheMap,\n // A history-traversal restore never restricts to the shell.\n false\n )\n\n if (task === null) {\n return completeHardNavigation(state, restoredUrl, 'replace')\n }\n spawnDynamicRequests(\n task,\n restoredUrl,\n restoredNextUrl,\n FreshnessPolicy.HistoryTraversal,\n accumulation,\n // History traversal doesn't use route prediction, so there's no route\n // cache entry to mark as having a dynamic rewrite on mismatch. If a\n // mismatch occurs, the retry handler will traverse the known route tree\n // to find and mark the entry.\n null,\n // History traversal always uses 'replace'.\n 'replace',\n // Instant Navigation Testing API: a traversal is not a capture. Spawn its\n // dynamic requests ungated (null lock) so they render from cache or fetch\n // normally rather than being withheld behind the lock.\n null,\n // A history-traversal restore is bound to the shared map.\n segmentCacheMap,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n // Instant Navigation Testing API: a traversal resets the lock to a fresh\n // pending scope — releasing any data withheld by prior forward navigations and\n // returning the panel to \"awaiting\" — without ending the testing session.\n // No-op when the testing API is disabled or no lock is held.\n resetNavigationLockToPending()\n return completeTraverseNavigation(\n state,\n restoredUrl,\n renderedSearch,\n task.node,\n task.route,\n restoredNextUrl\n )\n}\n"],"names":["extractPathFromFlightRouterState","FreshnessPolicy","resetNavigationLockToPending","spawnDynamicRequests","startPPRNavigation","completeHardNavigation","completeTraverseNavigation","convertServerPatchToFullTree","segmentCacheMap","UnknownDynamicStaleTime","restoreReducer","state","action","treeToRestore","renderedSearch","historyState","tree","currentUrl","URL","canonicalUrl","location","origin","restoredUrl","url","restoredNextUrl","pathname","now","Date","accumulation","separateRefreshUrls","scrollRef","restoreSeed","task","cache","routeTree","metadataVaryPath","HistoryTraversal","dynamicStaleAt","undefined","node","route"],"mappings":"AAKA,SAASA,gCAAgC,QAAQ,0BAAyB;AAC1E,SACEC,eAAe,EACfC,4BAA4B,EAC5BC,oBAAoB,EACpBC,kBAAkB,QAEb,qBAAoB;AAE3B,SACEC,sBAAsB,EACtBC,0BAA0B,QACrB,iCAAgC;AACvC,SAASC,4BAA4B,QAAQ,6CAA4C;AACzF,SAASC,eAAe,QAAQ,4BAA2B;AAC3D,SAASC,uBAAuB,QAAQ,8BAA6B;AAErE,OAAO,SAASC,eACdC,KAA2B,EAC3BC,MAAqB;IAErB,0EAA0E;IAC1E,4FAA4F;IAC5F,gGAAgG;IAChG,6FAA6F;IAC7F,8DAA8D;IAC9D,yGAAyG;IACzG,IAAIC;IACJ,IAAIC;IACJ,MAAMC,eAAeH,OAAOG,YAAY;IACxC,IAAIA,cAAc;QAChBF,gBAAgBE,aAAaC,IAAI;QACjCF,iBAAiBC,aAAaD,cAAc;IAC9C,OAAO;QACLD,gBAAgBF,MAAMK,IAAI;QAC1BF,iBAAiBH,MAAMG,cAAc;IACvC;IAEA,MAAMG,aAAa,IAAIC,IAAIP,MAAMQ,YAAY,EAAEC,SAASC,MAAM;IAC9D,MAAMC,cAAcV,OAAOW,GAAG;IAC9B,MAAMC,kBACJxB,iCAAiCa,kBAAkBS,YAAYG,QAAQ;IAEzE,MAAMC,MAAMC,KAAKD,GAAG;IACpB,0EAA0E;IAC1E,iCAAiC;IACjC,MAAME,eAA8C;QAClDC,qBAAqB;QACrBC,WAAW;IACb;IACA,MAAMC,cAAcxB,6BAClBmB,KACAb,eACA,MACAC,gBACAL;IAEF,MAAMuB,OAAO5B,mBACXsB,KACAT,YACAN,MAAMG,cAAc,EACpBH,MAAMsB,KAAK,EACXtB,MAAMK,IAAI,EACVe,YAAYG,SAAS,EACrBH,YAAYI,gBAAgB,EAC5BlC,gBAAgBmC,gBAAgB,EAChC,MACAL,YAAYM,cAAc,EAC1B,OACAT,cACA,0DAA0D;IAC1DpB,iBACA,4DAA4D;IAC5D;IAGF,IAAIwB,SAAS,MAAM;QACjB,OAAO3B,uBAAuBM,OAAOW,aAAa;IACpD;IACAnB,qBACE6B,MACAV,aACAE,iBACAvB,gBAAgBmC,gBAAgB,EAChCR,cACA,sEAAsE;IACtE,oEAAoE;IACpE,wEAAwE;IACxE,8BAA8B;IAC9B,MACA,2CAA2C;IAC3C,WACA,0EAA0E;IAC1E,0EAA0E;IAC1E,uDAAuD;IACvD,MACA,0DAA0D;IAC1DpB,iBACA,kEAAkE;IAClE8B;IAEF,yEAAyE;IACzE,+EAA+E;IAC/E,0EAA0E;IAC1E,6DAA6D;IAC7DpC;IACA,OAAOI,2BACLK,OACAW,aACAR,gBACAkB,KAAKO,IAAI,EACTP,KAAKQ,KAAK,EACVhB;AAEJ","ignoreList":[0]} |
@@ -18,3 +18,3 @@ import { callServer } from '../../../app-call-server'; | ||
| import { extractInfoFromServerReferenceId, omitUnusedArgs } from '../../../../shared/lib/server-reference-info'; | ||
| import { invalidateEntirePrefetchCache } from '../../segment-cache/cache'; | ||
| import { invalidateEntirePrefetchCache, segmentCacheMap } from '../../segment-cache/cache'; | ||
| import { startRevalidationCooldown } from '../../segment-cache/scheduler'; | ||
@@ -319,3 +319,4 @@ import { getDeploymentId } from '../../../../shared/lib/deployment-id'; | ||
| const navigationLock = getCurrentNavigationLock(); | ||
| return navigateToKnownRoute(now, state, redirectUrl, redirectCanonicalUrl, redirectSeed, currentUrl, currentRenderedSearch, state.cache, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, null, // Server action redirects don't use route prediction - we already | ||
| return navigateToKnownRoute(now, state, redirectUrl, redirectCanonicalUrl, redirectSeed, currentUrl, currentRenderedSearch, state.cache, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, // A server-action redirect navigation is bound to the shared map. | ||
| segmentCacheMap, null, // Server action redirects don't use route prediction - we already | ||
| // have the route tree from the server response. If a mismatch occurs | ||
@@ -322,0 +323,0 @@ // during dynamic data fetch, the retry handler will traverse the |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../../src/client/components/router-reducer/reducers/server-action-reducer.ts"],"sourcesContent":["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 NEXT_REQUEST_ID_HEADER,\n} from '../../app-router-headers'\nimport { UnrecognizedActionError } from '../../unrecognized-action-error'\nimport { fetch } from '../../segment-cache/fetch'\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 type {\n ReadonlyReducerState,\n ReducerState,\n ServerActionAction,\n} from '../router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer-types'\nimport { assignLocation } from '../../../assign-location'\nimport { createHrefFromUrl } from '../create-href-from-url'\nimport type { PartialTransportData } from '../../../../shared/lib/rsc-transport'\nimport { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'\nimport { prepareFlightRouterStateForRequest } from '../../../flight-data-helpers'\nimport { getRedirectError } from '../../redirect'\nimport type { RedirectType } from '../../redirect-error'\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 { invalidateEntirePrefetchCache } from '../../segment-cache/cache'\nimport { startRevalidationCooldown } from '../../segment-cache/scheduler'\nimport { getDeploymentId } from '../../../../shared/lib/deployment-id'\nimport { getNavigationBuildId } from '../../../navigation-build-id'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../../lib/constants'\nimport {\n completeHardNavigation,\n navigateToKnownRoute,\n navigate,\n} from '../../segment-cache/navigation'\nimport { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response'\nimport { discoverKnownRoute } from '../../segment-cache/optimistic-routes'\nimport type { NormalizedSearch } from '../../segment-cache/cache-key'\nimport {\n ActionDidNotRevalidate,\n ActionDidRevalidateDynamicOnly,\n ActionDidRevalidateStaticAndDynamic,\n type ActionRevalidationKind,\n} from '../../../../shared/lib/action-revalidation-kind'\nimport { isExternalURL } from '../../app-router-utils'\nimport { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations'\nimport { processFetch } from '../fetch-server-response'\nimport {\n invalidateBfCache,\n UnknownDynamicStaleTime,\n} from '../../segment-cache/bfcache'\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.__NEXT_DEV_SERVER && process.env.__NEXT_REACT_DEBUG_CHANNEL) {\n createDebugChannel = (\n require('../../../dev/debug-channel') as typeof import('../../../dev/debug-channel')\n ).createDebugChannel\n}\n\n// TODO: Refactor to be a discriminated union. Or just get rid of it;\n// fetchServerAction only has one caller, no reason this intermediate type has\n// to exist.\ntype FetchServerActionResult = {\n redirectLocation: URL | undefined\n redirectType: RedirectType | undefined\n revalidationKind: ActionRevalidationKind\n actionResult: ActionResult | undefined\n /**\n * The transport data from the action response, or a URL string when the\n * response handling triggered an external (MPA) redirect.\n */\n actionFlightData: PartialTransportData | string | undefined\n actionFlightDataRenderedSearch: NormalizedSearch | undefined\n isPrerender: boolean\n couldBeIntercepted: boolean\n}\n\nasync function fetchServerAction(\n state: ReadonlyReducerState,\n nextUrl: ReadonlyReducerState['nextUrl'],\n action: ServerActionAction\n): Promise<FetchServerActionResult> {\n const { actionId, actionArgs } = action\n const temporaryReferences = createTemporaryReferenceSet()\n const info = extractInfoFromServerReferenceId(actionId)\n const usedArgs = omitUnusedArgs(actionArgs, info)\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 const deploymentId = getDeploymentId()\n if (deploymentId) {\n headers['x-deployment-id'] = deploymentId\n }\n\n if (nextUrl) {\n headers[NEXT_URL] = nextUrl\n }\n\n if (process.env.__NEXT_DEV_SERVER) {\n if (self.__next_r) {\n headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r\n }\n\n // Create a new request ID for the server action request. The server uses\n // this to tag debug information sent via WebSocket to the client, which\n // then routes those chunks to the debug channel associated with this ID.\n headers[NEXT_REQUEST_ID_HEADER] = crypto\n .getRandomValues(new Uint32Array(1))[0]\n .toString(16)\n }\n\n let res: Response\n try {\n res = await fetch(state.canonicalUrl, { method: 'POST', headers, body })\n // If the fetch succeeds while we're in the offline state, notify the\n // offline module so it can short-circuit the polling loop.\n if (process.env.__NEXT_USE_OFFLINE) {\n const { notifyOnline } =\n require('../../offline') as typeof import('../../offline')\n notifyOnline()\n }\n } catch (err) {\n if (process.env.__NEXT_USE_OFFLINE) {\n const { checkOfflineError, getOffline, waitForConnection } =\n require('../../offline') as typeof import('../../offline')\n if (checkOfflineError(err)) {\n // It's safe to replay the action because the fetch rejection\n // means the request never reached the server — there are no\n // side effects to duplicate.\n const offline = getOffline()\n if (offline !== null) {\n await waitForConnection(offline)\n }\n return fetchServerAction(state, nextUrl, action)\n }\n }\n throw err\n }\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 = 'push'\n break\n case 'replace':\n redirectType = 'replace'\n break\n default:\n redirectType = undefined\n }\n\n const isPrerender = !!res.headers.get(NEXT_IS_PRERENDER_HEADER)\n\n let revalidationKind: ActionRevalidationKind = ActionDidNotRevalidate\n try {\n const revalidationHeader = res.headers.get('x-action-revalidated')\n if (revalidationHeader) {\n const parsedKind = JSON.parse(revalidationHeader)\n if (\n parsedKind === ActionDidRevalidateStaticAndDynamic ||\n parsedKind === ActionDidRevalidateDynamicOnly\n ) {\n revalidationKind = parsedKind\n }\n }\n } catch {}\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 let actionFlightDataRenderedSearch: FetchServerActionResult['actionFlightDataRenderedSearch']\n let couldBeIntercepted: boolean = false\n\n if (isRscResponse) {\n // Server action redirect responses carry the Flight data of the redirect\n // target, which may be prerendered with a completeness marker byte\n // prepended. Strip it before passing to Flight.\n const responsePromise = redirectLocation\n ? processFetch(res).then(({ response: r }) => r)\n : Promise.resolve(res)\n\n const response: ActionFlightResponse = await createFromFetch(\n responsePromise,\n {\n callServer,\n findSourceMapURL,\n temporaryReferences,\n debugChannel: createDebugChannel && createDebugChannel(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 couldBeIntercepted = response.i\n\n // Check if the response build ID matches the client build ID.\n // In a multi-zone setup, when a server action triggers a redirect,\n // the server pre-fetches the redirect target as RSC. If the redirect\n // target is served by a different Next.js zone (different build), the\n // pre-fetched RSC data will have a foreign build ID. We must discard\n // the flight data in that case so the redirect triggers an MPA\n // navigation (full page load) instead of trying to apply the foreign\n // RSC payload — which would result in a blank page.\n const responseBuildId =\n res.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? response.b\n if (\n responseBuildId !== undefined &&\n responseBuildId !== getNavigationBuildId()\n ) {\n // Build ID mismatch — discard the flight data. The redirect will\n // still be processed, and the absence of flight data will cause an\n // MPA navigation via completeHardNavigation().\n } else {\n if (response.t !== undefined) {\n actionFlightData = response.t\n actionFlightDataRenderedSearch = response.q as NormalizedSearch\n } else if (response.n !== undefined) {\n // The server responded with an MPA navigation URL.\n actionFlightData = response.n\n }\n }\n } else {\n // An external redirect doesn't contain RSC data.\n actionResult = undefined\n actionFlightData = undefined\n actionFlightDataRenderedSearch = undefined\n }\n\n return {\n actionResult,\n actionFlightData,\n actionFlightDataRenderedSearch,\n redirectLocation,\n redirectType,\n revalidationKind,\n isPrerender,\n couldBeIntercepted,\n }\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\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 // We always send the last next-url, not the current when\n // performing a dynamic request. This is because we update\n // the next-url after a navigation, but we want the same\n // interception route to be matched that used the last\n // next-url.\n (state.previousNextUrl || state.nextUrl) &&\n hasInterceptionRouteInCurrentTree(state.tree)\n ? state.previousNextUrl || state.nextUrl\n : null\n\n return fetchServerAction(state, nextUrl, action).then(\n async ({\n revalidationKind,\n actionResult,\n actionFlightData: flightData,\n actionFlightDataRenderedSearch: flightDataRenderedSearch,\n redirectLocation,\n redirectType,\n isPrerender,\n couldBeIntercepted,\n }) => {\n if (revalidationKind !== ActionDidNotRevalidate) {\n // There was either a revalidation or a refresh, or maybe both.\n\n // Evict the BFCache, which may contain dynamic data.\n invalidateBfCache()\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 action.didRevalidate = true\n\n // If there was a revalidation, evict the prefetch cache.\n // TODO: Evict only segments with matching tags and/or paths.\n // TODO: We should only invalidate the route cache if cookies were\n // mutated, since route trees may vary based on cookies. For now we\n // invalidate both caches until we have a way to detect cookie\n // mutations on the client.\n if (revalidationKind === ActionDidRevalidateStaticAndDynamic) {\n invalidateEntirePrefetchCache(nextUrl, state.tree)\n }\n\n // Start a cooldown before re-prefetching to allow CDN cache\n // propagation.\n startRevalidationCooldown()\n }\n\n const navigateType = redirectType || 'push'\n\n if (redirectLocation !== undefined) {\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\n if (isExternalURL(redirectLocation)) {\n // External redirect. Triggers an MPA navigation.\n const redirectHref = redirectLocation.href\n const redirectError = createRedirectErrorForAction(\n redirectHref,\n navigateType\n )\n reject(redirectError)\n return completeHardNavigation(state, redirectLocation, navigateType)\n } else {\n // Internal redirect. Triggers an SPA navigation.\n const redirectWithBasepath = createHrefFromUrl(\n redirectLocation,\n false\n )\n const redirectHref = hasBasePath(redirectWithBasepath)\n ? removeBasePath(redirectWithBasepath)\n : redirectWithBasepath\n const redirectError = createRedirectErrorForAction(\n redirectHref,\n navigateType\n )\n reject(redirectError)\n }\n } else {\n // If there's no redirect, resolve the action with the result.\n resolve(actionResult)\n }\n\n // Check if we can bail out without updating any state.\n if (\n // Did the action trigger a redirect?\n redirectLocation === undefined &&\n // Did the action revalidate any data?\n revalidationKind === ActionDidNotRevalidate &&\n // Did the server render new data?\n flightData === undefined\n ) {\n // The action did not trigger any revalidations or redirects. No\n // navigation is required.\n return state\n }\n\n if (flightData === undefined && redirectLocation !== undefined) {\n // The server redirected, but did not send any Flight data. This implies\n // an external redirect.\n // TODO: We should refactor the action response type to be more explicit\n // about the various response types.\n return completeHardNavigation(state, redirectLocation, navigateType)\n }\n\n if (typeof flightData === 'string') {\n // If the flight data is just a string, something earlier in the\n // response handling triggered an external redirect.\n return completeHardNavigation(\n state,\n new URL(flightData, location.origin),\n navigateType\n )\n }\n\n // The action triggered a navigation — either a redirect, a revalidation,\n // or both.\n\n // If there was no redirect, then the target URL is the same as the\n // current URL.\n const currentUrl = new URL(state.canonicalUrl, location.origin)\n const currentRenderedSearch = state.renderedSearch\n const redirectUrl =\n redirectLocation !== undefined ? redirectLocation : currentUrl\n const currentFlightRouterState = state.tree\n const scrollBehavior = ScrollBehavior.Default\n\n // If the action triggered a revalidation of the cache, we should also\n // refresh all the dynamic data.\n const freshnessPolicy =\n revalidationKind === ActionDidNotRevalidate\n ? FreshnessPolicy.Default\n : FreshnessPolicy.RefreshAll\n\n // The server may have sent back new data. If so, we will perform a\n // \"seeded\" navigation that uses the data from the response.\n // TODO: Currently the server always renders from the root in\n // response to a Server Action. In the case of a normal redirect\n // with no revalidation, it should skip over the shared layouts.\n if (flightData !== undefined && flightDataRenderedSearch !== undefined) {\n // The server sent back new route data as part of the response. We\n // will use this to render the new page. If this happens to be only a\n // subset of the data needed to render the new page, we'll initiate a\n // new fetch, like we would for a normal navigation.\n const redirectCanonicalUrl = createHrefFromUrl(redirectUrl)\n const now = Date.now()\n // TODO: Store the dynamic stale time on the top-level state so it's\n // known during restores and refreshes.\n const redirectSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n flightData,\n flightDataRenderedSearch,\n UnknownDynamicStaleTime\n )\n\n // Learn the route pattern so we can predict it for future navigations.\n const metadataVaryPath = redirectSeed.metadataVaryPath\n if (metadataVaryPath !== null) {\n discoverKnownRoute(\n now,\n redirectUrl.pathname,\n redirectUrl.search as NormalizedSearch,\n nextUrl,\n null, // No pending entry\n redirectSeed.routeTree,\n metadataVaryPath,\n couldBeIntercepted,\n redirectCanonicalUrl,\n isPrerender,\n false // hasDynamicRewrite\n )\n }\n const navigationLock = getCurrentNavigationLock()\n\n return navigateToKnownRoute(\n now,\n state,\n redirectUrl,\n redirectCanonicalUrl,\n redirectSeed,\n currentUrl,\n currentRenderedSearch,\n state.cache,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n null,\n // Server action redirects don't use route prediction - we already\n // have the route tree from the server response. If a mismatch occurs\n // during dynamic data fetch, the retry handler will traverse the\n // known route tree to mark the entry as having a dynamic rewrite.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n }\n\n // The server did not send back new data. We'll perform a regular, non-\n // seeded navigation — effectively the same as <Link> or router.push().\n return navigate(\n state,\n redirectUrl,\n currentUrl,\n currentRenderedSearch,\n state.cache,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType\n )\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\nfunction createRedirectErrorForAction(\n redirectHref: string,\n resolvedRedirectType: RedirectType\n) {\n const redirectError = getRedirectError(redirectHref, resolvedRedirectType)\n // We mark the error as handled because we don't want the redirect to be tried later by\n // the RedirectBoundary, in case the user goes back and `Activity` triggers the redirect\n // again, as it's run within an effect.\n // We don't actually need the RedirectBoundary to do a router.push because we already\n // have all the necessary RSC data to render the new page within a single roundtrip.\n ;(redirectError as any).handled = true\n return redirectError\n}\n"],"names":["callServer","findSourceMapURL","ACTION_HEADER","NEXT_ACTION_NOT_FOUND_HEADER","NEXT_IS_PRERENDER_HEADER","NEXT_HTML_REQUEST_ID_HEADER","NEXT_ROUTER_STATE_TREE_HEADER","NEXT_URL","RSC_CONTENT_TYPE_HEADER","NEXT_REQUEST_ID_HEADER","UnrecognizedActionError","fetch","createFromFetch","createFromFetchBrowser","createTemporaryReferenceSet","encodeReply","ScrollBehavior","assignLocation","createHrefFromUrl","hasInterceptionRouteInCurrentTree","prepareFlightRouterStateForRequest","getRedirectError","removeBasePath","hasBasePath","extractInfoFromServerReferenceId","omitUnusedArgs","invalidateEntirePrefetchCache","startRevalidationCooldown","getDeploymentId","getNavigationBuildId","NEXT_NAV_DEPLOYMENT_ID_HEADER","completeHardNavigation","navigateToKnownRoute","navigate","convertServerPatchToFullTree","discoverKnownRoute","ActionDidNotRevalidate","ActionDidRevalidateDynamicOnly","ActionDidRevalidateStaticAndDynamic","isExternalURL","FreshnessPolicy","getCurrentNavigationLock","processFetch","invalidateBfCache","UnknownDynamicStaleTime","createDebugChannel","process","env","__NEXT_DEV_SERVER","__NEXT_REACT_DEBUG_CHANNEL","require","fetchServerAction","state","nextUrl","action","actionId","actionArgs","temporaryReferences","info","usedArgs","body","headers","Accept","tree","deploymentId","self","__next_r","crypto","getRandomValues","Uint32Array","toString","res","canonicalUrl","method","__NEXT_USE_OFFLINE","notifyOnline","err","checkOfflineError","getOffline","waitForConnection","offline","unrecognizedActionHeader","get","redirectHeader","location","_redirectType","split","redirectType","undefined","isPrerender","revalidationKind","revalidationHeader","parsedKind","JSON","parse","redirectLocation","URL","window","href","contentType","isRscResponse","startsWith","message","status","text","Error","actionResult","actionFlightData","actionFlightDataRenderedSearch","couldBeIntercepted","responsePromise","then","response","r","Promise","resolve","debugChannel","a","i","responseBuildId","b","t","q","n","serverActionReducer","reject","previousNextUrl","flightData","flightDataRenderedSearch","didRevalidate","navigateType","redirectHref","redirectError","createRedirectErrorForAction","redirectWithBasepath","origin","currentUrl","currentRenderedSearch","renderedSearch","redirectUrl","currentFlightRouterState","scrollBehavior","Default","freshnessPolicy","RefreshAll","redirectCanonicalUrl","now","Date","redirectSeed","metadataVaryPath","pathname","search","routeTree","navigationLock","cache","e","resolvedRedirectType","handled"],"mappings":"AAIA,SAASA,UAAU,QAAQ,2BAA0B;AACrD,SAASC,gBAAgB,QAAQ,mCAAkC;AACnE,SACEC,aAAa,EACbC,4BAA4B,EAC5BC,wBAAwB,EACxBC,2BAA2B,EAC3BC,6BAA6B,EAC7BC,QAAQ,EACRC,uBAAuB,EACvBC,sBAAsB,QACjB,2BAA0B;AACjC,SAASC,uBAAuB,QAAQ,kCAAiC;AACzE,SAASC,KAAK,QAAQ,4BAA2B;AAEjD,8CAA8C;AAC9C,6DAA6D;AAC7D,SACEC,mBAAmBC,sBAAsB,EACzCC,2BAA2B,EAC3BC,WAAW,QACN,kCAAiC;AAOxC,SAASC,cAAc,QAAQ,0BAAyB;AACxD,SAASC,cAAc,QAAQ,2BAA0B;AACzD,SAASC,iBAAiB,QAAQ,0BAAyB;AAE3D,SAASC,iCAAiC,QAAQ,2CAA0C;AAC5F,SAASC,kCAAkC,QAAQ,+BAA8B;AACjF,SAASC,gBAAgB,QAAQ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C/C,MAAMO,MAAMC,KAAKD,GAAG;YACpB,oEAAoE;YACpE,uCAAuC;YACvC,MAAME,eAAelH,6BACnBgH,KACAN,0BACAb,YACAC,0BACApF;YAGF,uEAAuE;YACvE,MAAMyG,mBAAmBD,aAAaC,gBAAgB;YACtD,IAAIA,qBAAqB,MAAM;gBAC7BlH,mBACE+G,KACAP,YAAYW,QAAQ,EACpBX,YAAYY,MAAM,EAClBlG,SACA,MACA+F,aAAaI,SAAS,EACtBH,kBACAxC,oBACAoC,sBACAxD,aACA,MAAM,oBAAoB;;YAE9B;YACA,MAAMgE,iBAAiBhH;YAEvB,OAAOT,qBACLkH,KACA9F,OACAuF,aACAM,sBACAG,cACAZ,YACAC,uBACArF,MAAMsG,KAAK,EACXd,0BACAG,iBACA1F,SACAwF,gBACAX,cACAuB,gBACA,MACA,kEAAkE;YAClE,qEAAqE;YACrE,iEAAiE;YACjE,kEAAkE;YAClE,MACA,kEAAkE;YAClEjE;QAEJ;QAEA,uEAAuE;QACvE,uEAAuE;QACvE,OAAOvD,SACLmB,OACAuF,aACAH,YACAC,uBACArF,MAAMsG,KAAK,EACXd,0BACAvF,SACA0F,iBACAF,gBACAX;IAEJ,GACA,CAACyB;QACC,mHAAmH;QACnH9B,OAAO8B;QAEP,OAAOvG;IACT;AAEJ;AAEA,SAASiF,6BACPF,YAAoB,EACpByB,oBAAkC;IAElC,MAAMxB,gBAAgB/G,iBAAiB8G,cAAcyB;IAMnDxB,cAAsByB,OAAO,GAAG;IAClC,OAAOzB;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../../src/client/components/router-reducer/reducers/server-action-reducer.ts"],"sourcesContent":["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 NEXT_REQUEST_ID_HEADER,\n} from '../../app-router-headers'\nimport { UnrecognizedActionError } from '../../unrecognized-action-error'\nimport { fetch } from '../../segment-cache/fetch'\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 type {\n ReadonlyReducerState,\n ReducerState,\n ServerActionAction,\n} from '../router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer-types'\nimport { assignLocation } from '../../../assign-location'\nimport { createHrefFromUrl } from '../create-href-from-url'\nimport type { PartialTransportData } from '../../../../shared/lib/rsc-transport'\nimport { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'\nimport { prepareFlightRouterStateForRequest } from '../../../flight-data-helpers'\nimport { getRedirectError } from '../../redirect'\nimport type { RedirectType } from '../../redirect-error'\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 {\n invalidateEntirePrefetchCache,\n segmentCacheMap,\n} from '../../segment-cache/cache'\nimport { startRevalidationCooldown } from '../../segment-cache/scheduler'\nimport { getDeploymentId } from '../../../../shared/lib/deployment-id'\nimport { getNavigationBuildId } from '../../../navigation-build-id'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../../lib/constants'\nimport {\n completeHardNavigation,\n navigateToKnownRoute,\n navigate,\n} from '../../segment-cache/navigation'\nimport { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response'\nimport { discoverKnownRoute } from '../../segment-cache/optimistic-routes'\nimport type { NormalizedSearch } from '../../segment-cache/cache-key'\nimport {\n ActionDidNotRevalidate,\n ActionDidRevalidateDynamicOnly,\n ActionDidRevalidateStaticAndDynamic,\n type ActionRevalidationKind,\n} from '../../../../shared/lib/action-revalidation-kind'\nimport { isExternalURL } from '../../app-router-utils'\nimport { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations'\nimport { processFetch } from '../fetch-server-response'\nimport {\n invalidateBfCache,\n UnknownDynamicStaleTime,\n} from '../../segment-cache/bfcache'\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.__NEXT_DEV_SERVER && process.env.__NEXT_REACT_DEBUG_CHANNEL) {\n createDebugChannel = (\n require('../../../dev/debug-channel') as typeof import('../../../dev/debug-channel')\n ).createDebugChannel\n}\n\n// TODO: Refactor to be a discriminated union. Or just get rid of it;\n// fetchServerAction only has one caller, no reason this intermediate type has\n// to exist.\ntype FetchServerActionResult = {\n redirectLocation: URL | undefined\n redirectType: RedirectType | undefined\n revalidationKind: ActionRevalidationKind\n actionResult: ActionResult | undefined\n /**\n * The transport data from the action response, or a URL string when the\n * response handling triggered an external (MPA) redirect.\n */\n actionFlightData: PartialTransportData | string | undefined\n actionFlightDataRenderedSearch: NormalizedSearch | undefined\n isPrerender: boolean\n couldBeIntercepted: boolean\n}\n\nasync function fetchServerAction(\n state: ReadonlyReducerState,\n nextUrl: ReadonlyReducerState['nextUrl'],\n action: ServerActionAction\n): Promise<FetchServerActionResult> {\n const { actionId, actionArgs } = action\n const temporaryReferences = createTemporaryReferenceSet()\n const info = extractInfoFromServerReferenceId(actionId)\n const usedArgs = omitUnusedArgs(actionArgs, info)\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 const deploymentId = getDeploymentId()\n if (deploymentId) {\n headers['x-deployment-id'] = deploymentId\n }\n\n if (nextUrl) {\n headers[NEXT_URL] = nextUrl\n }\n\n if (process.env.__NEXT_DEV_SERVER) {\n if (self.__next_r) {\n headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r\n }\n\n // Create a new request ID for the server action request. The server uses\n // this to tag debug information sent via WebSocket to the client, which\n // then routes those chunks to the debug channel associated with this ID.\n headers[NEXT_REQUEST_ID_HEADER] = crypto\n .getRandomValues(new Uint32Array(1))[0]\n .toString(16)\n }\n\n let res: Response\n try {\n res = await fetch(state.canonicalUrl, { method: 'POST', headers, body })\n // If the fetch succeeds while we're in the offline state, notify the\n // offline module so it can short-circuit the polling loop.\n if (process.env.__NEXT_USE_OFFLINE) {\n const { notifyOnline } =\n require('../../offline') as typeof import('../../offline')\n notifyOnline()\n }\n } catch (err) {\n if (process.env.__NEXT_USE_OFFLINE) {\n const { checkOfflineError, getOffline, waitForConnection } =\n require('../../offline') as typeof import('../../offline')\n if (checkOfflineError(err)) {\n // It's safe to replay the action because the fetch rejection\n // means the request never reached the server — there are no\n // side effects to duplicate.\n const offline = getOffline()\n if (offline !== null) {\n await waitForConnection(offline)\n }\n return fetchServerAction(state, nextUrl, action)\n }\n }\n throw err\n }\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 = 'push'\n break\n case 'replace':\n redirectType = 'replace'\n break\n default:\n redirectType = undefined\n }\n\n const isPrerender = !!res.headers.get(NEXT_IS_PRERENDER_HEADER)\n\n let revalidationKind: ActionRevalidationKind = ActionDidNotRevalidate\n try {\n const revalidationHeader = res.headers.get('x-action-revalidated')\n if (revalidationHeader) {\n const parsedKind = JSON.parse(revalidationHeader)\n if (\n parsedKind === ActionDidRevalidateStaticAndDynamic ||\n parsedKind === ActionDidRevalidateDynamicOnly\n ) {\n revalidationKind = parsedKind\n }\n }\n } catch {}\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 let actionFlightDataRenderedSearch: FetchServerActionResult['actionFlightDataRenderedSearch']\n let couldBeIntercepted: boolean = false\n\n if (isRscResponse) {\n // Server action redirect responses carry the Flight data of the redirect\n // target, which may be prerendered with a completeness marker byte\n // prepended. Strip it before passing to Flight.\n const responsePromise = redirectLocation\n ? processFetch(res).then(({ response: r }) => r)\n : Promise.resolve(res)\n\n const response: ActionFlightResponse = await createFromFetch(\n responsePromise,\n {\n callServer,\n findSourceMapURL,\n temporaryReferences,\n debugChannel: createDebugChannel && createDebugChannel(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 couldBeIntercepted = response.i\n\n // Check if the response build ID matches the client build ID.\n // In a multi-zone setup, when a server action triggers a redirect,\n // the server pre-fetches the redirect target as RSC. If the redirect\n // target is served by a different Next.js zone (different build), the\n // pre-fetched RSC data will have a foreign build ID. We must discard\n // the flight data in that case so the redirect triggers an MPA\n // navigation (full page load) instead of trying to apply the foreign\n // RSC payload — which would result in a blank page.\n const responseBuildId =\n res.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? response.b\n if (\n responseBuildId !== undefined &&\n responseBuildId !== getNavigationBuildId()\n ) {\n // Build ID mismatch — discard the flight data. The redirect will\n // still be processed, and the absence of flight data will cause an\n // MPA navigation via completeHardNavigation().\n } else {\n if (response.t !== undefined) {\n actionFlightData = response.t\n actionFlightDataRenderedSearch = response.q as NormalizedSearch\n } else if (response.n !== undefined) {\n // The server responded with an MPA navigation URL.\n actionFlightData = response.n\n }\n }\n } else {\n // An external redirect doesn't contain RSC data.\n actionResult = undefined\n actionFlightData = undefined\n actionFlightDataRenderedSearch = undefined\n }\n\n return {\n actionResult,\n actionFlightData,\n actionFlightDataRenderedSearch,\n redirectLocation,\n redirectType,\n revalidationKind,\n isPrerender,\n couldBeIntercepted,\n }\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\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 // We always send the last next-url, not the current when\n // performing a dynamic request. This is because we update\n // the next-url after a navigation, but we want the same\n // interception route to be matched that used the last\n // next-url.\n (state.previousNextUrl || state.nextUrl) &&\n hasInterceptionRouteInCurrentTree(state.tree)\n ? state.previousNextUrl || state.nextUrl\n : null\n\n return fetchServerAction(state, nextUrl, action).then(\n async ({\n revalidationKind,\n actionResult,\n actionFlightData: flightData,\n actionFlightDataRenderedSearch: flightDataRenderedSearch,\n redirectLocation,\n redirectType,\n isPrerender,\n couldBeIntercepted,\n }) => {\n if (revalidationKind !== ActionDidNotRevalidate) {\n // There was either a revalidation or a refresh, or maybe both.\n\n // Evict the BFCache, which may contain dynamic data.\n invalidateBfCache()\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 action.didRevalidate = true\n\n // If there was a revalidation, evict the prefetch cache.\n // TODO: Evict only segments with matching tags and/or paths.\n // TODO: We should only invalidate the route cache if cookies were\n // mutated, since route trees may vary based on cookies. For now we\n // invalidate both caches until we have a way to detect cookie\n // mutations on the client.\n if (revalidationKind === ActionDidRevalidateStaticAndDynamic) {\n invalidateEntirePrefetchCache(nextUrl, state.tree)\n }\n\n // Start a cooldown before re-prefetching to allow CDN cache\n // propagation.\n startRevalidationCooldown()\n }\n\n const navigateType = redirectType || 'push'\n\n if (redirectLocation !== undefined) {\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\n if (isExternalURL(redirectLocation)) {\n // External redirect. Triggers an MPA navigation.\n const redirectHref = redirectLocation.href\n const redirectError = createRedirectErrorForAction(\n redirectHref,\n navigateType\n )\n reject(redirectError)\n return completeHardNavigation(state, redirectLocation, navigateType)\n } else {\n // Internal redirect. Triggers an SPA navigation.\n const redirectWithBasepath = createHrefFromUrl(\n redirectLocation,\n false\n )\n const redirectHref = hasBasePath(redirectWithBasepath)\n ? removeBasePath(redirectWithBasepath)\n : redirectWithBasepath\n const redirectError = createRedirectErrorForAction(\n redirectHref,\n navigateType\n )\n reject(redirectError)\n }\n } else {\n // If there's no redirect, resolve the action with the result.\n resolve(actionResult)\n }\n\n // Check if we can bail out without updating any state.\n if (\n // Did the action trigger a redirect?\n redirectLocation === undefined &&\n // Did the action revalidate any data?\n revalidationKind === ActionDidNotRevalidate &&\n // Did the server render new data?\n flightData === undefined\n ) {\n // The action did not trigger any revalidations or redirects. No\n // navigation is required.\n return state\n }\n\n if (flightData === undefined && redirectLocation !== undefined) {\n // The server redirected, but did not send any Flight data. This implies\n // an external redirect.\n // TODO: We should refactor the action response type to be more explicit\n // about the various response types.\n return completeHardNavigation(state, redirectLocation, navigateType)\n }\n\n if (typeof flightData === 'string') {\n // If the flight data is just a string, something earlier in the\n // response handling triggered an external redirect.\n return completeHardNavigation(\n state,\n new URL(flightData, location.origin),\n navigateType\n )\n }\n\n // The action triggered a navigation — either a redirect, a revalidation,\n // or both.\n\n // If there was no redirect, then the target URL is the same as the\n // current URL.\n const currentUrl = new URL(state.canonicalUrl, location.origin)\n const currentRenderedSearch = state.renderedSearch\n const redirectUrl =\n redirectLocation !== undefined ? redirectLocation : currentUrl\n const currentFlightRouterState = state.tree\n const scrollBehavior = ScrollBehavior.Default\n\n // If the action triggered a revalidation of the cache, we should also\n // refresh all the dynamic data.\n const freshnessPolicy =\n revalidationKind === ActionDidNotRevalidate\n ? FreshnessPolicy.Default\n : FreshnessPolicy.RefreshAll\n\n // The server may have sent back new data. If so, we will perform a\n // \"seeded\" navigation that uses the data from the response.\n // TODO: Currently the server always renders from the root in\n // response to a Server Action. In the case of a normal redirect\n // with no revalidation, it should skip over the shared layouts.\n if (flightData !== undefined && flightDataRenderedSearch !== undefined) {\n // The server sent back new route data as part of the response. We\n // will use this to render the new page. If this happens to be only a\n // subset of the data needed to render the new page, we'll initiate a\n // new fetch, like we would for a normal navigation.\n const redirectCanonicalUrl = createHrefFromUrl(redirectUrl)\n const now = Date.now()\n // TODO: Store the dynamic stale time on the top-level state so it's\n // known during restores and refreshes.\n const redirectSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n flightData,\n flightDataRenderedSearch,\n UnknownDynamicStaleTime\n )\n\n // Learn the route pattern so we can predict it for future navigations.\n const metadataVaryPath = redirectSeed.metadataVaryPath\n if (metadataVaryPath !== null) {\n discoverKnownRoute(\n now,\n redirectUrl.pathname,\n redirectUrl.search as NormalizedSearch,\n nextUrl,\n null, // No pending entry\n redirectSeed.routeTree,\n metadataVaryPath,\n couldBeIntercepted,\n redirectCanonicalUrl,\n isPrerender,\n false // hasDynamicRewrite\n )\n }\n const navigationLock = getCurrentNavigationLock()\n\n return navigateToKnownRoute(\n now,\n state,\n redirectUrl,\n redirectCanonicalUrl,\n redirectSeed,\n currentUrl,\n currentRenderedSearch,\n state.cache,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n // A server-action redirect navigation is bound to the shared map.\n segmentCacheMap,\n null,\n // Server action redirects don't use route prediction - we already\n // have the route tree from the server response. If a mismatch occurs\n // during dynamic data fetch, the retry handler will traverse the\n // known route tree to mark the entry as having a dynamic rewrite.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n }\n\n // The server did not send back new data. We'll perform a regular, non-\n // seeded navigation — effectively the same as <Link> or router.push().\n return navigate(\n state,\n redirectUrl,\n currentUrl,\n currentRenderedSearch,\n state.cache,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType\n )\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\nfunction createRedirectErrorForAction(\n redirectHref: string,\n resolvedRedirectType: RedirectType\n) {\n const redirectError = getRedirectError(redirectHref, resolvedRedirectType)\n // We mark the error as handled because we don't want the redirect to be tried later by\n // the RedirectBoundary, in case the user goes back and `Activity` triggers the redirect\n // again, as it's run within an effect.\n // We don't actually need the RedirectBoundary to do a router.push because we already\n // have all the necessary RSC data to render the new page within a single roundtrip.\n ;(redirectError as any).handled = true\n return redirectError\n}\n"],"names":["callServer","findSourceMapURL","ACTION_HEADER","NEXT_ACTION_NOT_FOUND_HEADER","NEXT_IS_PRERENDER_HEADER","NEXT_HTML_REQUEST_ID_HEADER","NEXT_ROUTER_STATE_TREE_HEADER","NEXT_URL","RSC_CONTENT_TYPE_HEADER","NEXT_REQUEST_ID_HEADER","UnrecognizedActionError","fetch","createFromFetch","createFromFetchBrowser","createTemporaryReferenceSet","encodeReply","ScrollBehavior","assignLocation","createHrefFromUrl","hasInterceptionRouteInCurrentTree","prepareFlightRouterStateForRequest","getRedirectError","removeBasePath","hasBasePath","extractInfoFromServerReferenceId","omitUnusedArgs","invalidateEntirePrefetchCache","segmentCacheMap","startRevalidationCooldown","getDeploymentId","getNavigationBuildId","NEXT_NAV_DEPLOYMENT_ID_HEADER","completeHardNavigation","navigateToKnownRoute","navigate","convertServerPatchToFullTree","discoverKnownRoute","ActionDidNotRevalidate","ActionDidRevalidateDynamicOnly","ActionDidRevalidateStaticAndDynamic","isExternalURL","FreshnessPolicy","getCurrentNavigationLock","processFetch","invalidateBfCache","UnknownDynamicStaleTime","createDebugChannel","process","env","__NEXT_DEV_SERVER","__NEXT_REACT_DEBUG_CHANNEL","require","fetchServerAction","state","nextUrl","action","actionId","actionArgs","temporaryReferences","info","usedArgs","body","headers","Accept","tree","deploymentId","self","__next_r","crypto","getRandomValues","Uint32Array","toString","res","canonicalUrl","method","__NEXT_USE_OFFLINE","notifyOnline","err","checkOfflineError","getOffline","waitForConnection","offline","unrecognizedActionHeader","get","redirectHeader","location","_redirectType","split","redirectType","undefined","isPrerender","revalidationKind","revalidationHeader","parsedKind","JSON","parse","redirectLocation","URL","window","href","contentType","isRscResponse","startsWith","message","status","text","Error","actionResult","actionFlightData","actionFlightDataRenderedSearch","couldBeIntercepted","responsePromise","then","response","r","Promise","resolve","debugChannel","a","i","responseBuildId","b","t","q","n","serverActionReducer","reject","previousNextUrl","flightData","flightDataRenderedSearch","didRevalidate","navigateType","redirectHref","redirectError","createRedirectErrorForAction","redirectWithBasepath","origin","currentUrl","currentRenderedSearch","renderedSearch","redirectUrl","currentFlightRouterState","scrollBehavior","Default","freshnessPolicy","RefreshAll","redirectCanonicalUrl","now","Date","redirectSeed","metadataVaryPath","pathname","search","routeTree","navigationLock","cache","e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kEAAkE;YAClE8D;QAEJ;QAEA,uEAAuE;QACvE,uEAAuE;QACvE,OAAOvD,SACLmB,OACAuF,aACAH,YACAC,uBACArF,MAAMsG,KAAK,EACXd,0BACAvF,SACA0F,iBACAF,gBACAX;IAEJ,GACA,CAACyB;QACC,mHAAmH;QACnH9B,OAAO8B;QAEP,OAAOvG;IACT;AAEJ;AAEA,SAASiF,6BACPF,YAAoB,EACpByB,oBAAkC;IAElC,MAAMxB,gBAAgBhH,iBAAiB+G,cAAcyB;IAMnDxB,cAAsByB,OAAO,GAAG;IAClC,OAAOzB;AACT","ignoreList":[0]} |
| import { createHrefFromUrl } from '../create-href-from-url'; | ||
| import { ACTION_REFRESH, ScrollBehavior } from '../router-reducer-types'; | ||
| import { completeHardNavigation, navigateToKnownRoute } from '../../segment-cache/navigation'; | ||
| import { segmentCacheMap } from '../../segment-cache/cache'; | ||
| import { refreshReducer } from './refresh-reducer'; | ||
@@ -42,3 +43,4 @@ import { getCurrentNavigationLock } from '../ppr-navigations'; | ||
| const now = Date.now(); | ||
| return navigateToKnownRoute(now, state, retryUrl, retryCanonicalUrl, retrySeed, currentUrl, currentRenderedSearch, state.cache, state.tree, action.freshnessPolicy, retryNextUrl, scrollBehavior, navigateType, navigationLock, null, // Server patch (retry) navigations don't use route prediction. This is | ||
| return navigateToKnownRoute(now, state, retryUrl, retryCanonicalUrl, retrySeed, currentUrl, currentRenderedSearch, state.cache, state.tree, action.freshnessPolicy, retryNextUrl, scrollBehavior, navigateType, navigationLock, // A server-patch retry navigation is bound to the shared map. | ||
| segmentCacheMap, null, // Server patch (retry) navigations don't use route prediction. This is | ||
| // typically a retry after a previous mismatch, so the route was already | ||
@@ -45,0 +47,0 @@ // marked as having a dynamic rewrite when the mismatch was detected. |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../../src/client/components/router-reducer/reducers/server-patch-reducer.ts"],"sourcesContent":["import { createHrefFromUrl } from '../create-href-from-url'\nimport {\n ACTION_REFRESH,\n type ServerPatchAction,\n type ReducerState,\n type ReadonlyReducerState,\n ScrollBehavior,\n} from '../router-reducer-types'\nimport {\n completeHardNavigation,\n navigateToKnownRoute,\n} from '../../segment-cache/navigation'\nimport { refreshReducer } from './refresh-reducer'\nimport { getCurrentNavigationLock } from '../ppr-navigations'\n\nexport function serverPatchReducer(\n state: ReadonlyReducerState,\n action: ServerPatchAction\n): ReducerState {\n // A \"retry\" is a navigation that happens due to a route mismatch. It's\n // similar to a refresh, because we will omit any existing dynamic data on\n // the page. But we seed the retry navigation with the exact tree that the\n // server just responded with.\n const retryMpa = action.mpa\n const retryUrl = new URL(action.url, location.origin)\n const retrySeed = action.seed\n const navigateType = action.navigateType\n if (retryMpa || retrySeed === null) {\n // If the server did not send back data during the mismatch, fall back to\n // an MPA navigation.\n return completeHardNavigation(state, retryUrl, navigateType)\n }\n const currentUrl = new URL(state.canonicalUrl, location.origin)\n const currentRenderedSearch = state.renderedSearch\n if (action.previousTree !== state.tree) {\n // There was another, more recent navigation since the once that\n // mismatched. We can abort the retry, but we still need to refresh the\n // page to evict any stale dynamic data.\n return refreshReducer(state, { type: ACTION_REFRESH })\n }\n // There have been no new navigations since the mismatched one. Refresh,\n // using the tree we just received from the server.\n //\n // The freshness policy comes from the action: a genuine tree mismatch\n // re-fetches the dynamic data (`RefreshAll`), whereas a redirect that only\n // changed the canonical URL reuses the data already in the tree\n // (`HistoryTraversal`), since the data we received is correct.\n const retryCanonicalUrl = createHrefFromUrl(retryUrl)\n const retryNextUrl = action.nextUrl\n const scrollBehavior = ScrollBehavior.Default\n const navigationLock = getCurrentNavigationLock()\n const now = Date.now()\n return navigateToKnownRoute(\n now,\n state,\n retryUrl,\n retryCanonicalUrl,\n retrySeed,\n currentUrl,\n currentRenderedSearch,\n state.cache,\n state.tree,\n action.freshnessPolicy,\n retryNextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n null,\n // Server patch (retry) navigations don't use route prediction. This is\n // typically a retry after a previous mismatch, so the route was already\n // marked as having a dynamic rewrite when the mismatch was detected.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n"],"names":["createHrefFromUrl","ACTION_REFRESH","ScrollBehavior","completeHardNavigation","navigateToKnownRoute","refreshReducer","getCurrentNavigationLock","serverPatchReducer","state","action","retryMpa","mpa","retryUrl","URL","url","location","origin","retrySeed","seed","navigateType","currentUrl","canonicalUrl","currentRenderedSearch","renderedSearch","previousTree","tree","type","retryCanonicalUrl","retryNextUrl","nextUrl","scrollBehavior","Default","navigationLock","now","Date","cache","freshnessPolicy","undefined"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,0BAAyB;AAC3D,SACEC,cAAc,EAIdC,cAAc,QACT,0BAAyB;AAChC,SACEC,sBAAsB,EACtBC,oBAAoB,QACf,iCAAgC;AACvC,SAASC,cAAc,QAAQ,oBAAmB;AAClD,SAASC,wBAAwB,QAAQ,qBAAoB;AAE7D,OAAO,SAASC,mBACdC,KAA2B,EAC3BC,MAAyB;IAEzB,uEAAuE;IACvE,0EAA0E;IAC1E,0EAA0E;IAC1E,8BAA8B;IAC9B,MAAMC,WAAWD,OAAOE,GAAG;IAC3B,MAAMC,WAAW,IAAIC,IAAIJ,OAAOK,GAAG,EAAEC,SAASC,MAAM;IACpD,MAAMC,YAAYR,OAAOS,IAAI;IAC7B,MAAMC,eAAeV,OAAOU,YAAY;IACxC,IAAIT,YAAYO,cAAc,MAAM;QAClC,yEAAyE;QACzE,qBAAqB;QACrB,OAAOd,uBAAuBK,OAAOI,UAAUO;IACjD;IACA,MAAMC,aAAa,IAAIP,IAAIL,MAAMa,YAAY,EAAEN,SAASC,MAAM;IAC9D,MAAMM,wBAAwBd,MAAMe,cAAc;IAClD,IAAId,OAAOe,YAAY,KAAKhB,MAAMiB,IAAI,EAAE;QACtC,gEAAgE;QAChE,uEAAuE;QACvE,wCAAwC;QACxC,OAAOpB,eAAeG,OAAO;YAAEkB,MAAMzB;QAAe;IACtD;IACA,wEAAwE;IACxE,mDAAmD;IACnD,EAAE;IACF,sEAAsE;IACtE,2EAA2E;IAC3E,gEAAgE;IAChE,+DAA+D;IAC/D,MAAM0B,oBAAoB3B,kBAAkBY;IAC5C,MAAMgB,eAAenB,OAAOoB,OAAO;IACnC,MAAMC,iBAAiB5B,eAAe6B,OAAO;IAC7C,MAAMC,iBAAiB1B;IACvB,MAAM2B,MAAMC,KAAKD,GAAG;IACpB,OAAO7B,qBACL6B,KACAzB,OACAI,UACAe,mBACAV,WACAG,YACAE,uBACAd,MAAM2B,KAAK,EACX3B,MAAMiB,IAAI,EACVhB,OAAO2B,eAAe,EACtBR,cACAE,gBACAX,cACAa,gBACA,MACA,uEAAuE;IACvE,wEAAwE;IACxE,qEAAqE;IACrE,MACA,kEAAkE;IAClEK;AAEJ","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../../src/client/components/router-reducer/reducers/server-patch-reducer.ts"],"sourcesContent":["import { createHrefFromUrl } from '../create-href-from-url'\nimport {\n ACTION_REFRESH,\n type ServerPatchAction,\n type ReducerState,\n type ReadonlyReducerState,\n ScrollBehavior,\n} from '../router-reducer-types'\nimport {\n completeHardNavigation,\n navigateToKnownRoute,\n} from '../../segment-cache/navigation'\nimport { segmentCacheMap } from '../../segment-cache/cache'\nimport { refreshReducer } from './refresh-reducer'\nimport { getCurrentNavigationLock } from '../ppr-navigations'\n\nexport function serverPatchReducer(\n state: ReadonlyReducerState,\n action: ServerPatchAction\n): ReducerState {\n // A \"retry\" is a navigation that happens due to a route mismatch. It's\n // similar to a refresh, because we will omit any existing dynamic data on\n // the page. But we seed the retry navigation with the exact tree that the\n // server just responded with.\n const retryMpa = action.mpa\n const retryUrl = new URL(action.url, location.origin)\n const retrySeed = action.seed\n const navigateType = action.navigateType\n if (retryMpa || retrySeed === null) {\n // If the server did not send back data during the mismatch, fall back to\n // an MPA navigation.\n return completeHardNavigation(state, retryUrl, navigateType)\n }\n const currentUrl = new URL(state.canonicalUrl, location.origin)\n const currentRenderedSearch = state.renderedSearch\n if (action.previousTree !== state.tree) {\n // There was another, more recent navigation since the once that\n // mismatched. We can abort the retry, but we still need to refresh the\n // page to evict any stale dynamic data.\n return refreshReducer(state, { type: ACTION_REFRESH })\n }\n // There have been no new navigations since the mismatched one. Refresh,\n // using the tree we just received from the server.\n //\n // The freshness policy comes from the action: a genuine tree mismatch\n // re-fetches the dynamic data (`RefreshAll`), whereas a redirect that only\n // changed the canonical URL reuses the data already in the tree\n // (`HistoryTraversal`), since the data we received is correct.\n const retryCanonicalUrl = createHrefFromUrl(retryUrl)\n const retryNextUrl = action.nextUrl\n const scrollBehavior = ScrollBehavior.Default\n const navigationLock = getCurrentNavigationLock()\n const now = Date.now()\n return navigateToKnownRoute(\n now,\n state,\n retryUrl,\n retryCanonicalUrl,\n retrySeed,\n currentUrl,\n currentRenderedSearch,\n state.cache,\n state.tree,\n action.freshnessPolicy,\n retryNextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n // A server-patch retry navigation is bound to the shared map.\n segmentCacheMap,\n null,\n // Server patch (retry) navigations don't use route prediction. This is\n // typically a retry after a previous mismatch, so the route was already\n // marked as having a dynamic rewrite when the mismatch was detected.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n"],"names":["createHrefFromUrl","ACTION_REFRESH","ScrollBehavior","completeHardNavigation","navigateToKnownRoute","segmentCacheMap","refreshReducer","getCurrentNavigationLock","serverPatchReducer","state","action","retryMpa","mpa","retryUrl","URL","url","location","origin","retrySeed","seed","navigateType","currentUrl","canonicalUrl","currentRenderedSearch","renderedSearch","previousTree","tree","type","retryCanonicalUrl","retryNextUrl","nextUrl","scrollBehavior","Default","navigationLock","now","Date","cache","freshnessPolicy","undefined"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,0BAAyB;AAC3D,SACEC,cAAc,EAIdC,cAAc,QACT,0BAAyB;AAChC,SACEC,sBAAsB,EACtBC,oBAAoB,QACf,iCAAgC;AACvC,SAASC,eAAe,QAAQ,4BAA2B;AAC3D,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EJ","ignoreList":[0]} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/client/components/router-reducer/router-reducer-types.ts"],"sourcesContent":["import type { CacheNode, ScrollRef } from '../../../shared/lib/app-router-types'\nimport type { FlightRouterState } from '../../../shared/lib/app-router-types'\nimport type { NavigationSeed } from '../segment-cache/decode-server-response'\nimport type { FetchServerResponseResult } from './fetch-server-response'\nimport type { FreshnessPolicy } from './ppr-navigations'\n\nexport const ACTION_REFRESH = 'refresh'\nexport const ACTION_NAVIGATE = 'navigate'\nexport const ACTION_RESTORE = 'restore'\nexport const ACTION_SERVER_PATCH = 'server-patch'\nexport const ACTION_HMR_REFRESH = 'hmr-refresh'\nexport const ACTION_SERVER_ACTION = 'server-action'\n\nexport type RouterChangeByServerResponse = ({\n navigatedAt,\n previousTree,\n serverResponse,\n}: {\n navigatedAt: number\n previousTree: FlightRouterState\n serverResponse: FetchServerResponseResult\n}) => void\n\n/**\n * Refresh triggers a refresh of the full page data.\n * - fetches the Flight data and fills rsc at the root of the cache.\n * - The router state is updated at the root.\n */\nexport interface RefreshAction {\n type: typeof ACTION_REFRESH\n /**\n * Bypass invalidating the segment cache. Used by the Instant Navigation\n * Testing API to preserve prefetched data when refreshing after an MPA\n * navigation. Not exposed in production builds by default.\n */\n bypassCacheInvalidation?: boolean\n}\n\nexport interface HmrRefreshAction {\n type: typeof ACTION_HMR_REFRESH\n signal?: AbortSignal\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 scrollBehavior: ScrollBehavior\n}\n\n/**\n * Restore applies the provided router state.\n * - Used for `popstate` (back/forward navigation) where a known router state has to be applied.\n * - Also used when syncing the router state with `pushState`/`replaceState` calls.\n * - Router state is applied as-is from the history state, if available.\n * - If the history state does not contain the router state, the existing router state is used.\n * - If any cache node is missing it will be fetched in layout-router during rendering and the server-patch case.\n * - If existing cache nodes match these are used.\n */\nexport interface RestoreAction {\n type: typeof ACTION_RESTORE\n url: URL\n historyState: AppHistoryState | undefined\n}\n\nexport type AppHistoryState = {\n tree: FlightRouterState\n renderedSearch: string\n}\n\n/**\n * Server-patch applies the provided Flight data to the cache and router tree.\n */\nexport interface ServerPatchAction {\n type: typeof ACTION_SERVER_PATCH\n previousTree: FlightRouterState\n url: URL\n nextUrl: string | null\n seed: NavigationSeed | null\n mpa: boolean\n navigateType: 'push' | 'replace'\n /**\n * Freshness policy for the retry navigation. `RefreshAll` re-fetches the\n * tree's dynamic data (genuine tree mismatch). `HistoryTraversal` reuses the\n * data already in the tree (when only the URL needs correcting after a\n * redirect).\n */\n freshnessPolicy: FreshnessPolicy.RefreshAll | FreshnessPolicy.HistoryTraversal\n}\n\n/**\n * PrefetchKind defines the type of prefetching that should be done.\n * - `auto` - if the page is dynamic, prefetch the page data partially, if static prefetch the page data fully.\n * - `full` - prefetch the page data fully.\n */\n\nexport enum PrefetchKind {\n AUTO = 'auto',\n FULL = 'full',\n}\n\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\n/**\n * Controls the scroll behavior for a navigation.\n */\nexport const enum ScrollBehavior {\n /** Use per-node ScrollRef to decide whether to scroll. */\n Default = 0,\n /** Suppress scroll entirely (e.g. scroll={false} on Link or router.push). */\n NoScroll = 1,\n}\n\nexport type FocusAndScrollRef = {\n /**\n * The scroll ref from the most recent navigation. Set to whatever was\n * accumulated during tree construction (or null if nothing was\n * accumulated). On the next navigation, if new scroll targets are\n * created, the previous scrollRef is invalidated by setting\n * `current = false`.\n */\n scrollRef: ScrollRef | null\n /**\n * When true, the scroll handler uses `focusAndScrollRef.scrollRef`\n * for every segment regardless of per-node state. Used for hash-only\n * navigations where every segment should be treated as a scroll\n * target. When false, the handler checks `cacheNode.scrollRef`\n * instead (per-node), so only segments that actually navigated scroll.\n */\n forceScroll: boolean\n /**\n * The hash fragment that should be scrolled to.\n */\n hashFragment: string | null\n /**\n * If only the URLs hash fragment changed\n */\n onlyHashChange: boolean\n}\n\n/**\n * Handles keeping the state of app-router.\n */\nexport type AppRouterState = {\n /**\n * The router state, this is written into the history state in app-router using replaceState/pushState.\n * - Has to be serializable as it is written into the history state.\n * - Holds which segments and parallel routes are shown on the screen.\n */\n tree: FlightRouterState\n /**\n * The cache holds React nodes for every segment that is shown on screen as well as previously shown segments.\n * It also holds in-progress data requests.\n */\n cache: CacheNode\n /**\n * Decides if the update should create a new history entry and if the navigation has to trigger a browser navigation.\n */\n pushRef: PushRef\n /**\n * Decides if the update should apply scroll and focus management.\n */\n focusAndScrollRef: FocusAndScrollRef\n /**\n * The canonical url that is pushed/replaced.\n * - This is the url you see in the browser.\n */\n canonicalUrl: string\n\n /**\n * The search query observed by the server during rendering. This may be\n * different from the canonical URL's search query if the server performed\n * a rewrite. Even though a client component won't observe this (unless it\n * were passed from a Server component), the client router needs to know this\n * so it can properly cache segment data; it'ss part of a page segment's\n * cache key.\n */\n renderedSearch: string\n\n /**\n * The underlying \"url\" representing the UI state, which is used for intercepting routes.\n */\n nextUrl: string | null\n\n /**\n * The previous next-url that was used previous to a dynamic navigation.\n */\n previousNextUrl: string | null\n\n debugInfo: Array<unknown> | null\n}\n\nexport type ReadonlyReducerState = Readonly<AppRouterState>\nexport type ReducerState =\n | (Promise<AppRouterState> & { _debugInfo?: Array<unknown> })\n | AppRouterState\nexport type ReducerActions = Readonly<\n | RefreshAction\n | NavigateAction\n | RestoreAction\n | ServerPatchAction\n | HmrRefreshAction\n | ServerActionAction\n>\n"],"names":["ACTION_REFRESH","ACTION_NAVIGATE","ACTION_RESTORE","ACTION_SERVER_PATCH","ACTION_HMR_REFRESH","ACTION_SERVER_ACTION","PrefetchKind","ScrollBehavior"],"mappings":"AAMA,OAAO,MAAMA,iBAAiB,UAAS;AACvC,OAAO,MAAMC,kBAAkB,WAAU;AACzC,OAAO,MAAMC,iBAAiB,UAAS;AACvC,OAAO,MAAMC,sBAAsB,eAAc;AACjD,OAAO,MAAMC,qBAAqB,cAAa;AAC/C,OAAO,MAAMC,uBAAuB,gBAAe;AA+HnD;;;;CAIC,GAED,OAAO,IAAA,AAAKC,sCAAAA;;;WAAAA;MAGX;AAiBD;;CAEC,GACD,OAAO,IAAA,AAAWC,wCAAAA;IAChB,wDAAwD;IAExD,2EAA2E;WAH3DA;MAKjB","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/client/components/router-reducer/router-reducer-types.ts"],"sourcesContent":["import type { CacheNode, ScrollRef } from '../../../shared/lib/app-router-types'\nimport type { FlightRouterState } from '../../../shared/lib/app-router-types'\nimport type { NavigationSeed } from '../segment-cache/decode-server-response'\nimport type { FetchServerResponseResult } from './fetch-server-response'\nimport type { FreshnessPolicy } from './ppr-navigations'\n\nexport const ACTION_REFRESH = 'refresh'\nexport const ACTION_NAVIGATE = 'navigate'\nexport const ACTION_RESTORE = 'restore'\nexport const ACTION_SERVER_PATCH = 'server-patch'\nexport const ACTION_HMR_REFRESH = 'hmr-refresh'\nexport const ACTION_SERVER_ACTION = 'server-action'\n\nexport type RouterChangeByServerResponse = ({\n navigatedAt,\n previousTree,\n serverResponse,\n}: {\n navigatedAt: number\n previousTree: FlightRouterState\n serverResponse: FetchServerResponseResult\n}) => void\n\n/**\n * Refresh triggers a refresh of the full page data.\n * - fetches the Flight data and fills rsc at the root of the cache.\n * - The router state is updated at the root.\n */\nexport interface RefreshAction {\n type: typeof ACTION_REFRESH\n /**\n * Bypass invalidating the segment cache. Used by the Instant Navigation\n * Testing API to preserve prefetched data when refreshing after an MPA\n * navigation. Not exposed in production builds by default.\n */\n bypassCacheInvalidation?: boolean\n}\n\nexport interface HmrRefreshAction {\n type: typeof ACTION_HMR_REFRESH\n signal?: AbortSignal\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 scrollBehavior: ScrollBehavior\n}\n\n/**\n * Restore applies the provided router state.\n * - Used for `popstate` (back/forward navigation) where a known router state has to be applied.\n * - Also used when syncing the router state with `pushState`/`replaceState` calls.\n * - Router state is applied as-is from the history state, if available.\n * - If the history state does not contain the router state, the existing router state is used.\n * - If any cache node is missing it will be fetched in layout-router during rendering and the server-patch case.\n * - If existing cache nodes match these are used.\n */\nexport interface RestoreAction {\n type: typeof ACTION_RESTORE\n url: URL\n historyState: AppHistoryState | undefined\n}\n\nexport type AppHistoryState = {\n tree: FlightRouterState\n renderedSearch: string\n}\n\n/**\n * Server-patch applies the provided Flight data to the cache and router tree.\n */\nexport interface ServerPatchAction {\n type: typeof ACTION_SERVER_PATCH\n previousTree: FlightRouterState\n url: URL\n nextUrl: string | null\n seed: NavigationSeed | null\n mpa: boolean\n navigateType: 'push' | 'replace'\n /**\n * Freshness policy for the retry navigation. `RefreshAll` re-fetches the\n * tree's dynamic data (genuine tree mismatch). `HistoryTraversal` reuses the\n * data already in the tree (when only the URL needs correcting after a\n * redirect).\n */\n freshnessPolicy: FreshnessPolicy.RefreshAll | FreshnessPolicy.HistoryTraversal\n}\n\n/**\n * PrefetchKind defines the type of prefetching that should be done.\n * - `auto` - if the page is dynamic, prefetch the page data partially, if static prefetch the page data fully.\n * - `full` - prefetch the page data fully.\n */\n\nexport enum PrefetchKind {\n AUTO = 'auto',\n FULL = 'full',\n}\n\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\n/**\n * Controls the scroll behavior for a navigation.\n */\nexport const enum ScrollBehavior {\n /** Use per-node ScrollRef to decide whether to scroll. */\n Default = 0,\n /** Suppress scroll entirely (e.g. scroll={false} on Link or router.push). */\n NoScroll = 1,\n}\n\nexport type ScrollHandlerRef = {\n /**\n * The scroll ref from the most recent navigation. Set to whatever was\n * accumulated during tree construction (or null if nothing was\n * accumulated). On the next navigation, if new scroll targets are\n * created, the previous scrollRef is invalidated by setting\n * `current = false`.\n */\n scrollRef: ScrollRef | null\n /**\n * When true, the scroll handler uses the navigation-level `scrollRef`\n * for every segment regardless of per-node state. Used for hash-only\n * navigations where every segment should be treated as a scroll\n * target. When false, the handler checks `cacheNode.scrollRef`\n * instead (per-node), so only segments that actually navigated scroll.\n */\n forceScroll: boolean\n /**\n * The hash fragment that should be scrolled to.\n */\n hashFragment: string | null\n /**\n * If only the URLs hash fragment changed\n */\n onlyHashChange: boolean\n}\n\n/**\n * Handles keeping the state of app-router.\n */\nexport type AppRouterState = {\n /**\n * The router state, this is written into the history state in app-router using replaceState/pushState.\n * - Has to be serializable as it is written into the history state.\n * - Holds which segments and parallel routes are shown on the screen.\n */\n tree: FlightRouterState\n /**\n * The cache holds React nodes for every segment that is shown on screen as well as previously shown segments.\n * It also holds in-progress data requests.\n */\n cache: CacheNode\n /**\n * Decides if the update should create a new history entry and if the navigation has to trigger a browser navigation.\n */\n pushRef: PushRef\n /**\n * Decides if the update should apply scroll management.\n */\n scrollRef: ScrollHandlerRef\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 /**\n * The search query observed by the server during rendering. This may be\n * different from the canonical URL's search query if the server performed\n * a rewrite. Even though a client component won't observe this (unless it\n * were passed from a Server component), the client router needs to know this\n * so it can properly cache segment data; it'ss part of a page segment's\n * cache key.\n */\n renderedSearch: string\n\n /**\n * The underlying \"url\" representing the UI state, which is used for intercepting routes.\n */\n nextUrl: string | null\n\n /**\n * The previous next-url that was used previous to a dynamic navigation.\n */\n previousNextUrl: string | null\n\n debugInfo: Array<unknown> | null\n}\n\nexport type ReadonlyReducerState = Readonly<AppRouterState>\nexport type ReducerState =\n | (Promise<AppRouterState> & { _debugInfo?: Array<unknown> })\n | AppRouterState\nexport type ReducerActions = Readonly<\n | RefreshAction\n | NavigateAction\n | RestoreAction\n | ServerPatchAction\n | HmrRefreshAction\n | ServerActionAction\n>\n"],"names":["ACTION_REFRESH","ACTION_NAVIGATE","ACTION_RESTORE","ACTION_SERVER_PATCH","ACTION_HMR_REFRESH","ACTION_SERVER_ACTION","PrefetchKind","ScrollBehavior"],"mappings":"AAMA,OAAO,MAAMA,iBAAiB,UAAS;AACvC,OAAO,MAAMC,kBAAkB,WAAU;AACzC,OAAO,MAAMC,iBAAiB,UAAS;AACvC,OAAO,MAAMC,sBAAsB,eAAc;AACjD,OAAO,MAAMC,qBAAqB,cAAa;AAC/C,OAAO,MAAMC,uBAAuB,gBAAe;AA+HnD;;;;CAIC,GAED,OAAO,IAAA,AAAKC,sCAAAA;;;WAAAA;MAGX;AAiBD;;CAEC,GACD,OAAO,IAAA,AAAWC,wCAAAA;IAChB,wDAAwD;IAExD,2EAA2E;WAH3DA;MAKjB","ignoreList":[0]} |
@@ -19,5 +19,6 @@ /** | ||
| } | ||
| export function recordNavigationLockOwnedEntry(_entry) {} | ||
| export function trackNavigationLockPrefetchEntry(_prefetch, _entry) {} | ||
| export function finishNavigationLockPrefetchSpawning(_prefetch) {} | ||
| export function getNavigationLockSegmentCacheMap() { | ||
| return null; | ||
| } | ||
| export function resolveNavigationLockPrefetch(_prefetch) {} | ||
| export function startListeningForInstantNavigationCookie() {} | ||
@@ -28,5 +29,2 @@ export function updateCapturedSPAToTree(_fromTree, _toTree) {} | ||
| } | ||
| export function getCurrentNavigationLock() { | ||
| return null; | ||
| } | ||
| export function beginLockedNavigation() { | ||
@@ -33,0 +31,0 @@ return null; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/client/components/segment-cache/navigation-testing-lock.disabled.ts"],"sourcesContent":["/**\n * Inert stand-in for `./navigation-testing-lock`.\n *\n * When the Instant Navigation Testing API is disabled (a production build\n * without `experimental.exposeTestingApiInProductionBuild`), the browser\n * bundle resolves `./navigation-testing-lock` to this module instead of the\n * real implementation, so none of the lock machinery ships. The alias is set\n * up in `create-compiler-aliases.ts` (webpack) and\n * `crates/next-core/src/next_import_map.rs` (Turbopack).\n *\n * Every export mirrors the real module's signature and returns the value the\n * real implementation produces when no lock is held.\n */\n\nimport type { FlightRouterState } from '../../../shared/lib/app-router-types'\nimport type { PendingSegmentCacheEntry, SegmentCacheEntry } from './cache'\nimport type { FetchStrategy } from './types'\nimport type {\n NavigationLockPrefetch,\n NavigationLockState,\n} from './navigation-testing-lock'\n\nexport type {\n NavigationLockPrefetch,\n NavigationLockState,\n} from './navigation-testing-lock'\n\nexport function getPreLockFetch(): typeof fetch | null {\n return null\n}\n\nexport function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {\n return null\n}\n\nexport function recordNavigationLockOwnedEntry(\n _entry: SegmentCacheEntry\n): void {}\n\nexport function trackNavigationLockPrefetchEntry(\n _prefetch: NavigationLockPrefetch,\n _entry: PendingSegmentCacheEntry\n): void {}\n\nexport function finishNavigationLockPrefetchSpawning(\n _prefetch: NavigationLockPrefetch\n): void {}\n\nexport function startListeningForInstantNavigationCookie(): void {}\n\nexport function updateCapturedSPAToTree(\n _fromTree: FlightRouterState,\n _toTree: FlightRouterState\n): void {}\n\nexport function isNavigationLocked(): boolean {\n return false\n}\n\nexport function getCurrentNavigationLock(): NavigationLockState | null {\n return null\n}\n\nexport function beginLockedNavigation(): Promise<void> | null {\n return null\n}\n\nexport function getCurrentNavigationGate(): Promise<void> | null {\n return null\n}\n\nexport function resetNavigationLockToPending(): void {}\n\nexport function shouldRestrictNavigationToShell(\n _rootPrefetchHints: number,\n _linkFetchStrategy: FetchStrategy\n): boolean {\n return false\n}\n"],"names":["getPreLockFetch","beginNavigationLockPrefetch","recordNavigationLockOwnedEntry","_entry","trackNavigationLockPrefetchEntry","_prefetch","finishNavigationLockPrefetchSpawning","startListeningForInstantNavigationCookie","updateCapturedSPAToTree","_fromTree","_toTree","isNavigationLocked","getCurrentNavigationLock","beginLockedNavigation","getCurrentNavigationGate","resetNavigationLockToPending","shouldRestrictNavigationToShell","_rootPrefetchHints","_linkFetchStrategy"],"mappings":"AAAA;;;;;;;;;;;;CAYC,GAeD,OAAO,SAASA;IACd,OAAO;AACT;AAEA,OAAO,SAASC;IACd,OAAO;AACT;AAEA,OAAO,SAASC,+BACdC,MAAyB,GAClB;AAET,OAAO,SAASC,iCACdC,SAAiC,EACjCF,MAAgC,GACzB;AAET,OAAO,SAASG,qCACdD,SAAiC,GAC1B;AAET,OAAO,SAASE,4CAAkD;AAElE,OAAO,SAASC,wBACdC,SAA4B,EAC5BC,OAA0B,GACnB;AAET,OAAO,SAASC;IACd,OAAO;AACT;AAEA,OAAO,SAASC;IACd,OAAO;AACT;AAEA,OAAO,SAASC;IACd,OAAO;AACT;AAEA,OAAO,SAASC;IACd,OAAO;AACT;AAEA,OAAO,SAASC,gCAAsC;AAEtD,OAAO,SAASC,gCACdC,kBAA0B,EAC1BC,kBAAiC;IAEjC,OAAO;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/client/components/segment-cache/navigation-testing-lock.disabled.ts"],"sourcesContent":["/**\n * Inert stand-in for `./navigation-testing-lock`.\n *\n * When the Instant Navigation Testing API is disabled (a production build\n * without `experimental.exposeTestingApiInProductionBuild`), the browser\n * bundle resolves `./navigation-testing-lock` to this module instead of the\n * real implementation, so none of the lock machinery ships. The alias is set\n * up in `create-compiler-aliases.ts` (webpack) and\n * `crates/next-core/src/next_import_map.rs` (Turbopack).\n *\n * Every export mirrors the real module's signature and returns the value the\n * real implementation produces when no lock is held.\n */\n\nimport type { FlightRouterState } from '../../../shared/lib/app-router-types'\nimport type { SegmentCacheEntry } from './cache'\nimport type { CacheMap } from './cache-map'\nimport type { FetchStrategy } from './types'\nimport type { NavigationLockPrefetch } from './navigation-testing-lock'\n\nexport type {\n NavigationLockPrefetch,\n NavigationLockState,\n} from './navigation-testing-lock'\n\nexport function getPreLockFetch(): typeof fetch | null {\n return null\n}\n\nexport function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {\n return null\n}\n\nexport function getNavigationLockSegmentCacheMap(): CacheMap<SegmentCacheEntry> | null {\n return null\n}\n\nexport function resolveNavigationLockPrefetch(\n _prefetch: NavigationLockPrefetch\n): void {}\n\nexport function startListeningForInstantNavigationCookie(): void {}\n\nexport function updateCapturedSPAToTree(\n _fromTree: FlightRouterState,\n _toTree: FlightRouterState\n): void {}\n\nexport function isNavigationLocked(): boolean {\n return false\n}\n\nexport function beginLockedNavigation(): Promise<void> | null {\n return null\n}\n\nexport function getCurrentNavigationGate(): Promise<void> | null {\n return null\n}\n\nexport function resetNavigationLockToPending(): void {}\n\nexport function shouldRestrictNavigationToShell(\n _rootPrefetchHints: number,\n _linkFetchStrategy: FetchStrategy\n): boolean {\n return false\n}\n"],"names":["getPreLockFetch","beginNavigationLockPrefetch","getNavigationLockSegmentCacheMap","resolveNavigationLockPrefetch","_prefetch","startListeningForInstantNavigationCookie","updateCapturedSPAToTree","_fromTree","_toTree","isNavigationLocked","beginLockedNavigation","getCurrentNavigationGate","resetNavigationLockToPending","shouldRestrictNavigationToShell","_rootPrefetchHints","_linkFetchStrategy"],"mappings":"AAAA;;;;;;;;;;;;CAYC,GAaD,OAAO,SAASA;IACd,OAAO;AACT;AAEA,OAAO,SAASC;IACd,OAAO;AACT;AAEA,OAAO,SAASC;IACd,OAAO;AACT;AAEA,OAAO,SAASC,8BACdC,SAAiC,GAC1B;AAET,OAAO,SAASC,4CAAkD;AAElE,OAAO,SAASC,wBACdC,SAA4B,EAC5BC,OAA0B,GACnB;AAET,OAAO,SAASC;IACd,OAAO;AACT;AAEA,OAAO,SAASC;IACd,OAAO;AACT;AAEA,OAAO,SAASC;IACd,OAAO;AACT;AAEA,OAAO,SAASC,gCAAsC;AAEtD,OAAO,SAASC,gCACdC,kBAA0B,EAC1BC,kBAAiC;IAEjC,OAAO;AACT","ignoreList":[0]} |
@@ -23,3 +23,3 @@ /** | ||
| import { subtreeHasSpeculativePrefetch } from './scheduler'; | ||
| import { waitForSegmentCacheEntry } from './cache'; | ||
| import { createCacheMap } from './cache-map'; | ||
| function parseCookieValue(raw) { | ||
@@ -88,8 +88,4 @@ if (raw === '') { | ||
| * prefetch task and awaits `.promise`). Returns null if no lock is held. | ||
| * | ||
| * `pendingCount` starts at 1, representing the scheduler itself while it is | ||
| * still spawning requests; that reference is released by | ||
| * `finishNavigationLockPrefetchSpawning`. Each spawned pending entry adds | ||
| * another (see `trackNavigationLockPrefetchEntry`). `promise` resolves when the | ||
| * count drains to 0 — i.e. spawning finished and every entry fulfilled. | ||
| * Resolved by the scheduler via `resolveNavigationLockPrefetch` when the | ||
| * driving prefetch task completes. | ||
| */ export function beginNavigationLockPrefetch() { | ||
@@ -103,5 +99,3 @@ if (lockState !== null) { | ||
| promise, | ||
| resolve: resolve, | ||
| pendingCount: 1, | ||
| trackedEntries: new Set() | ||
| resolve: resolve | ||
| }; | ||
@@ -114,52 +108,20 @@ lockState.activePrefetches.add(prefetch); | ||
| /** | ||
| * Records a freshly-created segment entry as owned by the current lock scope, so | ||
| * navigation reads will match it — and only entries created within the scope | ||
| * (see `NavigationLockState.ownedEntries`). Called from | ||
| * `createDetachedSegmentCacheEntry`, the single factory every creation path | ||
| * funnels through, so re-keyed entries created during response processing (e.g. | ||
| * a runtime prefetch resolving a concrete param) are owned too. No-op when no | ||
| * lock is held. | ||
| */ export function recordNavigationLockOwnedEntry(entry) { | ||
| if (lockState !== null) { | ||
| lockState.ownedEntries.add(entry); | ||
| } | ||
| * Returns the current lock scope's private segment cache map, or null when no | ||
| * lock is held. See `NavigationLockState.segmentCacheMap`. | ||
| */ export function getNavigationLockSegmentCacheMap() { | ||
| return lockState !== null ? lockState.segmentCacheMap : null; | ||
| } | ||
| /** | ||
| * Called by `upgradeToPendingSegment` whenever the locked-navigation prefetch | ||
| * spawns a pending segment entry. Adds the entry to the prefetch's ref count and | ||
| * decrements when it fulfills (or rejects — `waitForSegmentCacheEntry` resolves | ||
| * to null). Deduped so the same entry never double-counts. | ||
| */ export function trackNavigationLockPrefetchEntry(prefetch, entry) { | ||
| if (prefetch.trackedEntries.has(entry)) { | ||
| return; | ||
| * Called by the scheduler when the locked-navigation prefetch task completes. | ||
| * A task only completes after a full pass observed every segment response it | ||
| * cares about, so the data the navigation will read has settled by this | ||
| * point. Unregisters from the lock (if still held) and resolves. Resolving is | ||
| * idempotent, so it's safe even if the lock already force-resolved this on | ||
| * release. | ||
| */ export function resolveNavigationLockPrefetch(prefetch) { | ||
| if (lockState !== null) { | ||
| lockState.activePrefetches.delete(prefetch); | ||
| } | ||
| prefetch.trackedEntries.add(entry); | ||
| prefetch.pendingCount++; | ||
| const onSettled = ()=>{ | ||
| prefetch.pendingCount--; | ||
| settleNavigationLockPrefetchIfDrained(prefetch); | ||
| }; | ||
| // Decrement whether the entry fulfills or its request rejects, so a failed | ||
| // segment can't leave the navigation waiting forever. | ||
| waitForSegmentCacheEntry(entry).then(onSettled, onSettled); | ||
| prefetch.resolve(); | ||
| } | ||
| /** | ||
| * Called once the scheduler has finished spawning every request for the | ||
| * locked-navigation prefetch, releasing the scheduler's reference from the ref | ||
| * count. The prefetch resolves here if every spawned entry already fulfilled. | ||
| */ export function finishNavigationLockPrefetchSpawning(prefetch) { | ||
| prefetch.pendingCount--; | ||
| settleNavigationLockPrefetchIfDrained(prefetch); | ||
| } | ||
| function settleNavigationLockPrefetchIfDrained(prefetch) { | ||
| if (prefetch.pendingCount === 0) { | ||
| // Unregister from the lock (if still held) and resolve. Resolving is | ||
| // idempotent, so it's safe even if the lock already force-resolved this on | ||
| // release. | ||
| if (lockState !== null) { | ||
| lockState.activePrefetches.delete(prefetch); | ||
| } | ||
| prefetch.resolve(); | ||
| } | ||
| } | ||
| function acquireLock() { | ||
@@ -182,3 +144,3 @@ if (lockState !== null) { | ||
| activePrefetches: new Set(), | ||
| ownedEntries: new Set(), | ||
| segmentCacheMap: createCacheMap(), | ||
| currentNavigation, | ||
@@ -443,5 +405,2 @@ resolveCurrentNavigation: resolveCurrentNavigation | ||
| } | ||
| export function getCurrentNavigationLock() { | ||
| return lockState; | ||
| } | ||
| /** | ||
@@ -448,0 +407,0 @@ * Returns the current locked navigation's withheld-data gate — the same |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/client/components/segment-cache/navigation-testing-lock.ts"],"sourcesContent":["/**\n * Navigation lock for the Instant Navigation Testing API.\n *\n * Manages the in-memory lock (a promise) that gates dynamic data writes\n * during instant navigation captures, and owns all cookie state\n * transitions (pending → captured-MPA, pending → captured-SPA).\n *\n * External actors (Playwright, devtools) set [0] to start a lock scope\n * and delete the cookie to end one. Next.js writes captured values.\n * The CookieStore handler distinguishes them by value: pending = external,\n * captured = self-write (ignored).\n *\n * This module assumes the Instant Navigation Testing API is enabled. When it\n * is disabled, the bundler resolves this module to\n * `./navigation-testing-lock.disabled` instead (see\n * `create-compiler-aliases.ts` for webpack and\n * `crates/next-core/src/next_import_map.rs` for Turbopack), so none of this\n * code ships in the browser bundle.\n */\n\nimport {\n PrefetchHint,\n type FlightRouterState,\n type InstantCookie,\n} from '../../../shared/lib/app-router-types'\nimport { NEXT_INSTANT_TEST_COOKIE } from '../app-router-headers'\nimport { refreshOnInstantNavigationUnlock } from '../use-action-queue'\nimport { subtreeHasSpeculativePrefetch } from './scheduler'\nimport {\n waitForSegmentCacheEntry,\n type PendingSegmentCacheEntry,\n type SegmentCacheEntry,\n} from './cache'\nimport type { FetchStrategy } from './types'\n\ntype InstantNavCookieState = 'empty' | 'pending' | 'mpa' | 'spa'\n\nfunction parseCookieValue(raw: string): InstantNavCookieState {\n if (raw === '') {\n return 'empty'\n }\n try {\n const parsed = JSON.parse(raw)\n if (Array.isArray(parsed)) {\n if (parsed.length >= 3) {\n const rawState = parsed[2]\n return rawState === null ? 'mpa' : 'spa'\n }\n }\n } catch {}\n return 'pending'\n}\n\nfunction writeDocumentCookie(\n value: InstantCookie,\n options: { domain?: string | null; path?: string | null }\n): void {\n if (typeof document === 'undefined') {\n return\n }\n let cookie = `${NEXT_INSTANT_TEST_COOKIE}=${JSON.stringify(value)}; Path=${\n options.path ?? '/'\n }`\n if (options.domain) {\n cookie += `; Domain=${options.domain}`\n }\n document.cookie = cookie\n}\n\nfunction writeCookieValue(value: InstantCookie): void {\n if (typeof cookieStore === 'undefined') {\n return\n }\n // Read the existing cookie to preserve its attributes (domain, path), then\n // write back with the new value. This updates the same cookie entry that the\n // external actor created, regardless of how it was scoped. The read goes\n // through `cookieStore.get` because `document.cookie` exposes only names and\n // values, not the domain/path we need to preserve. The write goes through\n // document.cookie because WebKit exposes Cookie Store on localhost but does\n // not commit cookies written through cookieStore.set() there.\n //\n // Capture the current lockState and compare it in the callback so we only\n // write if the lock we observed at call time is still held. This guards\n // against two races: (a) the scope ended between get and set (lockState is\n // now null), and (b) the scope ended and a new one was acquired in the same\n // gap (lockState is a different object). In either case we must not write —\n // doing so would leak stale state into the next scope or outlive the current\n // one. It cannot close one window, though: the callback can run after an\n // external delete but before the deleted-event handler nulls lockState, so\n // the guard still passes and we resurrect the cookie. The deleted handler\n // clears any such entry once the lock is released (see the `event.deleted`\n // loop below).\n const lockAtCall = lockState\n cookieStore.get(NEXT_INSTANT_TEST_COOKIE).then((existing: any) => {\n if (existing && lockState === lockAtCall && lockAtCall !== null) {\n writeDocumentCookie(value, existing)\n }\n })\n}\n\n/**\n * The \"wait for the locked navigation's prefetch to fulfill\" state for a single\n * locked navigation. `promise` resolves once that prefetch has spawned every\n * request and all of them have fulfilled, so the navigation reads present data\n * rather than a still-in-flight entry. Owned by the prefetch task (one per\n * navigation, so successive navigations in a scope resolve independently) and\n * also tracked in `NavigationLockState.activePrefetches` so the lock can\n * force-resolve any that are still pending when it's released.\n *\n * `pendingCount` holds one reference for the scheduler while it is still\n * spawning, plus one per in-flight entry; `promise` resolves when it drains to\n * 0. `trackedEntries` dedupes entry registration.\n */\nexport type NavigationLockPrefetch = {\n promise: Promise<void>\n resolve: () => void\n pendingCount: number\n trackedEntries: Set<PendingSegmentCacheEntry>\n}\n\nexport type NavigationLockState = {\n // Resolves when the lock is released (the testing scope ends). Out-of-band\n // user fetches blocked by `globalFetchOverride` wait on this so they dispatch\n // only once the scope ends. (A locked navigation's *withheld dynamic write*\n // waits on `currentNavigation` instead — see below.)\n released: Promise<void>\n resolveReleased: () => void\n // The pre-lock `window.fetch`, captured at `acquireLock` time and\n // restored at `releaseLock`. Internal Next.js code reads this via\n // `getPreLockFetch` to bypass the override we install on `window.fetch`\n // during a lock scope.\n fetch: typeof fetch\n // Every prefetch-completion state for this scope that hasn't resolved yet.\n // A prefetch removes itself when it drains; on release, any still here are\n // force-resolved so no navigation hangs waiting on a prefetch that the scope\n // ended before it could finish.\n activePrefetches: Set<NavigationLockPrefetch>\n // Every segment entry that was (re)fetched within this lock scope. Navigation\n // reads are restricted to these, so each instant() navigation observes only\n // data fetched under the lock — a \"clean read\" — and never matches a stale\n // entry left in the cache by an earlier navigation or prefetch. See\n // `readSegmentCacheEntryForNavigation`.\n ownedEntries: Set<SegmentCacheEntry>\n // The withheld-data gate for the current locked navigation. A locked\n // navigation's dynamic write waits on this rather than on the scope-wide\n // `released`. Each navigation captures the promise when it begins (via\n // `beginLockedNavigation` or `getCurrentNavigationGate`) and awaits that\n // immutable snapshot, never this mutable field. `beginLockedNavigation`\n // rolls the field over on each new locked navigation: it resolves the\n // current promise — so the *previous* navigation's withheld data is written\n // out and the cache nodes it produced stop holding pending deferred promises\n // that a reused shared segment would otherwise suspend on — then installs a\n // fresh one. `releaseLock` resolves it too. Net effect: only the most recent\n // navigation's data stays withheld; a new navigation always releases the\n // previous one.\n currentNavigation: Promise<void>\n resolveCurrentNavigation: () => void\n}\n\nlet lockState: NavigationLockState | null = null\n\nexport function getPreLockFetch(): typeof fetch | null {\n return lockState !== null ? lockState.fetch : null\n}\n\n/**\n * Creates the \"wait for prefetch to fulfill\" state for one locked navigation,\n * registers it on the current lock, and returns it (the caller stores it on the\n * prefetch task and awaits `.promise`). Returns null if no lock is held.\n *\n * `pendingCount` starts at 1, representing the scheduler itself while it is\n * still spawning requests; that reference is released by\n * `finishNavigationLockPrefetchSpawning`. Each spawned pending entry adds\n * another (see `trackNavigationLockPrefetchEntry`). `promise` resolves when the\n * count drains to 0 — i.e. spawning finished and every entry fulfilled.\n */\nexport function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {\n if (lockState !== null) {\n let resolve: () => void\n const promise = new Promise<void>((r) => {\n resolve = r\n })\n const prefetch: NavigationLockPrefetch = {\n promise,\n resolve: resolve!,\n pendingCount: 1,\n trackedEntries: new Set(),\n }\n lockState.activePrefetches.add(prefetch)\n return prefetch\n }\n return null\n}\n\n/**\n * Records a freshly-created segment entry as owned by the current lock scope, so\n * navigation reads will match it — and only entries created within the scope\n * (see `NavigationLockState.ownedEntries`). Called from\n * `createDetachedSegmentCacheEntry`, the single factory every creation path\n * funnels through, so re-keyed entries created during response processing (e.g.\n * a runtime prefetch resolving a concrete param) are owned too. No-op when no\n * lock is held.\n */\nexport function recordNavigationLockOwnedEntry(entry: SegmentCacheEntry): void {\n if (lockState !== null) {\n lockState.ownedEntries.add(entry)\n }\n}\n\n/**\n * Called by `upgradeToPendingSegment` whenever the locked-navigation prefetch\n * spawns a pending segment entry. Adds the entry to the prefetch's ref count and\n * decrements when it fulfills (or rejects — `waitForSegmentCacheEntry` resolves\n * to null). Deduped so the same entry never double-counts.\n */\nexport function trackNavigationLockPrefetchEntry(\n prefetch: NavigationLockPrefetch,\n entry: PendingSegmentCacheEntry\n): void {\n if (prefetch.trackedEntries.has(entry)) {\n return\n }\n prefetch.trackedEntries.add(entry)\n prefetch.pendingCount++\n const onSettled = () => {\n prefetch.pendingCount--\n settleNavigationLockPrefetchIfDrained(prefetch)\n }\n // Decrement whether the entry fulfills or its request rejects, so a failed\n // segment can't leave the navigation waiting forever.\n waitForSegmentCacheEntry(entry).then(onSettled, onSettled)\n}\n\n/**\n * Called once the scheduler has finished spawning every request for the\n * locked-navigation prefetch, releasing the scheduler's reference from the ref\n * count. The prefetch resolves here if every spawned entry already fulfilled.\n */\nexport function finishNavigationLockPrefetchSpawning(\n prefetch: NavigationLockPrefetch\n): void {\n prefetch.pendingCount--\n settleNavigationLockPrefetchIfDrained(prefetch)\n}\n\nfunction settleNavigationLockPrefetchIfDrained(\n prefetch: NavigationLockPrefetch\n): void {\n if (prefetch.pendingCount === 0) {\n // Unregister from the lock (if still held) and resolve. Resolving is\n // idempotent, so it's safe even if the lock already force-resolved this on\n // release.\n if (lockState !== null) {\n lockState.activePrefetches.delete(prefetch)\n }\n prefetch.resolve()\n }\n}\n\nfunction acquireLock(): void {\n if (lockState !== null) {\n return\n }\n let resolveReleased: () => void\n const released = new Promise<void>((r) => {\n resolveReleased = r\n })\n let resolveCurrentNavigation: () => void\n const currentNavigation = new Promise<void>((r) => {\n resolveCurrentNavigation = r\n })\n lockState = {\n released,\n resolveReleased: resolveReleased!,\n fetch: window.fetch,\n activePrefetches: new Set(),\n ownedEntries: new Set(),\n currentNavigation,\n resolveCurrentNavigation: resolveCurrentNavigation!,\n }\n\n // Install the fetch blocker. We only intercept `window.fetch` for the\n // duration of the lock so that — outside of a testing scope — user-\n // installed overrides of `window.fetch` are untouched.\n window.fetch = globalFetchOverride\n}\n\nfunction releaseLock(): void {\n if (lockState === null) {\n return\n }\n // Restore the pre-lock `window.fetch` before resolving the lock promise\n // so any fetches queued on the promise see the restored fetch.\n window.fetch = lockState.fetch\n const { resolveReleased, activePrefetches, resolveCurrentNavigation } =\n lockState\n lockState = null\n // Force-resolve every prefetch that hasn't finished, so a navigation still\n // waiting on one doesn't hang now that the scope is ending.\n for (const prefetch of activePrefetches) {\n prefetch.resolve()\n }\n // Resolve the current locked navigation's withheld-data gate, so its gated\n // dynamic write unblocks now that the scope is ending.\n resolveCurrentNavigation()\n // Resolve the release promise so blocked out-of-band fetches dispatch too.\n resolveReleased()\n}\n\n/**\n * Called when a new locked navigation begins (from `navigate` while the lock is\n * held). Rolls over the lock's withheld-data gate: it resolves the current\n * `currentNavigation` promise — so the *previous* locked navigation's withheld\n * dynamic write proceeds and the cache nodes it produced stop holding pending\n * deferred `rsc` promises that a reused shared segment in this navigation would\n * otherwise suspend on — then installs a fresh promise for this navigation.\n * Only the most recent navigation's data stays withheld; a new navigation\n * always releases the previous one. Returns this navigation's gate — the\n * immutable promise its dynamic write awaits — or null when no lock is held.\n *\n * This is the testing-lock behavior for repeated navigations while paused. It\n * is not a principled fix for the underlying `useDeferredValue`/reuse-suspend\n * behavior; it just ensures that, under the lock, a reused segment never\n * carries a still-pending deferred `rsc` from an earlier navigation.\n */\nexport function beginLockedNavigation(): Promise<void> | null {\n if (lockState === null) {\n return null\n }\n // Release the previous locked navigation's withheld data, then roll over to a\n // fresh gate for this navigation — all without ending the scope.\n lockState.resolveCurrentNavigation()\n let resolveCurrentNavigation: () => void\n const currentNavigation = new Promise<void>((r) => {\n resolveCurrentNavigation = r\n })\n lockState.currentNavigation = currentNavigation\n lockState.resolveCurrentNavigation = resolveCurrentNavigation!\n return currentNavigation\n}\n\n/**\n * Called when the router applies a history traversal (Back/Forward restore) while\n * the testing lock is active. A traversal is not a capture — the mental model is\n * that history entries are already cached — so it must not participate in the\n * current capture. Instead it resets the lock to a fresh pending scope:\n *\n * - `releaseLock` flushes every still-withheld write from prior forward\n * navigations, so the pages you navigated away from finish streaming.\n * - `acquireLock` immediately re-arms a fresh pending scope (no gap where the\n * lock or fetch blocker is down).\n * - the cookie flips from the captured state back to pending.\n *\n * The traversal's own dynamic requests are spawned ungated by the caller (see\n * `restore-reducer`), so they render from cache or fetch normally rather than\n * being withheld.\n */\nexport function resetNavigationLockToPending(): void {\n if (lockState === null || typeof document === 'undefined') {\n return\n }\n releaseLock()\n acquireLock()\n writeCookieValue([0, `c${Math.random()}`])\n}\n\n/**\n * Returns true if the request targets a dev-server endpoint — one of the\n * hot-reloader middleware routes (error overlay, source maps, launch-editor,\n * devtools). They all share the `/__nextjs_` path prefix and are always\n * requested root-relative on the same origin.\n */\nfunction isDevServerRequest(input: RequestInfo | URL): boolean {\n let url: URL\n try {\n url = new URL(\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input\n : input.url,\n window.location.href\n )\n } catch {\n return false\n }\n return (\n url.origin === window.location.origin &&\n url.pathname.startsWith('/__nextjs_')\n )\n}\n\n/**\n * Global fetch override\n *\n * While the navigation lock is active, we install this as `window.fetch` so\n * out-of-band client-side fetches (e.g. `fetch('/api/data')` inside a\n * useEffect) are blocked until the lock is released. Next.js internals\n * bypass the override by importing `fetch` from `./fetch`, which reads the\n * captured pre-lock fetch via `getPreLockFetch`.\n *\n * NOTE: This override only affects environments where the Instant Navigation\n * Testing API is enabled. It has no impact on live production behavior.\n */\nfunction globalFetchOverride(\n input: RequestInfo | URL,\n init?: RequestInit\n): Promise<Response> {\n if (lockState === null) {\n // Lock is not active. Fall through to the global fetch — we reach this\n // only if a caller captured a reference to this function during a lock\n // scope and invoked it after release.\n return fetch(input, init)\n }\n if (process.env.__NEXT_DEV_SERVER && isDevServerRequest(input)) {\n // Dev-server requests must not be gated on the testing lock — blocking\n // them would break the error overlay, source maps, and devtools for the\n // whole scope. Dispatch immediately through the pre-lock fetch. Copy to a\n // local so the call doesn't bind `this` to the lock state object (native\n // fetch throws \"Illegal invocation\" for a foreign receiver).\n const preLockFetch = lockState.fetch\n return preLockFetch(input, init)\n }\n // Block user-initiated fetches until the lock is released, then dispatch\n // through the fetch captured at acquire time. Reading from `lockState`\n // (rather than `window.fetch`) pins to the capture even if `window.fetch`\n // is reassigned after release.\n const currentLock = lockState\n return currentLock.released.then(() => {\n const preLockFetch = currentLock.fetch\n return preLockFetch(input, init)\n })\n}\n\n/**\n * Sets up the cookie-based lock. Handles the initial page load state and\n * registers a CookieStore listener for runtime changes.\n *\n * Called once during page initialization from app-globals.ts.\n */\nexport function startListeningForInstantNavigationCookie(): void {\n // If the server served a shell, this is an MPA page load\n // while the lock is held. Transition to captured-MPA and acquire.\n if (self.__next_instant_test) {\n if (typeof cookieStore !== 'undefined') {\n // If the cookie was already cleared during the MPA page\n // transition, reload to get the full dynamic page.\n cookieStore.get(NEXT_INSTANT_TEST_COOKIE).then((cookie: any) => {\n if (!cookie) {\n window.location.reload()\n }\n })\n }\n\n // Acquire the lock before writing the cookie. writeCookieValue's\n // guard requires lockState to be non-null at call time (so a stale\n // write can't outlive its scope). On a fresh page load that scope\n // is the one we're about to establish, so we have to establish it\n // first.\n acquireLock()\n writeCookieValue([1, `c${Math.random()}`, null])\n }\n\n if (typeof cookieStore === 'undefined') {\n return\n }\n\n cookieStore.addEventListener('change', (event: CookieChangeEvent) => {\n for (const cookie of event.changed) {\n if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {\n const state = parseCookieValue(cookie.value ?? '')\n\n if (state === 'pending') {\n // External actor starting a new lock scope.\n if (lockState !== null) {\n // This can be the delayed CookieStore event for the pending\n // cookie that was already observed synchronously from\n // document.cookie. Keep the existing lock identity so work that\n // captured it keeps waiting on the same promise.\n return\n }\n acquireLock()\n }\n // Captured value (our own transition) or empty. Ignore.\n return\n }\n }\n\n for (const cookie of event.deleted) {\n if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {\n if (lockState === null) {\n // Either no lock is active, or this is the re-entrant change event\n // from the defensive clear below (which runs after releaseLock).\n // Nothing to release either way.\n return\n }\n releaseLock()\n // A captured write from this page's bootstrap can resurrect the\n // cookie in the narrow gap between the external delete and this\n // handler: writeCookieValue's guard only rejects the write once the\n // lock is torn down, which happens here. Now that the lock is\n // released, no further captured write can re-add the cookie, so clear\n // any entry that was resurrected in that gap. Otherwise an unlock\n // that falls back to a hard reload (when the shell has not yet\n // hydrated) would carry the stale cookie, be served the shell again,\n // and re-enter instant mode with no scope left to release it.\n if (typeof document !== 'undefined') {\n document.cookie = `${NEXT_INSTANT_TEST_COOKIE}=; Path=/; Max-Age=0`\n }\n refreshOnInstantNavigationUnlock()\n return\n }\n }\n })\n}\n\n/**\n * Transitions the cookie from pending to captured-SPA once the prefetch resolves\n * and the navigation is known to be an SPA.\n */\nexport function updateCapturedSPAToTree(\n fromTree: FlightRouterState,\n toTree: FlightRouterState\n): void {\n writeCookieValue([1, `c${Math.random()}`, { from: fromTree, to: toTree }])\n}\n\n/**\n * Returns true if the navigation lock is currently active.\n */\nexport function isNavigationLocked(): boolean {\n if (lockState !== null) {\n return true\n }\n\n // If `lockState` is null, fall back to reading the test cookie\n // synchronously from `document.cookie`. This accounts for a small race\n // between `cookieStore.set(...)` and its corresponding `change` event.\n // During that gap `lockState` is still null even though the cookie\n // indicates a new lock scope is starting.\n if (typeof document === 'undefined') {\n return false\n }\n const allCookies = document.cookie\n if (!allCookies.includes(NEXT_INSTANT_TEST_COOKIE)) {\n // Fast bail-out: in almost every navigation the test cookie is not\n // set at all.\n return false\n }\n const target = NEXT_INSTANT_TEST_COOKIE + '='\n for (const segment of allCookies.split(';')) {\n const trimmed = segment.trim()\n if (\n trimmed.startsWith(target) &&\n parseCookieValue(trimmed.slice(target.length)) === 'pending'\n ) {\n // The cookie was set by an external actor but the change event was not\n // yet dispatched. Acquire the lock synchronously.\n acquireLock()\n return true\n }\n }\n return false\n}\n\nexport function getCurrentNavigationLock(): NavigationLockState | null {\n return lockState\n}\n\n/**\n * Returns the current locked navigation's withheld-data gate — the same\n * immutable promise `beginLockedNavigation` handed that navigation — or null\n * when no lock is held. For router work that spawns a dynamic write without\n * beginning a navigation of its own (refreshes, server actions, server\n * patches): it gates behind the navigation that is current when it spawns, so\n * the next locked navigation (or unlock) releases it.\n */\nexport function getCurrentNavigationGate(): Promise<void> | null {\n return lockState !== null ? lockState.currentNavigation : null\n}\n\n/**\n * Decides whether segment reads during a navigation should be restricted to\n * shell entries (every param substituted with Fallback) rather than matching\n * entries that vary on concrete route params.\n *\n * The testing tools (Navigation Inspector, instant()) simulate what a user\n * would see with a warm cache. When the lock is held, partial prefetching is\n * enabled for the target route, and no whole-route (\"speculative\") prefetch\n * would have been made, only the shell is prefetched — so that's all a\n * navigation should be allowed to match. A speculative prefetch happens for a\n * `<Link prefetch={true}>` or an eagerly-prefetched subtree, in which case the\n * concrete-param entry is genuinely warm and may be matched.\n *\n * Always returns false outside the testing API, via the aliased\n * `navigation-testing-lock.disabled` module.\n */\nexport function shouldRestrictNavigationToShell(\n rootPrefetchHints: number,\n linkFetchStrategy: FetchStrategy\n): boolean {\n return (\n isNavigationLocked() &&\n (rootPrefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0 &&\n !subtreeHasSpeculativePrefetch(linkFetchStrategy, rootPrefetchHints)\n )\n}\n"],"names":["PrefetchHint","NEXT_INSTANT_TEST_COOKIE","refreshOnInstantNavigationUnlock","subtreeHasSpeculativePrefetch","waitForSegmentCacheEntry","parseCookieValue","raw","parsed","JSON","parse","Array","isArray","length","rawState","writeDocumentCookie","value","options","document","cookie","stringify","path","domain","writeCookieValue","cookieStore","lockAtCall","lockState","get","then","existing","getPreLockFetch","fetch","beginNavigationLockPrefetch","resolve","promise","Promise","r","prefetch","pendingCount","trackedEntries","Set","activePrefetches","add","recordNavigationLockOwnedEntry","entry","ownedEntries","trackNavigationLockPrefetchEntry","has","onSettled","settleNavigationLockPrefetchIfDrained","finishNavigationLockPrefetchSpawning","delete","acquireLock","resolveReleased","released","resolveCurrentNavigation","currentNavigation","window","globalFetchOverride","releaseLock","beginLockedNavigation","resetNavigationLockToPending","Math","random","isDevServerRequest","input","url","URL","location","href","origin","pathname","startsWith","init","process","env","__NEXT_DEV_SERVER","preLockFetch","currentLock","startListeningForInstantNavigationCookie","self","__next_instant_test","reload","addEventListener","event","changed","name","state","deleted","updateCapturedSPAToTree","fromTree","toTree","from","to","isNavigationLocked","allCookies","includes","target","segment","split","trimmed","trim","slice","getCurrentNavigationLock","getCurrentNavigationGate","shouldRestrictNavigationToShell","rootPrefetchHints","linkFetchStrategy","SubtreeHasPartialPrefetching"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;CAkBC,GAED,SACEA,YAAY,QAGP,uCAAsC;AAC7C,SAASC,wBAAwB,QAAQ,wBAAuB;AAChE,SAASC,gCAAgC,QAAQ,sBAAqB;AACtE,SAASC,6BAA6B,QAAQ,cAAa;AAC3D,SACEC,wBAAwB,QAGnB,UAAS;AAKhB,SAASC,iBAAiBC,GAAW;IACnC,IAAIA,QAAQ,IAAI;QACd,OAAO;IACT;IACA,IAAI;QACF,MAAMC,SAASC,KAAKC,KAAK,CAACH;QAC1B,IAAII,MAAMC,OAAO,CAACJ,SAAS;YACzB,IAAIA,OAAOK,MAAM,IAAI,GAAG;gBACtB,MAAMC,WAAWN,MAAM,CAAC,EAAE;gBAC1B,OAAOM,aAAa,OAAO,QAAQ;YACrC;QACF;I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WAAWH,WAAWI,KAAK,CAAC,KAAM;QAC3C,MAAMC,UAAUF,QAAQG,IAAI;QAC5B,IACED,QAAQ5B,UAAU,CAACyB,WACnB3F,iBAAiB8F,QAAQE,KAAK,CAACL,OAAOpF,MAAM,OAAO,WACnD;YACA,uEAAuE;YACvE,kDAAkD;YAClDuC;YACA,OAAO;QACT;IACF;IACA,OAAO;AACT;AAEA,OAAO,SAASmD;IACd,OAAO7E;AACT;AAEA;;;;;;;CAOC,GACD,OAAO,SAAS8E;IACd,OAAO9E,cAAc,OAAOA,UAAU8B,iBAAiB,GAAG;AAC5D;AAEA;;;;;;;;;;;;;;;CAeC,GACD,OAAO,SAASiD,gCACdC,iBAAyB,EACzBC,iBAAgC;IAEhC,OACEb,wBACA,AAACY,CAAAA,oBAAoBzG,aAAa2G,4BAA4B,AAAD,MAAO,KACpE,CAACxG,8BAA8BuG,mBAAmBD;AAEtD","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/client/components/segment-cache/navigation-testing-lock.ts"],"sourcesContent":["/**\n * Navigation lock for the Instant Navigation Testing API.\n *\n * Manages the in-memory lock (a promise) that gates dynamic data writes\n * during instant navigation captures, and owns all cookie state\n * transitions (pending → captured-MPA, pending → captured-SPA).\n *\n * External actors (Playwright, devtools) set [0] to start a lock scope\n * and delete the cookie to end one. Next.js writes captured values.\n * The CookieStore handler distinguishes them by value: pending = external,\n * captured = self-write (ignored).\n *\n * This module assumes the Instant Navigation Testing API is enabled. When it\n * is disabled, the bundler resolves this module to\n * `./navigation-testing-lock.disabled` instead (see\n * `create-compiler-aliases.ts` for webpack and\n * `crates/next-core/src/next_import_map.rs` for Turbopack), so none of this\n * code ships in the browser bundle.\n */\n\nimport {\n PrefetchHint,\n type FlightRouterState,\n type InstantCookie,\n} from '../../../shared/lib/app-router-types'\nimport { NEXT_INSTANT_TEST_COOKIE } from '../app-router-headers'\nimport { refreshOnInstantNavigationUnlock } from '../use-action-queue'\nimport { subtreeHasSpeculativePrefetch } from './scheduler'\nimport type { SegmentCacheEntry } from './cache'\nimport { createCacheMap, type CacheMap } from './cache-map'\nimport type { FetchStrategy } from './types'\n\ntype InstantNavCookieState = 'empty' | 'pending' | 'mpa' | 'spa'\n\nfunction parseCookieValue(raw: string): InstantNavCookieState {\n if (raw === '') {\n return 'empty'\n }\n try {\n const parsed = JSON.parse(raw)\n if (Array.isArray(parsed)) {\n if (parsed.length >= 3) {\n const rawState = parsed[2]\n return rawState === null ? 'mpa' : 'spa'\n }\n }\n } catch {}\n return 'pending'\n}\n\nfunction writeDocumentCookie(\n value: InstantCookie,\n options: { domain?: string | null; path?: string | null }\n): void {\n if (typeof document === 'undefined') {\n return\n }\n let cookie = `${NEXT_INSTANT_TEST_COOKIE}=${JSON.stringify(value)}; Path=${\n options.path ?? '/'\n }`\n if (options.domain) {\n cookie += `; Domain=${options.domain}`\n }\n document.cookie = cookie\n}\n\nfunction writeCookieValue(value: InstantCookie): void {\n if (typeof cookieStore === 'undefined') {\n return\n }\n // Read the existing cookie to preserve its attributes (domain, path), then\n // write back with the new value. This updates the same cookie entry that the\n // external actor created, regardless of how it was scoped. The read goes\n // through `cookieStore.get` because `document.cookie` exposes only names and\n // values, not the domain/path we need to preserve. The write goes through\n // document.cookie because WebKit exposes Cookie Store on localhost but does\n // not commit cookies written through cookieStore.set() there.\n //\n // Capture the current lockState and compare it in the callback so we only\n // write if the lock we observed at call time is still held. This guards\n // against two races: (a) the scope ended between get and set (lockState is\n // now null), and (b) the scope ended and a new one was acquired in the same\n // gap (lockState is a different object). In either case we must not write —\n // doing so would leak stale state into the next scope or outlive the current\n // one. It cannot close one window, though: the callback can run after an\n // external delete but before the deleted-event handler nulls lockState, so\n // the guard still passes and we resurrect the cookie. The deleted handler\n // clears any such entry once the lock is released (see the `event.deleted`\n // loop below).\n const lockAtCall = lockState\n cookieStore.get(NEXT_INSTANT_TEST_COOKIE).then((existing: any) => {\n if (existing && lockState === lockAtCall && lockAtCall !== null) {\n writeDocumentCookie(value, existing)\n }\n })\n}\n\n/**\n * The \"wait for the locked navigation's prefetch to fulfill\" state for a single\n * locked navigation. `promise` resolves when the driving prefetch task\n * completes — which the scheduler only allows after a full pass has observed\n * every segment response it cares about (see `blockTaskOnPendingResponse` in\n * scheduler.ts) — so the navigation reads present data rather than a\n * still-in-flight entry. Owned by the prefetch task (one per navigation, so\n * successive navigations in a scope resolve independently) and also tracked\n * in `NavigationLockState.activePrefetches` so the lock can force-resolve any\n * that are still pending when it's released.\n */\nexport type NavigationLockPrefetch = {\n promise: Promise<void>\n resolve: () => void\n}\n\nexport type NavigationLockState = {\n // Resolves when the lock is released (the testing scope ends). Out-of-band\n // user fetches blocked by `globalFetchOverride` wait on this so they dispatch\n // only once the scope ends. (A locked navigation's *withheld dynamic write*\n // waits on `currentNavigation` instead — see below.)\n released: Promise<void>\n resolveReleased: () => void\n // The pre-lock `window.fetch`, captured at `acquireLock` time and\n // restored at `releaseLock`. Internal Next.js code reads this via\n // `getPreLockFetch` to bypass the override we install on `window.fetch`\n // during a lock scope.\n fetch: typeof fetch\n // Every prefetch-completion state for this scope that hasn't resolved yet.\n // A prefetch removes itself when its driving task completes; on release, any\n // still here are force-resolved so no navigation hangs waiting on a prefetch\n // that the scope ended before it could finish.\n activePrefetches: Set<NavigationLockPrefetch>\n // The scope's private segment cache. Prefetch tasks scheduled while the\n // lock is held are bound to this map instead of the shared one, and a\n // locked navigation inherits the map of the task that drives it (see\n // `segmentCacheMap` in cache.ts). It starts empty, so each instant()\n // navigation observes only data fetched under the lock — a \"clean read\" —\n // and never matches a stale entry left in the shared cache by an earlier\n // navigation, prefetch, or scope. Discarded when the lock is released; its\n // entries are reclaimed by the LRU under memory pressure.\n segmentCacheMap: CacheMap<SegmentCacheEntry>\n // The withheld-data gate for the current locked navigation. A locked\n // navigation's dynamic write waits on this rather than on the scope-wide\n // `released`. Each navigation captures the promise when it begins (via\n // `beginLockedNavigation` or `getCurrentNavigationGate`) and awaits that\n // immutable snapshot, never this mutable field. `beginLockedNavigation`\n // rolls the field over on each new locked navigation: it resolves the\n // current promise — so the *previous* navigation's withheld data is written\n // out and the cache nodes it produced stop holding pending deferred promises\n // that a reused shared segment would otherwise suspend on — then installs a\n // fresh one. `releaseLock` resolves it too. Net effect: only the most recent\n // navigation's data stays withheld; a new navigation always releases the\n // previous one.\n currentNavigation: Promise<void>\n resolveCurrentNavigation: () => void\n}\n\nlet lockState: NavigationLockState | null = null\n\nexport function getPreLockFetch(): typeof fetch | null {\n return lockState !== null ? lockState.fetch : null\n}\n\n/**\n * Creates the \"wait for prefetch to fulfill\" state for one locked navigation,\n * registers it on the current lock, and returns it (the caller stores it on the\n * prefetch task and awaits `.promise`). Returns null if no lock is held.\n * Resolved by the scheduler via `resolveNavigationLockPrefetch` when the\n * driving prefetch task completes.\n */\nexport function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {\n if (lockState !== null) {\n let resolve: () => void\n const promise = new Promise<void>((r) => {\n resolve = r\n })\n const prefetch: NavigationLockPrefetch = {\n promise,\n resolve: resolve!,\n }\n lockState.activePrefetches.add(prefetch)\n return prefetch\n }\n return null\n}\n\n/**\n * Returns the current lock scope's private segment cache map, or null when no\n * lock is held. See `NavigationLockState.segmentCacheMap`.\n */\nexport function getNavigationLockSegmentCacheMap(): CacheMap<SegmentCacheEntry> | null {\n return lockState !== null ? lockState.segmentCacheMap : null\n}\n\n/**\n * Called by the scheduler when the locked-navigation prefetch task completes.\n * A task only completes after a full pass observed every segment response it\n * cares about, so the data the navigation will read has settled by this\n * point. Unregisters from the lock (if still held) and resolves. Resolving is\n * idempotent, so it's safe even if the lock already force-resolved this on\n * release.\n */\nexport function resolveNavigationLockPrefetch(\n prefetch: NavigationLockPrefetch\n): void {\n if (lockState !== null) {\n lockState.activePrefetches.delete(prefetch)\n }\n prefetch.resolve()\n}\n\nfunction acquireLock(): void {\n if (lockState !== null) {\n return\n }\n let resolveReleased: () => void\n const released = new Promise<void>((r) => {\n resolveReleased = r\n })\n let resolveCurrentNavigation: () => void\n const currentNavigation = new Promise<void>((r) => {\n resolveCurrentNavigation = r\n })\n lockState = {\n released,\n resolveReleased: resolveReleased!,\n fetch: window.fetch,\n activePrefetches: new Set(),\n segmentCacheMap: createCacheMap(),\n currentNavigation,\n resolveCurrentNavigation: resolveCurrentNavigation!,\n }\n\n // Install the fetch blocker. We only intercept `window.fetch` for the\n // duration of the lock so that — outside of a testing scope — user-\n // installed overrides of `window.fetch` are untouched.\n window.fetch = globalFetchOverride\n}\n\nfunction releaseLock(): void {\n if (lockState === null) {\n return\n }\n // Restore the pre-lock `window.fetch` before resolving the lock promise\n // so any fetches queued on the promise see the restored fetch.\n window.fetch = lockState.fetch\n const { resolveReleased, activePrefetches, resolveCurrentNavigation } =\n lockState\n lockState = null\n // Force-resolve every prefetch that hasn't finished, so a navigation still\n // waiting on one doesn't hang now that the scope is ending.\n for (const prefetch of activePrefetches) {\n prefetch.resolve()\n }\n // Resolve the current locked navigation's withheld-data gate, so its gated\n // dynamic write unblocks now that the scope is ending.\n resolveCurrentNavigation()\n // Resolve the release promise so blocked out-of-band fetches dispatch too.\n resolveReleased()\n}\n\n/**\n * Called when a new locked navigation begins (from `navigate` while the lock is\n * held). Rolls over the lock's withheld-data gate: it resolves the current\n * `currentNavigation` promise — so the *previous* locked navigation's withheld\n * dynamic write proceeds and the cache nodes it produced stop holding pending\n * deferred `rsc` promises that a reused shared segment in this navigation would\n * otherwise suspend on — then installs a fresh promise for this navigation.\n * Only the most recent navigation's data stays withheld; a new navigation\n * always releases the previous one. Returns this navigation's gate — the\n * immutable promise its dynamic write awaits — or null when no lock is held.\n *\n * This is the testing-lock behavior for repeated navigations while paused. It\n * is not a principled fix for the underlying `useDeferredValue`/reuse-suspend\n * behavior; it just ensures that, under the lock, a reused segment never\n * carries a still-pending deferred `rsc` from an earlier navigation.\n */\nexport function beginLockedNavigation(): Promise<void> | null {\n if (lockState === null) {\n return null\n }\n // Release the previous locked navigation's withheld data, then roll over to a\n // fresh gate for this navigation — all without ending the scope.\n lockState.resolveCurrentNavigation()\n let resolveCurrentNavigation: () => void\n const currentNavigation = new Promise<void>((r) => {\n resolveCurrentNavigation = r\n })\n lockState.currentNavigation = currentNavigation\n lockState.resolveCurrentNavigation = resolveCurrentNavigation!\n return currentNavigation\n}\n\n/**\n * Called when the router applies a history traversal (Back/Forward restore) while\n * the testing lock is active. A traversal is not a capture — the mental model is\n * that history entries are already cached — so it must not participate in the\n * current capture. Instead it resets the lock to a fresh pending scope:\n *\n * - `releaseLock` flushes every still-withheld write from prior forward\n * navigations, so the pages you navigated away from finish streaming.\n * - `acquireLock` immediately re-arms a fresh pending scope (no gap where the\n * lock or fetch blocker is down).\n * - the cookie flips from the captured state back to pending.\n *\n * The traversal's own dynamic requests are spawned ungated by the caller (see\n * `restore-reducer`), so they render from cache or fetch normally rather than\n * being withheld.\n */\nexport function resetNavigationLockToPending(): void {\n if (lockState === null || typeof document === 'undefined') {\n return\n }\n releaseLock()\n acquireLock()\n writeCookieValue([0, `c${Math.random()}`])\n}\n\n/**\n * Returns true if the request targets a dev-server endpoint — one of the\n * hot-reloader middleware routes (error overlay, source maps, launch-editor,\n * devtools). They all share the `/__nextjs_` path prefix and are always\n * requested root-relative on the same origin.\n */\nfunction isDevServerRequest(input: RequestInfo | URL): boolean {\n let url: URL\n try {\n url = new URL(\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input\n : input.url,\n window.location.href\n )\n } catch {\n return false\n }\n return (\n url.origin === window.location.origin &&\n url.pathname.startsWith('/__nextjs_')\n )\n}\n\n/**\n * Global fetch override\n *\n * While the navigation lock is active, we install this as `window.fetch` so\n * out-of-band client-side fetches (e.g. `fetch('/api/data')` inside a\n * useEffect) are blocked until the lock is released. Next.js internals\n * bypass the override by importing `fetch` from `./fetch`, which reads the\n * captured pre-lock fetch via `getPreLockFetch`.\n *\n * NOTE: This override only affects environments where the Instant Navigation\n * Testing API is enabled. It has no impact on live production behavior.\n */\nfunction globalFetchOverride(\n input: RequestInfo | URL,\n init?: RequestInit\n): Promise<Response> {\n if (lockState === null) {\n // Lock is not active. Fall through to the global fetch — we reach this\n // only if a caller captured a reference to this function during a lock\n // scope and invoked it after release.\n return fetch(input, init)\n }\n if (process.env.__NEXT_DEV_SERVER && isDevServerRequest(input)) {\n // Dev-server requests must not be gated on the testing lock — blocking\n // them would break the error overlay, source maps, and devtools for the\n // whole scope. Dispatch immediately through the pre-lock fetch. Copy to a\n // local so the call doesn't bind `this` to the lock state object (native\n // fetch throws \"Illegal invocation\" for a foreign receiver).\n const preLockFetch = lockState.fetch\n return preLockFetch(input, init)\n }\n // Block user-initiated fetches until the lock is released, then dispatch\n // through the fetch captured at acquire time. Reading from `lockState`\n // (rather than `window.fetch`) pins to the capture even if `window.fetch`\n // is reassigned after release.\n const currentLock = lockState\n return currentLock.released.then(() => {\n const preLockFetch = currentLock.fetch\n return preLockFetch(input, init)\n })\n}\n\n/**\n * Sets up the cookie-based lock. Handles the initial page load state and\n * registers a CookieStore listener for runtime changes.\n *\n * Called once during page initialization from app-globals.ts.\n */\nexport function startListeningForInstantNavigationCookie(): void {\n // If the server served a shell, this is an MPA page load\n // while the lock is held. Transition to captured-MPA and acquire.\n if (self.__next_instant_test) {\n if (typeof cookieStore !== 'undefined') {\n // If the cookie was already cleared during the MPA page\n // transition, reload to get the full dynamic page.\n cookieStore.get(NEXT_INSTANT_TEST_COOKIE).then((cookie: any) => {\n if (!cookie) {\n window.location.reload()\n }\n })\n }\n\n // Acquire the lock before writing the cookie. writeCookieValue's\n // guard requires lockState to be non-null at call time (so a stale\n // write can't outlive its scope). On a fresh page load that scope\n // is the one we're about to establish, so we have to establish it\n // first.\n acquireLock()\n writeCookieValue([1, `c${Math.random()}`, null])\n }\n\n if (typeof cookieStore === 'undefined') {\n return\n }\n\n cookieStore.addEventListener('change', (event: CookieChangeEvent) => {\n for (const cookie of event.changed) {\n if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {\n const state = parseCookieValue(cookie.value ?? '')\n\n if (state === 'pending') {\n // External actor starting a new lock scope.\n if (lockState !== null) {\n // This can be the delayed CookieStore event for the pending\n // cookie that was already observed synchronously from\n // document.cookie. Keep the existing lock identity so work that\n // captured it keeps waiting on the same promise.\n return\n }\n acquireLock()\n }\n // Captured value (our own transition) or empty. Ignore.\n return\n }\n }\n\n for (const cookie of event.deleted) {\n if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {\n if (lockState === null) {\n // Either no lock is active, or this is the re-entrant change event\n // from the defensive clear below (which runs after releaseLock).\n // Nothing to release either way.\n return\n }\n releaseLock()\n // A captured write from this page's bootstrap can resurrect the\n // cookie in the narrow gap between the external delete and this\n // handler: writeCookieValue's guard only rejects the write once the\n // lock is torn down, which happens here. Now that the lock is\n // released, no further captured write can re-add the cookie, so clear\n // any entry that was resurrected in that gap. Otherwise an unlock\n // that falls back to a hard reload (when the shell has not yet\n // hydrated) would carry the stale cookie, be served the shell again,\n // and re-enter instant mode with no scope left to release it.\n if (typeof document !== 'undefined') {\n document.cookie = `${NEXT_INSTANT_TEST_COOKIE}=; Path=/; Max-Age=0`\n }\n refreshOnInstantNavigationUnlock()\n return\n }\n }\n })\n}\n\n/**\n * Transitions the cookie from pending to captured-SPA once the prefetch resolves\n * and the navigation is known to be an SPA.\n */\nexport function updateCapturedSPAToTree(\n fromTree: FlightRouterState,\n toTree: FlightRouterState\n): void {\n writeCookieValue([1, `c${Math.random()}`, { from: fromTree, to: toTree }])\n}\n\n/**\n * Returns true if the navigation lock is currently active.\n */\nexport function isNavigationLocked(): boolean {\n if (lockState !== null) {\n return true\n }\n\n // If `lockState` is null, fall back to reading the test cookie\n // synchronously from `document.cookie`. This accounts for a small race\n // between `cookieStore.set(...)` and its corresponding `change` event.\n // During that gap `lockState` is still null even though the cookie\n // indicates a new lock scope is starting.\n if (typeof document === 'undefined') {\n return false\n }\n const allCookies = document.cookie\n if (!allCookies.includes(NEXT_INSTANT_TEST_COOKIE)) {\n // Fast bail-out: in almost every navigation the test cookie is not\n // set at all.\n return false\n }\n const target = NEXT_INSTANT_TEST_COOKIE + '='\n for (const segment of allCookies.split(';')) {\n const trimmed = segment.trim()\n if (\n trimmed.startsWith(target) &&\n parseCookieValue(trimmed.slice(target.length)) === 'pending'\n ) {\n // The cookie was set by an external actor but the change event was not\n // yet dispatched. Acquire the lock synchronously.\n acquireLock()\n return true\n }\n }\n return false\n}\n\n/**\n * Returns the current locked navigation's withheld-data gate — the same\n * immutable promise `beginLockedNavigation` handed that navigation — or null\n * when no lock is held. For router work that spawns a dynamic write without\n * beginning a navigation of its own (refreshes, server actions, server\n * patches): it gates behind the navigation that is current when it spawns, so\n * the next locked navigation (or unlock) releases it.\n */\nexport function getCurrentNavigationGate(): Promise<void> | null {\n return lockState !== null ? lockState.currentNavigation : null\n}\n\n/**\n * Decides whether segment reads during a navigation should be restricted to\n * shell entries (every param substituted with Fallback) rather than matching\n * entries that vary on concrete route params.\n *\n * The testing tools (Navigation Inspector, instant()) simulate what a user\n * would see with a warm cache. When the lock is held, partial prefetching is\n * enabled for the target route, and no whole-route (\"speculative\") prefetch\n * would have been made, only the shell is prefetched — so that's all a\n * navigation should be allowed to match. A speculative prefetch happens for a\n * `<Link prefetch={true}>` or an eagerly-prefetched subtree, in which case the\n * concrete-param entry is genuinely warm and may be matched.\n *\n * Always returns false outside the testing API, via the aliased\n * `navigation-testing-lock.disabled` module.\n */\nexport function shouldRestrictNavigationToShell(\n rootPrefetchHints: number,\n linkFetchStrategy: FetchStrategy\n): boolean {\n return (\n isNavigationLocked() &&\n (rootPrefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0 &&\n !subtreeHasSpeculativePrefetch(linkFetchStrategy, rootPrefetchHints)\n )\n}\n"],"names":["PrefetchHint","NEXT_INSTANT_TEST_COOKIE","refreshOnInstantNavigationUnlock","subtreeHasSpeculativePrefetch","createCacheMap","parseCookieValue","raw","parsed","JSON","parse","Array","isArray","length","rawState","writeDocumentCookie","value","options","document","cookie","stringify","path","domain","writeCookieValue","cookieStore","lockAtCall","lockState","get","then","existing","getPreLockFetch","fetch","beginNavigationLockPrefetch","resolve","promise","Promise","r","prefetch","activePrefetches","add","getNavigationLockSegmentCacheMap","segmentCacheMap","resolveNavigationLockPrefetch","delete","acquireLock","resolveReleased","released","resolveCurrentNavigation","currentNavigation","window","Set","globalFetchOverride","releaseLock","beginLockedNavigation","resetNavigationLockToPending","Math","random","isDevServerRequest","input","url","URL","location","href","origin","pathname","startsWith","init","process","env","__NEXT_DEV_SERVER","preLockFetch","currentLock","startListeningForInstantNavigationCookie","self","__next_instant_test","reload","addEventListener","event","changed","name","state","deleted","updateCapturedSPAToTree","fromTree","toTree","from","to","isNavigationLocked","allCookies","includes","target","segment","split","trimmed","trim","slice","getCurrentNavigationGate","shouldRestrictNavigationToShell","rootPrefetchHints","linkFetchStrategy","SubtreeHasPartialPrefetching"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;CAkBC,GAED,SACEA,YAAY,QAGP,uCAAsC;AAC7C,SAASC,wBAAwB,QAAQ,wBAAuB;AAChE,SAASC,gCAAgC,QAAQ,sBAAqB;AACtE,SAASC,6BAA6B,QAAQ,cAAa;AAE3D,SAASC,cAAc,QAAuB,cAAa;AAK3D,SAASC,iBAAiBC,GAAW;IACnC,IAAIA,QAAQ,IAAI;QACd,OAAO;IACT;IACA,IAAI;QACF,MAAMC,SAASC,KAAKC,KAAK,CAACH;QAC1B,IAAII,MAAMC,OAAO,CAACJ,SAAS;YACzB,IAAIA,OAAOK,MAAM,IAAI,GAAG;gBACtB,MAAMC,WAAWN,MAAM,CAAC,EAAE;gBAC1B,OAAOM,aAAa,OAAO,QAAQ;YACrC;QACF;IACF,EAAE,OAAM,CAAC;IACT,OAAO;AACT;AAEA,SAASC,oBACPC,KAAoB,EACpBC,OAAyD;IAEzD,IAAI,OAAOC,aAAa,aAAa;QACnC;IACF;IACA,IAAIC,SAAS,GAAGjB,yBAAyB,CAAC,EAAEO,KAAKW,SAAS,CAACJ,OAAO,OAAO,EACvEC,QAAQI,IAAI,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B,MAAMF;YAAUG,IAAIF;QAAO;KAAE;AAC3E;AAEA;;CAEC,GACD,OAAO,SAASG;IACd,IAAI7D,cAAc,MAAM;QACtB,OAAO;IACT;IAEA,+DAA+D;IAC/D,uEAAuE;IACvE,uEAAuE;IACvE,mEAAmE;IACnE,0CAA0C;IAC1C,IAAI,OAAOR,aAAa,aAAa;QACnC,OAAO;IACT;IACA,MAAMsE,aAAatE,SAASC,MAAM;IAClC,IAAI,CAACqE,WAAWC,QAAQ,CAACvF,2BAA2B;QAClD,mEAAmE;QACnE,cAAc;QACd,OAAO;IACT;IACA,MAAMwF,SAASxF,2BAA2B;IAC1C,KAAK,MAAMyF,WAAWH,WAAWI,KAAK,CAAC,KAAM;QAC3C,MAAMC,UAAUF,QAAQG,IAAI;QAC5B,IACED,QAAQ5B,UAAU,CAACyB,WACnBpF,iBAAiBuF,QAAQE,KAAK,CAACL,OAAO7E,MAAM,OAAO,WACnD;YACA,uEAAuE;YACvE,kDAAkD;YAClD+B;YACA,OAAO;QACT;IACF;IACA,OAAO;AACT;AAEA;;;;;;;CAOC,GACD,OAAO,SAASoD;IACd,OAAOtE,cAAc,OAAOA,UAAUsB,iBAAiB,GAAG;AAC5D;AAEA;;;;;;;;;;;;;;;CAeC,GACD,OAAO,SAASiD,gCACdC,iBAAyB,EACzBC,iBAAgC;IAEhC,OACEZ,wBACA,AAACW,CAAAA,oBAAoBjG,aAAamG,4BAA4B,AAAD,MAAO,KACpE,CAAChG,8BAA8B+F,mBAAmBD;AAEtD","ignoreList":[0]} |
@@ -6,3 +6,3 @@ import { PrefetchHint } from '../../../shared/lib/app-router-types'; | ||
| import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'; | ||
| import { EntryStatus, readRouteCacheEntry, deprecated_requestOptimisticRouteCacheEntry, resolveStaleAt, writePrerenderResponseIntoCache, processRuntimePrefetchStream, writeDynamicRenderResponseIntoCache } from './cache'; | ||
| import { EntryStatus, segmentCacheMap, readRouteCacheEntry, deprecated_requestOptimisticRouteCacheEntry, resolveStaleAt, writePrerenderResponseIntoCache, processRuntimePrefetchStream, writeDynamicRenderResponseIntoCache } from './cache'; | ||
| import { discoverKnownRoute } from './optimistic-routes'; | ||
@@ -45,5 +45,8 @@ import { createCacheKey } from './cache-key'; | ||
| } | ||
| return navigateImpl(state, url, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType, navigationLock); | ||
| return navigateImpl(state, url, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType, navigationLock, // An unlocked navigation is bound to the shared map. | ||
| segmentCacheMap); | ||
| } | ||
| function navigateImpl(state, url, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType, navigationLock) { | ||
| function navigateImpl(state, url, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType, navigationLock, // The segment cache map this navigation is bound to: a locked navigation's | ||
| // driving-task map, or the shared map. See `segmentCacheMap` in cache.ts. | ||
| map) { | ||
| const now = Date.now(); | ||
@@ -55,3 +58,3 @@ const href = url.href; | ||
| // We have a matching prefetch. | ||
| return navigateUsingPrefetchedRouteTree(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, route, navigationLock); | ||
| return navigateUsingPrefetchedRouteTree(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, route, navigationLock, map); | ||
| } | ||
@@ -74,3 +77,3 @@ // There was no matching route tree in the cache. Let's see if we can | ||
| // We have an optimistic route tree. Proceed with the normal flow. | ||
| return navigateUsingPrefetchedRouteTree(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, optimisticRoute, navigationLock); | ||
| return navigateUsingPrefetchedRouteTree(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, optimisticRoute, navigationLock, map); | ||
| } | ||
@@ -84,3 +87,3 @@ } | ||
| // dynamic request, we should do a runtime prefetch. | ||
| return navigateToUnknownRoute(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, navigationLock).catch(()=>{ | ||
| return navigateToUnknownRoute(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, navigationLock, map).catch(()=>{ | ||
| // If the navigation fails, return the current state | ||
@@ -90,3 +93,5 @@ return state; | ||
| } | ||
| export function navigateToKnownRoute(now, state, url, canonicalUrl, navigationSeed, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, debugInfo, // The route cache entry used for this navigation, if it came from route | ||
| export function navigateToKnownRoute(now, state, url, canonicalUrl, navigationSeed, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, // The segment cache map this navigation is bound to: a locked navigation's | ||
| // driving-task map, or the shared map. See `segmentCacheMap` in cache.ts. | ||
| map, debugInfo, // The route cache entry used for this navigation, if it came from route | ||
| // prediction. Passed through so it can be marked as having a dynamic rewrite | ||
@@ -168,6 +173,6 @@ // if the server returns a different pathname (indicating dynamic rewrite | ||
| const isSamePageNavigation = url.href === currentUrl.href; | ||
| const task = startPPRNavigation(now, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, navigationSeed.routeTree, navigationSeed.metadataVaryPath, freshnessPolicy, navigationSeed.head, navigationSeed.dynamicStaleAt, isSamePageNavigation, accumulation, restrictToShell); | ||
| const task = startPPRNavigation(now, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, navigationSeed.routeTree, navigationSeed.metadataVaryPath, freshnessPolicy, navigationSeed.head, navigationSeed.dynamicStaleAt, isSamePageNavigation, accumulation, map, restrictToShell); | ||
| if (task !== null) { | ||
| if (freshnessPolicy !== FreshnessPolicy.Gesture) { | ||
| spawnDynamicRequests(task, url, nextUrl, freshnessPolicy, accumulation, routeCacheEntry, navigateType, navigationLock, signal); | ||
| spawnDynamicRequests(task, url, nextUrl, freshnessPolicy, accumulation, routeCacheEntry, navigateType, navigationLock, map, signal); | ||
| } | ||
@@ -179,3 +184,3 @@ return completeSoftNavigation(state, url, nextUrl, task.route, task.node, navigationSeed.renderedSearch, canonicalUrl, navigateType, scrollBehavior, accumulation.scrollRef, debugInfo); | ||
| } | ||
| function navigateUsingPrefetchedRouteTree(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, route, navigationLock) { | ||
| function navigateUsingPrefetchedRouteTree(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, route, navigationLock, map) { | ||
| const routeTree = route.tree; | ||
@@ -193,3 +198,3 @@ const canonicalUrl = route.canonicalUrl + url.hash; | ||
| }; | ||
| return navigateToKnownRoute(now, state, url, canonicalUrl, prefetchSeed, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, null, route, // Not an HMR refresh, so there's no request generation to cancel. | ||
| return navigateToKnownRoute(now, state, url, canonicalUrl, prefetchSeed, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, map, null, route, // Not an HMR refresh, so there's no request generation to cancel. | ||
| undefined); | ||
@@ -208,3 +213,3 @@ } | ||
| ]; | ||
| async function navigateToUnknownRoute(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, navigationLock) { | ||
| async function navigateToUnknownRoute(now, state, url, currentUrl, currentRenderedSearch, nextUrl, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, navigationLock, map) { | ||
| // Runs when a navigation happens but there's no cached prefetch we can use. | ||
@@ -274,3 +279,3 @@ // Don't bother to wait for a prefetch response; go straight to a full | ||
| // Shells. | ||
| writePrerenderResponseIntoCache(now, FetchStrategy.PPR, staticStageResponse.t ?? null, buildId, staticStageResponse.r ?? null, staleAt, currentFlightRouterState, renderedSearch, isResponsePartial); | ||
| writePrerenderResponseIntoCache(now, FetchStrategy.PPR, staticStageResponse.t ?? null, buildId, staticStageResponse.r ?? null, staleAt, currentFlightRouterState, renderedSearch, isResponsePartial, map); | ||
| }).catch(()=>{ | ||
@@ -284,3 +289,3 @@ // The static stage processing failed. Not fatal — the navigation | ||
| if (processed !== null) { | ||
| writeDynamicRenderResponseIntoCache(now, FetchStrategy.PPRRuntime, processed.buildId, processed.isResponsePartial, processed.headVaryParams, processed.rootVaryParamsIterable, processed.staleAt, processed.navigationSeed, null); | ||
| writeDynamicRenderResponseIntoCache(now, FetchStrategy.PPRRuntime, processed.buildId, processed.isResponsePartial, processed.headVaryParams, processed.rootVaryParamsIterable, processed.staleAt, processed.navigationSeed, null, map); | ||
| } | ||
@@ -307,3 +312,3 @@ }).catch(()=>{ | ||
| } | ||
| return navigateToKnownRoute(now, state, url, createHrefFromUrl(canonicalUrl), navigationSeed, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, debugInfo, // Unknown route navigations don't use route prediction - the route tree | ||
| return navigateToKnownRoute(now, state, url, createHrefFromUrl(canonicalUrl), navigationSeed, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, navigationLock, map, debugInfo, // Unknown route navigations don't use route prediction - the route tree | ||
| // came directly from the server. If a mismatch occurs during dynamic data | ||
@@ -333,3 +338,3 @@ // fetch, the retry handler will traverse the known route tree to mark the | ||
| renderedSearch: state.renderedSearch, | ||
| focusAndScrollRef: state.focusAndScrollRef, | ||
| scrollRef: state.scrollRef, | ||
| cache: state.cache, | ||
@@ -394,3 +399,3 @@ tree: state.tree, | ||
| } | ||
| activeScrollRef = oldState.focusAndScrollRef.scrollRef; | ||
| activeScrollRef = oldState.scrollRef.scrollRef; | ||
| forceScroll = false; | ||
@@ -403,3 +408,3 @@ } else if (onlyHashChange) { | ||
| // been consumed yet. | ||
| const oldScrollRef = oldState.focusAndScrollRef.scrollRef; | ||
| const oldScrollRef = oldState.scrollRef.scrollRef; | ||
| if (oldScrollRef !== null) { | ||
@@ -426,3 +431,3 @@ oldScrollRef.current = false; | ||
| if (scrollRef !== null) { | ||
| const oldScrollRef = oldState.focusAndScrollRef.scrollRef; | ||
| const oldScrollRef = oldState.scrollRef.scrollRef; | ||
| if (oldScrollRef !== null) { | ||
@@ -442,3 +447,3 @@ oldScrollRef.current = false; | ||
| }, | ||
| focusAndScrollRef: { | ||
| scrollRef: { | ||
| scrollRef: activeScrollRef, | ||
@@ -452,4 +457,4 @@ forceScroll, | ||
| // | ||
| // Refer to `ScrollAndFocusHandler` for details on how this is used. | ||
| scrollBehavior !== ScrollBehavior.NoScroll && url.hash !== '' ? decodeURIComponent(url.hash.slice(1)) : oldState.focusAndScrollRef.hashFragment | ||
| // Refer to `ScrollHandler` for details on how this is used. | ||
| scrollBehavior !== ScrollBehavior.NoScroll && url.hash !== '' ? decodeURIComponent(url.hash.slice(1)) : oldState.scrollRef.hashFragment | ||
| }, | ||
@@ -475,3 +480,3 @@ cache, | ||
| }, | ||
| focusAndScrollRef: state.focusAndScrollRef, | ||
| scrollRef: state.scrollRef, | ||
| cache, | ||
@@ -501,8 +506,8 @@ // Restore provided tree | ||
| // the prefetch as a locked-navigation prefetch. The prefetch's promise | ||
| // resolves once it has spawned every request and all of them have fulfilled, | ||
| // so the navigation below reads present data rather than a still-in-flight | ||
| // entry. | ||
| // resolves when the task completes — after every segment response the task | ||
| // cares about has settled — so the navigation below reads present data | ||
| // rather than a still-in-flight entry. | ||
| const { beginNavigationLockPrefetch } = require('./navigation-testing-lock'); | ||
| const navigationLockPrefetch = beginNavigationLockPrefetch(); | ||
| schedulePrefetchTask(cacheKey, currentFlightRouterState, fetchStrategy, PrefetchPriority.Default, null, navigationLockPrefetch); | ||
| const prefetchTask = schedulePrefetchTask(cacheKey, currentFlightRouterState, fetchStrategy, PrefetchPriority.Default, null, navigationLockPrefetch); | ||
| if (navigationLockPrefetch !== null) { | ||
@@ -512,4 +517,7 @@ await navigationLockPrefetch.promise; | ||
| // Prefetch is complete. Proceed with the normal navigation flow, which | ||
| // will now find the route in the cache. | ||
| const result = await navigateImpl(state, url, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType, navigationLock); | ||
| // will now find the route in the cache. The navigation inherits the map of | ||
| // the prefetch task that drives it: the task was scheduled inside the lock | ||
| // scope, so this is the scope's private map, and the navigation reads only | ||
| // data fetched under the lock. | ||
| const result = await navigateImpl(state, url, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType, navigationLock, prefetchTask.segmentCacheMap); | ||
| // Only transition to captured-SPA once the navigation is known to be an SPA. | ||
@@ -516,0 +524,0 @@ // If the result is an MPA navigation, leave the cookie pending and let the new |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/client/components/segment-cache/navigation.ts"],"sourcesContent":["import type {\n FlightRouterState,\n ScrollRef,\n} from '../../../shared/lib/app-router-types'\nimport type { CacheNode } from '../../../shared/lib/app-router-types'\nimport { PrefetchHint } from '../../../shared/lib/app-router-types'\nimport { fetchServerResponse } from '../router-reducer/fetch-server-response'\nimport {\n startPPRNavigation,\n spawnDynamicRequests,\n FreshnessPolicy,\n beginLockedNavigation,\n type NavigationLock,\n type NavigationRequestAccumulation,\n} from '../router-reducer/ppr-navigations'\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport {\n EntryStatus,\n readRouteCacheEntry,\n deprecated_requestOptimisticRouteCacheEntry,\n resolveStaleAt,\n writePrerenderResponseIntoCache,\n processRuntimePrefetchStream,\n writeDynamicRenderResponseIntoCache,\n type FulfilledRouteCacheEntry,\n} from './cache'\nimport { discoverKnownRoute } from './optimistic-routes'\nimport { createCacheKey, type NormalizedSearch } from './cache-key'\nimport { schedulePrefetchTask } from './scheduler'\nimport { PrefetchPriority, FetchStrategy } from './types'\nimport { getLinkForCurrentNavigation } from '../links'\nimport type { AppRouterState } from '../router-reducer/router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer/router-reducer-types'\nimport { computeChangedPath } from '../router-reducer/compute-changed-path'\nimport { isJavaScriptURLString } from '../../lib/javascript-url'\nimport { UnknownDynamicStaleTime, computeDynamicStaleAt } from './bfcache'\nimport { createLinkPrefetchPartialError } from '../../../shared/lib/instant-messages'\nimport {\n convertServerPatchToFullTree,\n type NavigationSeed,\n} from './decode-server-response'\n\n/**\n * Navigate to a new URL, using the Segment Cache to construct a response.\n *\n * To allow for synchronous navigations whenever possible, this is not an async\n * function. It returns a promise only if there's no matching prefetch in\n * the cache. Otherwise it returns an immediate result and uses Suspense/RSC to\n * stream in any missing data.\n */\nexport function navigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace'\n): AppRouterState | Promise<AppRouterState> {\n let navigationLock: NavigationLock | null = null\n\n // Instant Navigation Testing API: when the lock is active, ensure a\n // prefetch task has been initiated before proceeding with the navigation.\n // This guarantees that segment data requests are at least pending, even\n // for routes that already have a cached route tree. Without this, the\n // shell might be incomplete because some segments were never\n // requested.\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { isNavigationLocked } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n if (isNavigationLocked()) {\n // Signal that a new locked navigation is starting. This force-resolves the\n // previous locked navigation's withheld data (so a reused shared segment\n // no longer carries a pending deferred rsc) and returns this navigation's\n // own withheld-data gate.\n navigationLock = beginLockedNavigation()\n return ensurePrefetchThenNavigate(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n }\n }\n\n return navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n}\n\nfunction navigateImpl(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): AppRouterState | Promise<AppRouterState> {\n const now = Date.now()\n const href = url.href\n\n const cacheKey = createCacheKey(href, nextUrl)\n const route = readRouteCacheEntry(now, cacheKey)\n if (route !== null && route.status === EntryStatus.Fulfilled) {\n // We have a matching prefetch.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n route,\n navigationLock\n )\n }\n\n // There was no matching route tree in the cache. Let's see if we can\n // construct an \"optimistic\" route tree using the deprecated search-params\n // based matching. This is only used when the new optimisticRouting flag is\n // disabled.\n //\n // Do not construct an optimistic route tree if there was a cache hit, but\n // the entry has a rejected status, since it may have been rejected due to a\n // rewrite or redirect based on the search params.\n //\n // TODO: There are multiple reasons a prefetch might be rejected; we should\n // track them explicitly and choose what to do here based on that.\n if (!process.env.__NEXT_OPTIMISTIC_ROUTING) {\n if (route === null || route.status !== EntryStatus.Rejected) {\n const optimisticRoute = deprecated_requestOptimisticRouteCacheEntry(\n now,\n url,\n nextUrl\n )\n if (optimisticRoute !== null) {\n // We have an optimistic route tree. Proceed with the normal flow.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n optimisticRoute,\n navigationLock\n )\n }\n }\n }\n\n // There's no matching prefetch for this route in the cache. We must lazily\n // fetch it from the server before we can perform the navigation.\n //\n // TODO: If this is a gesture navigation, instead of performing a\n // dynamic request, we should do a runtime prefetch.\n return navigateToUnknownRoute(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n ).catch(() => {\n // If the navigation fails, return the current state\n return state\n })\n}\n\nexport function navigateToKnownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n canonicalUrl: string,\n navigationSeed: NavigationSeed,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n nextUrl: string | null,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n debugInfo: Array<unknown> | null,\n // The route cache entry used for this navigation, if it came from route\n // prediction. Passed through so it can be marked as having a dynamic rewrite\n // if the server returns a different pathname (indicating dynamic rewrite\n // behavior).\n //\n // When null, the navigation did not use route prediction - either because\n // the route was already fully cached, or it's a navigation that doesn't\n // involve prediction (refresh, history traversal, server action, etc.).\n // In these cases, if a mismatch occurs, we still mark the route as having a\n // dynamic rewrite by traversing the known route tree (see\n // dispatchRetryDueToTreeMismatch).\n routeCacheEntry: FulfilledRouteCacheEntry | null,\n signal: AbortSignal | undefined\n): AppRouterState {\n // A version of navigate() that accepts the target route tree as an argument\n // rather than reading it from the prefetch cache.\n if (\n process.env.NODE_ENV !== 'production' &&\n process.env.__NEXT_CACHE_COMPONENTS\n ) {\n // Warn when navigating via a `<Link prefetch={true}>` to a route that has\n // not opted into Partial Prefetching. Such a link does a legacy \"full\"\n // prefetch that includes the route's dynamic data, defeating the\n // static/dynamic split that Cache Components provides.\n //\n // This runs at navigation time (rather than prefetch time) so that, in dev\n // where we don't prefetch, the warning only appears when you actually\n // navigate to the route — existing apps with many `prefetch={true}` links\n // aren't flooded with warnings the moment they enable Cache Components.\n //\n // The warning is suppressed if any segment on the target route exports\n // `instant = false`, which is the explicit API for opting a route out of\n // this validation.\n const link = getLinkForCurrentNavigation()\n if (\n link !== null &&\n link.fetchStrategy === FetchStrategy.Full &&\n (navigationSeed.routeTree.prefetchHints &\n (PrefetchHint.SubtreeHasPartialPrefetching |\n PrefetchHint.SubtreeHasInstantFalse)) ===\n 0\n ) {\n const error = createLinkPrefetchPartialError(url.pathname)\n const ownerStack = 'ownerStack' in link ? link.ownerStack : undefined\n if (ownerStack === undefined) {\n console.error(\n '' +\n 'Cannot associate the \"prefetch={true}\" warning with a specific <Link> making it harder to find the cause of the following warning. ' +\n 'This is a bug in Next.js.'\n )\n } else if (ownerStack !== null) {\n // Replace the (useless) stack captured at the throw site — which\n // points into router internals — with the Owner Stack captured when\n // the <Link> rendered. That way the dev overlay associates this\n // warning with the JSX that created the link, not with\n // navigation.ts.\n error.stack = `${error.name}: ${error.message}${ownerStack}`\n }\n console.error(error)\n }\n }\n\n // Instant Navigation Testing API: when the lock is held, restrict segment\n // reads to shell entries if the target route would only have prefetched\n // its shell.\n let restrictToShell = false\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { shouldRestrictNavigationToShell } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const link = getLinkForCurrentNavigation()\n restrictToShell = shouldRestrictNavigationToShell(\n navigationSeed.routeTree.prefetchHints,\n link !== null ? link.fetchStrategy : FetchStrategy.PPR\n )\n }\n\n const accumulation: NavigationRequestAccumulation = {\n separateRefreshUrls: null,\n scrollRef: null,\n }\n // We special case navigations to the exact same URL as the current location.\n // It's a common UI pattern for apps to refresh when you click a link to the\n // current page. So when this happens, we refresh the dynamic data in the page\n // segments.\n //\n // Note that this does not apply if the any part of the hash or search query\n // has changed. This might feel a bit weird but it makes more sense when you\n // consider that the way to trigger this behavior is to click the same link\n // multiple times.\n //\n // TODO: We should probably refresh the *entire* route when this case occurs,\n // not just the page segments. Essentially treating it the same as a refresh()\n // triggered by an action, which is the more explicit way of modeling the UI\n // pattern described above.\n //\n // Also note that this only refreshes the dynamic data, not static/ cached\n // data. If the page segment is fully static and prefetched, the request is\n // skipped. (This is also how refresh() works.)\n const isSamePageNavigation = url.href === currentUrl.href\n const task = startPPRNavigation(\n now,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n navigationSeed.routeTree,\n navigationSeed.metadataVaryPath,\n freshnessPolicy,\n navigationSeed.head,\n navigationSeed.dynamicStaleAt,\n isSamePageNavigation,\n accumulation,\n restrictToShell\n )\n if (task !== null) {\n if (freshnessPolicy !== FreshnessPolicy.Gesture) {\n spawnDynamicRequests(\n task,\n url,\n nextUrl,\n freshnessPolicy,\n accumulation,\n routeCacheEntry,\n navigateType,\n navigationLock,\n signal\n )\n }\n return completeSoftNavigation(\n state,\n url,\n nextUrl,\n task.route,\n task.node,\n navigationSeed.renderedSearch,\n canonicalUrl,\n navigateType,\n scrollBehavior,\n accumulation.scrollRef,\n debugInfo\n )\n }\n // Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.\n return completeHardNavigation(state, url, navigateType)\n}\n\nfunction navigateUsingPrefetchedRouteTree(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n route: FulfilledRouteCacheEntry,\n navigationLock: NavigationLock | null\n): AppRouterState {\n const routeTree = route.tree\n const canonicalUrl = route.canonicalUrl + url.hash\n const renderedSearch = route.renderedSearch\n const prefetchSeed: NavigationSeed = {\n renderedSearch,\n routeTree,\n metadataVaryPath: route.metadata.varyPath as any,\n head: null,\n isHeadPartial: true,\n headVaryParams: null,\n dynamicStaleAt: computeDynamicStaleAt(now, UnknownDynamicStaleTime),\n }\n return navigateToKnownRoute(\n now,\n state,\n url,\n canonicalUrl,\n prefetchSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n null,\n route,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\n// Used to request all the dynamic data for a route, rather than just a subset,\n// e.g. during a refresh or a revalidation. Typically this gets constructed\n// during the normal flow when diffing the route tree, but for an unprefetched\n// navigation, where we don't know the structure of the target route, we use\n// this instead.\nconst DynamicRequestTreeForEntireRoute: FlightRouterState = [\n '',\n {},\n null,\n 'refetch',\n]\n\nasync function navigateToUnknownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): Promise<AppRouterState> {\n // Runs when a navigation happens but there's no cached prefetch we can use.\n // Don't bother to wait for a prefetch response; go straight to a full\n // navigation that contains both static and dynamic data in a single stream.\n // (This is unlike the old navigation implementation, which instead blocks\n // the dynamic request until a prefetch request is received.)\n //\n // To avoid duplication of logic, we're going to pretend that the tree\n // returned by the dynamic request is, in fact, a prefetch tree. Then we can\n // use the same server response to write the actual data into the CacheNode\n // tree. So it's the same flow as the \"happy path\" (prefetch, then\n // navigation), except we use a single server response for both stages.\n\n let dynamicRequestTree: FlightRouterState\n switch (freshnessPolicy) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.HistoryTraversal:\n case FreshnessPolicy.Gesture:\n dynamicRequestTree = currentFlightRouterState\n break\n case FreshnessPolicy.Hydration: // <- shouldn't happen during client nav\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n dynamicRequestTree = DynamicRequestTreeForEntireRoute\n break\n default:\n freshnessPolicy satisfies never\n dynamicRequestTree = currentFlightRouterState\n break\n }\n\n const promiseForDynamicServerResponse = fetchServerResponse(url, {\n flightRouterState: dynamicRequestTree,\n nextUrl,\n })\n const result = await promiseForDynamicServerResponse\n if (typeof result === 'string') {\n // This is an MPA navigation.\n const redirectUrl = new URL(result, location.origin)\n return completeHardNavigation(state, redirectUrl, navigateType)\n }\n\n const {\n transportData,\n canonicalUrl,\n renderedSearch,\n couldBeIntercepted,\n supportsPerSegmentPrefetching,\n dynamicStaleTime,\n staticStageData,\n runtimePrefetchStream,\n responseHeaders,\n debugInfo,\n } = result\n\n // Since the response format of dynamic requests and prefetches is slightly\n // different, we'll need to massage the data a bit. Create FlightRouterState\n // tree that simulates what we'd receive as the result of a prefetch.\n const navigationSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n transportData,\n renderedSearch,\n dynamicStaleTime\n )\n\n // Learn the route pattern so we can predict it for future navigations.\n // hasDynamicRewrite is false because this is a fresh navigation to an\n // unknown route - any rewrite detection happens during the traversal inside\n // discoverKnownRoute. The hasDynamicRewrite param is only set to true when\n // retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).\n const metadataVaryPath = navigationSeed.metadataVaryPath\n if (metadataVaryPath !== null) {\n discoverKnownRoute(\n now,\n url.pathname,\n url.search as NormalizedSearch,\n nextUrl,\n null, // No pending entry\n navigationSeed.routeTree,\n metadataVaryPath,\n couldBeIntercepted,\n // Store a hashless canonical URL: the entry is shared across hashes, and\n // a later same-route hash nav appends `url.hash` to it.\n createHrefFromUrl(canonicalUrl, false),\n supportsPerSegmentPrefetching,\n false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal\n )\n\n if (staticStageData !== null) {\n const { response: staticStageResponse, isResponsePartial } =\n staticStageData\n\n // Write the static stage of the response into the segment cache so that\n // subsequent navigations can serve cached static segments instantly.\n resolveStaleAt(now, staticStageResponse.s)\n .then((staleAt) => {\n const buildId =\n responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n staticStageResponse.b\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the\n // Cached Navigations behavior should work in combination with App\n // Shells.\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.t ?? null,\n buildId,\n staticStageResponse.r ?? null,\n staleAt,\n currentFlightRouterState,\n renderedSearch,\n isResponsePartial\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the navigation\n // completed normally, we just won't write into the cache.\n })\n }\n\n if (runtimePrefetchStream !== null) {\n processRuntimePrefetchStream(\n now,\n runtimePrefetchStream,\n currentFlightRouterState,\n renderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n now,\n FetchStrategy.PPRRuntime,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null\n )\n }\n })\n .catch(() => {\n // The runtime prefetch cache write failed. Not fatal — the\n // navigation completed normally, we just won't cache runtime data.\n })\n }\n }\n\n // In the streaming dev render, this single response's seed content may still\n // be streaming when we build the tree below. An unknown-route navigation\n // places that content inline (it has no prior cache entry, so the server\n // sends a full seed rather than the dynamic-only delta a known route gets),\n // and that inline content is not gated like a known route's deferred RSCs. So\n // React could read a still-pending chunk and flash a Suspense fallback\n // (wanted on a cold cache, but not on a warm one). Wait for the shell to\n // flush (`revealAfter`) first, so the inline seed content is decoded by the\n // time React reads it, the same way the known-route path gates its deferred\n // RSCs. `revealAfter` is null outside the streaming dev render. On a cache\n // miss it resolves early, so the cold-cache fallback is still shown.\n if (result.revealAfter !== null) {\n await result.revealAfter\n }\n\n return navigateToKnownRoute(\n now,\n state,\n url,\n createHrefFromUrl(canonicalUrl),\n navigationSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n debugInfo,\n // Unknown route navigations don't use route prediction - the route tree\n // came directly from the server. If a mismatch occurs during dynamic data\n // fetch, the retry handler will traverse the known route tree to mark the\n // entry as having a dynamic rewrite.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\nexport function completeHardNavigation(\n state: AppRouterState,\n url: URL,\n navigateType: 'push' | 'replace'\n): AppRouterState {\n if (isJavaScriptURLString(url.href)) {\n console.error(\n 'Next.js has blocked a javascript: URL as a security precaution.'\n )\n return state\n }\n const newState: AppRouterState = {\n canonicalUrl:\n url.origin === location.origin ? createHrefFromUrl(url) : url.href,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: true,\n preserveCustomHistoryState: false,\n },\n // TODO: None of the rest of these values are consistent with the incoming\n // navigation. We rely on the fact that AppRouter will suspend and trigger\n // a hard navigation before it accesses any of these values. But instead\n // we should trigger the hard navigation and blocking any subsequent\n // router updates without updating React.\n renderedSearch: state.renderedSearch,\n focusAndScrollRef: state.focusAndScrollRef,\n cache: state.cache,\n tree: state.tree,\n nextUrl: state.nextUrl,\n previousNextUrl: state.previousNextUrl,\n debugInfo: null,\n }\n return newState\n}\n\nexport function completeSoftNavigation(\n oldState: AppRouterState,\n url: URL,\n referringNextUrl: string | null,\n tree: FlightRouterState,\n cache: CacheNode,\n renderedSearch: string,\n canonicalUrl: string,\n navigateType: 'push' | 'replace',\n scrollBehavior: ScrollBehavior,\n scrollRef: ScrollRef | null,\n collectedDebugInfo: Array<unknown> | null\n) {\n // The \"Next-Url\" is a special representation of the URL that Next.js\n // uses to implement interception routes.\n // TODO: Get rid of this extra traversal by computing this during the\n // same traversal that computes the tree itself. We should also figure out\n // what is the minimum information needed for the server to correctly\n // intercept the route.\n const changedPath = computeChangedPath(oldState.tree, tree)\n const nextUrlForNewRoute = changedPath ? changedPath : oldState.nextUrl\n\n // This value is stored on the state as `previousNextUrl`; the naming is\n // confusing. What it represents is the \"Next-Url\" header that was used to\n // fetch the incoming route. It's essentially the refererer URL, but in a\n // Next.js specific format. During refreshes, this is sent back to the server\n // instead of the current route's \"Next-Url\" so that the same interception\n // logic is applied as during the original navigation.\n const previousNextUrl = referringNextUrl\n\n // Check if the only thing that changed was the hash fragment.\n const oldUrl = new URL(oldState.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\n // Determine whether and how the page should scroll after this\n // navigation.\n //\n // By default, we scroll to the segments that were navigated to — i.e.\n // segments in the new part of the route, as opposed to shared segments\n // that were already part of the previous route. All newly navigated\n // segments share a single ScrollRef. When they mount, the first one\n // to mount initiates the scroll. They share a ref so that only one\n // scroll happens per navigation.\n //\n // If a subsequent navigation produces new segments, those supersede\n // any pending scroll from the previous navigation by invalidating its\n // ScrollRef. If a navigation doesn't produce any new segments (e.g.\n // a refresh where the route structure didn't change), any pending\n // scrolls from previous navigations are unaffected.\n //\n // The branches below handle special cases layered on top of this\n // default model.\n let activeScrollRef: ScrollRef | null\n let forceScroll: boolean\n if (scrollBehavior === ScrollBehavior.NoScroll) {\n // The user explicitly opted out of scrolling (e.g. scroll={false}\n // on a Link or router.push).\n //\n // If this navigation created new scroll targets (scrollRef !== null),\n // neutralize them. If it didn't, any prior scroll targets carried\n // forward on the cache nodes via reuseSharedCacheNode remain active.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = oldState.focusAndScrollRef.scrollRef\n forceScroll = false\n } else if (onlyHashChange) {\n // Hash-only navigations should scroll regardless of per-node state.\n // Create a fresh ref so the first segment to scroll consumes it.\n //\n // Invalidate any scroll ref from a prior navigation that hasn't\n // been consumed yet.\n const oldScrollRef = oldState.focusAndScrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n // Also invalidate any per-node refs that were accumulated during\n // this navigation's tree construction — the hash-only ref\n // supersedes them.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = { current: true }\n forceScroll = true\n } else {\n // Default case. Use the accumulated scrollRef (may be null if no\n // new segments were created). The handler checks per-node refs, so\n // unchanged parallel route slots won't scroll.\n activeScrollRef = scrollRef\n\n // If this navigation created new scroll targets, invalidate any\n // pending scroll from a previous navigation.\n if (scrollRef !== null) {\n const oldScrollRef = oldState.focusAndScrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n }\n forceScroll = false\n }\n\n const newState: AppRouterState = {\n canonicalUrl,\n renderedSearch,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: false,\n preserveCustomHistoryState: false,\n },\n focusAndScrollRef: {\n scrollRef: activeScrollRef,\n forceScroll,\n onlyHashChange,\n hashFragment:\n // Remove leading # and decode hash to make non-latin hashes work.\n //\n // Empty hash should trigger default behavior of scrolling layout into\n // view. #top is handled in layout-router.\n //\n // Refer to `ScrollAndFocusHandler` for details on how this is used.\n scrollBehavior !== ScrollBehavior.NoScroll && url.hash !== ''\n ? decodeURIComponent(url.hash.slice(1))\n : oldState.focusAndScrollRef.hashFragment,\n },\n cache,\n tree,\n nextUrl: nextUrlForNewRoute,\n previousNextUrl,\n debugInfo: collectedDebugInfo,\n }\n return newState\n}\n\nexport function completeTraverseNavigation(\n state: AppRouterState,\n url: URL,\n renderedSearch: string,\n cache: CacheNode,\n tree: FlightRouterState,\n nextUrl: string | null\n) {\n return {\n // Set canonical url\n canonicalUrl: createHrefFromUrl(url),\n renderedSearch,\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,\n // Restore provided tree\n tree,\n nextUrl,\n // TODO: We need to restore previousNextUrl, too, which represents the\n // Next-Url that was used to fetch the data. Anywhere we fetch using the\n // canonical URL, there should be a corresponding Next-Url.\n previousNextUrl: null,\n debugInfo: null,\n }\n}\n\n/**\n * Instant Navigation Testing API: ensures a prefetch task has been initiated\n * and completed before proceeding with the navigation. This guarantees that\n * segment data requests are at least pending, even for routes whose route\n * tree is already cached.\n *\n * After the prefetch completes, delegates to the normal navigation flow.\n */\nasync function ensurePrefetchThenNavigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): Promise<AppRouterState> {\n const link = getLinkForCurrentNavigation()\n const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR\n\n const cacheKey = createCacheKey(url.href, nextUrl)\n\n // Create this navigation's \"wait for prefetch to fulfill\" state and schedule\n // the prefetch as a locked-navigation prefetch. The prefetch's promise\n // resolves once it has spawned every request and all of them have fulfilled,\n // so the navigation below reads present data rather than a still-in-flight\n // entry.\n const { beginNavigationLockPrefetch } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const navigationLockPrefetch = beginNavigationLockPrefetch()\n schedulePrefetchTask(\n cacheKey,\n currentFlightRouterState,\n fetchStrategy,\n PrefetchPriority.Default,\n null, // onInvalidate\n navigationLockPrefetch\n )\n if (navigationLockPrefetch !== null) {\n await navigationLockPrefetch.promise\n }\n\n // Prefetch is complete. Proceed with the normal navigation flow, which\n // will now find the route in the cache.\n const result = await navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n\n // Only transition to captured-SPA once the navigation is known to be an SPA.\n // If the result is an MPA navigation, leave the cookie pending and let the new\n // document load transition it to captured-MPA.\n if (!result.pushRef.mpaNavigation) {\n const { updateCapturedSPAToTree } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n updateCapturedSPAToTree(currentFlightRouterState, result.tree)\n }\n\n return result\n}\n"],"names":["PrefetchHint","fetchServerResponse","startPPRNavigation","spawnDynamicRequests","FreshnessPolicy","beginLockedNavigation","createHrefFromUrl","NEXT_NAV_DEPLOYMENT_ID_HEADER","EntryStatus","readRouteCacheEntry","deprecated_requestOptimisticRouteCacheEntry","resolveStaleAt","writePrerenderResponseIntoCache","processRuntimePrefetchStream","writeDynamicRenderResponseIntoCache","discoverKnownRoute","createCacheKey","schedulePrefetchTask","PrefetchPriority","FetchStrategy","getLinkForCurrentNavigation","ScrollBehavior","computeChangedPath","isJavaScriptURLString","UnknownDynamicStaleTime","computeDynamicStaleAt","createLinkPrefetchPartialError","convertServerPatchToFullTree","navigate","state","url","currentUrl","currentRenderedSearch","currentCacheNode","currentFlightRouterState","nextUrl","freshnessPolicy","scrollBehavior","navigateType","navigationLock","process","env","__NEXT_EXPOSE_TESTING_API","isNavigationLocked","require","ensurePrefetchThenNavigate","navigateImpl","now","Date","href","cacheKey","route","status","Fulfilled","navigateUsingPrefetchedRouteTree","__NEXT_OPTIMISTIC_ROUTING","Rejected","optimisticRoute","navigateToUnknownRoute","catch","navigateToKnownRoute","canonicalUrl","navigationSeed","debugInfo","routeCacheEntry","signal","NODE_ENV","__NEXT_CACHE_COMPONENTS","link","fetchStrategy","Full","routeTree","prefetchHints","SubtreeHasPartialPrefetching","SubtreeHasInstantFalse","error","pathname","ownerStack","undefined","console","stack","name","message","restrictToShell","shouldRestrictNavigationToShell","PPR","accumulation","separateRefreshUrls","scrollRef","isSamePageNavigation","task","metadataVaryPath","head","dynamicStaleAt","Gesture","completeSoftNavigation","node","renderedSearch","completeHardNavigation","tree","hash","prefetchSeed","metadata","varyPath","isHeadPartial","headVaryParams","DynamicRequestTreeForEntireRoute","dynamicRequestTree","Default","HistoryTraversal","Hydration","RefreshAll","HMRRefresh","promiseForDynamicServerResponse","flightRouterState","result","redirectUrl","URL","location","origin","transportData","couldBeIntercepted","supportsPerSegmentPrefetching","dynamicStaleTime","staticStageData","runtimePrefetchStream","responseHeaders","search","response","staticStageResponse","isResponsePartial","s","then","staleAt","buildId","get","b","t","r","processed","PPRRuntime","rootVaryParamsIterable","revealAfter","newState","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","cache","previousNextUrl","oldState","referringNextUrl","collectedDebugInfo","changedPath","nextUrlForNewRoute","oldUrl","onlyHashChange","activeScrollRef","forceScroll","NoScroll","current","oldScrollRef","hashFragment","decodeURIComponent","slice","completeTraverseNavigation","beginNavigationLockPrefetch","navigationLockPrefetch","promise","updateCapturedSPAToTree"],"mappings":"AAKA,SAASA,YAAY,QAAQ,uCAAsC;AACnE,SAASC,mBAAmB,QAAQ,0CAAyC;AAC7E,SACEC,kBAAkB,EAClBC,oBAAoB,EACpBC,eAAe,EACfC,qBAAqB,QAGhB,oCAAmC;AAC1C,SAASC,iBAAiB,QAAQ,yCAAwC;AAC1E,SAASC,6BAA6B,QAAQ,yBAAwB;AACtE,SACEC,WAAW,EACXC,mBAAmB,EACnBC,2CAA2C,EAC3CC,cAAc,EACdC,+BAA+B,EAC/BC,4BAA4B,EAC5BC,mCAAmC,QAE9B,UAAS;AAChB,SAASC,kBAAkB,QAAQ,sBAAqB;AACxD,SAASC,cAAc,QAA+B,cAAa;AACnE,SAASC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C7E,uEAAuE;IACvE,6EAA6E;IAC7E,2EAA2E;IAC3E,SAAS;IACT,MAAM,EAAEoI,2BAA2B,EAAE,GACnC3H,QAAQ;IACV,MAAM4H,yBAAyBD;IAC/BtJ,qBACEiC,UACAhB,0BACAmC,eACAnD,iBAAiB0F,OAAO,EACxB,MACA4D;IAEF,IAAIA,2BAA2B,MAAM;QACnC,MAAMA,uBAAuBC,OAAO;IACtC;IAEA,uEAAuE;IACvE,wCAAwC;IACxC,MAAMtD,SAAS,MAAMrE,aACnBjB,OACAC,KACAC,YACAC,uBACAC,kBACAC,0BACAC,SACAC,iBACAC,gBACAC,cACAC;IAGF,6EAA6E;IAC7E,+EAA+E;IAC/E,+CAA+C;IAC/C,IAAI,CAAC4E,OAAO6B,OAAO,CAACE,aAAa,EAAE;QACjC,MAAM,EAAEwB,uBAAuB,EAAE,GAC/B9H,QAAQ;QACV8H,wBAAwBxI,0BAA0BiF,OAAOhB,IAAI;IAC/D;IAEA,OAAOgB;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/client/components/segment-cache/navigation.ts"],"sourcesContent":["import type {\n FlightRouterState,\n ScrollRef,\n} from '../../../shared/lib/app-router-types'\nimport type { CacheNode } from '../../../shared/lib/app-router-types'\nimport { PrefetchHint } from '../../../shared/lib/app-router-types'\nimport { fetchServerResponse } from '../router-reducer/fetch-server-response'\nimport {\n startPPRNavigation,\n spawnDynamicRequests,\n FreshnessPolicy,\n beginLockedNavigation,\n type NavigationLock,\n type NavigationRequestAccumulation,\n} from '../router-reducer/ppr-navigations'\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport {\n EntryStatus,\n segmentCacheMap,\n type SegmentCacheEntry,\n readRouteCacheEntry,\n deprecated_requestOptimisticRouteCacheEntry,\n resolveStaleAt,\n writePrerenderResponseIntoCache,\n processRuntimePrefetchStream,\n writeDynamicRenderResponseIntoCache,\n type FulfilledRouteCacheEntry,\n} from './cache'\nimport { discoverKnownRoute } from './optimistic-routes'\nimport { createCacheKey, type NormalizedSearch } from './cache-key'\nimport type { CacheMap } from './cache-map'\nimport { schedulePrefetchTask } from './scheduler'\nimport { PrefetchPriority, FetchStrategy } from './types'\nimport { getLinkForCurrentNavigation } from '../links'\nimport type { AppRouterState } from '../router-reducer/router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer/router-reducer-types'\nimport { computeChangedPath } from '../router-reducer/compute-changed-path'\nimport { isJavaScriptURLString } from '../../lib/javascript-url'\nimport { UnknownDynamicStaleTime, computeDynamicStaleAt } from './bfcache'\nimport { createLinkPrefetchPartialError } from '../../../shared/lib/instant-messages'\nimport {\n convertServerPatchToFullTree,\n type NavigationSeed,\n} from './decode-server-response'\n\n/**\n * Navigate to a new URL, using the Segment Cache to construct a response.\n *\n * To allow for synchronous navigations whenever possible, this is not an async\n * function. It returns a promise only if there's no matching prefetch in\n * the cache. Otherwise it returns an immediate result and uses Suspense/RSC to\n * stream in any missing data.\n */\nexport function navigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace'\n): AppRouterState | Promise<AppRouterState> {\n let navigationLock: NavigationLock | null = null\n\n // Instant Navigation Testing API: when the lock is active, ensure a\n // prefetch task has been initiated before proceeding with the navigation.\n // This guarantees that segment data requests are at least pending, even\n // for routes that already have a cached route tree. Without this, the\n // shell might be incomplete because some segments were never\n // requested.\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { isNavigationLocked } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n if (isNavigationLocked()) {\n // Signal that a new locked navigation is starting. This force-resolves the\n // previous locked navigation's withheld data (so a reused shared segment\n // no longer carries a pending deferred rsc) and returns this navigation's\n // own withheld-data gate.\n navigationLock = beginLockedNavigation()\n return ensurePrefetchThenNavigate(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n }\n }\n\n return navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n // An unlocked navigation is bound to the shared map.\n segmentCacheMap\n )\n}\n\nfunction navigateImpl(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n // The segment cache map this navigation is bound to: a locked navigation's\n // driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.\n map: CacheMap<SegmentCacheEntry>\n): AppRouterState | Promise<AppRouterState> {\n const now = Date.now()\n const href = url.href\n\n const cacheKey = createCacheKey(href, nextUrl)\n const route = readRouteCacheEntry(now, cacheKey)\n if (route !== null && route.status === EntryStatus.Fulfilled) {\n // We have a matching prefetch.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n route,\n navigationLock,\n map\n )\n }\n\n // There was no matching route tree in the cache. Let's see if we can\n // construct an \"optimistic\" route tree using the deprecated search-params\n // based matching. This is only used when the new optimisticRouting flag is\n // disabled.\n //\n // Do not construct an optimistic route tree if there was a cache hit, but\n // the entry has a rejected status, since it may have been rejected due to a\n // rewrite or redirect based on the search params.\n //\n // TODO: There are multiple reasons a prefetch might be rejected; we should\n // track them explicitly and choose what to do here based on that.\n if (!process.env.__NEXT_OPTIMISTIC_ROUTING) {\n if (route === null || route.status !== EntryStatus.Rejected) {\n const optimisticRoute = deprecated_requestOptimisticRouteCacheEntry(\n now,\n url,\n nextUrl\n )\n if (optimisticRoute !== null) {\n // We have an optimistic route tree. Proceed with the normal flow.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n optimisticRoute,\n navigationLock,\n map\n )\n }\n }\n }\n\n // There's no matching prefetch for this route in the cache. We must lazily\n // fetch it from the server before we can perform the navigation.\n //\n // TODO: If this is a gesture navigation, instead of performing a\n // dynamic request, we should do a runtime prefetch.\n return navigateToUnknownRoute(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n map\n ).catch(() => {\n // If the navigation fails, return the current state\n return state\n })\n}\n\nexport function navigateToKnownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n canonicalUrl: string,\n navigationSeed: NavigationSeed,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n nextUrl: string | null,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n // The segment cache map this navigation is bound to: a locked navigation's\n // driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.\n map: CacheMap<SegmentCacheEntry>,\n debugInfo: Array<unknown> | null,\n // The route cache entry used for this navigation, if it came from route\n // prediction. Passed through so it can be marked as having a dynamic rewrite\n // if the server returns a different pathname (indicating dynamic rewrite\n // behavior).\n //\n // When null, the navigation did not use route prediction - either because\n // the route was already fully cached, or it's a navigation that doesn't\n // involve prediction (refresh, history traversal, server action, etc.).\n // In these cases, if a mismatch occurs, we still mark the route as having a\n // dynamic rewrite by traversing the known route tree (see\n // dispatchRetryDueToTreeMismatch).\n routeCacheEntry: FulfilledRouteCacheEntry | null,\n signal: AbortSignal | undefined\n): AppRouterState {\n // A version of navigate() that accepts the target route tree as an argument\n // rather than reading it from the prefetch cache.\n if (\n process.env.NODE_ENV !== 'production' &&\n process.env.__NEXT_CACHE_COMPONENTS\n ) {\n // Warn when navigating via a `<Link prefetch={true}>` to a route that has\n // not opted into Partial Prefetching. Such a link does a legacy \"full\"\n // prefetch that includes the route's dynamic data, defeating the\n // static/dynamic split that Cache Components provides.\n //\n // This runs at navigation time (rather than prefetch time) so that, in dev\n // where we don't prefetch, the warning only appears when you actually\n // navigate to the route — existing apps with many `prefetch={true}` links\n // aren't flooded with warnings the moment they enable Cache Components.\n //\n // The warning is suppressed if any segment on the target route exports\n // `instant = false`, which is the explicit API for opting a route out of\n // this validation.\n const link = getLinkForCurrentNavigation()\n if (\n link !== null &&\n link.fetchStrategy === FetchStrategy.Full &&\n (navigationSeed.routeTree.prefetchHints &\n (PrefetchHint.SubtreeHasPartialPrefetching |\n PrefetchHint.SubtreeHasInstantFalse)) ===\n 0\n ) {\n const error = createLinkPrefetchPartialError(url.pathname)\n const ownerStack = 'ownerStack' in link ? link.ownerStack : undefined\n if (ownerStack === undefined) {\n console.error(\n '' +\n 'Cannot associate the \"prefetch={true}\" warning with a specific <Link> making it harder to find the cause of the following warning. ' +\n 'This is a bug in Next.js.'\n )\n } else if (ownerStack !== null) {\n // Replace the (useless) stack captured at the throw site — which\n // points into router internals — with the Owner Stack captured when\n // the <Link> rendered. That way the dev overlay associates this\n // warning with the JSX that created the link, not with\n // navigation.ts.\n error.stack = `${error.name}: ${error.message}${ownerStack}`\n }\n console.error(error)\n }\n }\n\n // Instant Navigation Testing API: when the lock is held, restrict segment\n // reads to shell entries if the target route would only have prefetched\n // its shell.\n let restrictToShell = false\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { shouldRestrictNavigationToShell } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const link = getLinkForCurrentNavigation()\n restrictToShell = shouldRestrictNavigationToShell(\n navigationSeed.routeTree.prefetchHints,\n link !== null ? link.fetchStrategy : FetchStrategy.PPR\n )\n }\n\n const accumulation: NavigationRequestAccumulation = {\n separateRefreshUrls: null,\n scrollRef: null,\n }\n // We special case navigations to the exact same URL as the current location.\n // It's a common UI pattern for apps to refresh when you click a link to the\n // current page. So when this happens, we refresh the dynamic data in the page\n // segments.\n //\n // Note that this does not apply if the any part of the hash or search query\n // has changed. This might feel a bit weird but it makes more sense when you\n // consider that the way to trigger this behavior is to click the same link\n // multiple times.\n //\n // TODO: We should probably refresh the *entire* route when this case occurs,\n // not just the page segments. Essentially treating it the same as a refresh()\n // triggered by an action, which is the more explicit way of modeling the UI\n // pattern described above.\n //\n // Also note that this only refreshes the dynamic data, not static/ cached\n // data. If the page segment is fully static and prefetched, the request is\n // skipped. (This is also how refresh() works.)\n const isSamePageNavigation = url.href === currentUrl.href\n const task = startPPRNavigation(\n now,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n navigationSeed.routeTree,\n navigationSeed.metadataVaryPath,\n freshnessPolicy,\n navigationSeed.head,\n navigationSeed.dynamicStaleAt,\n isSamePageNavigation,\n accumulation,\n map,\n restrictToShell\n )\n if (task !== null) {\n if (freshnessPolicy !== FreshnessPolicy.Gesture) {\n spawnDynamicRequests(\n task,\n url,\n nextUrl,\n freshnessPolicy,\n accumulation,\n routeCacheEntry,\n navigateType,\n navigationLock,\n map,\n signal\n )\n }\n return completeSoftNavigation(\n state,\n url,\n nextUrl,\n task.route,\n task.node,\n navigationSeed.renderedSearch,\n canonicalUrl,\n navigateType,\n scrollBehavior,\n accumulation.scrollRef,\n debugInfo\n )\n }\n // Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.\n return completeHardNavigation(state, url, navigateType)\n}\n\nfunction navigateUsingPrefetchedRouteTree(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n route: FulfilledRouteCacheEntry,\n navigationLock: NavigationLock | null,\n map: CacheMap<SegmentCacheEntry>\n): AppRouterState {\n const routeTree = route.tree\n const canonicalUrl = route.canonicalUrl + url.hash\n const renderedSearch = route.renderedSearch\n const prefetchSeed: NavigationSeed = {\n renderedSearch,\n routeTree,\n metadataVaryPath: route.metadata.varyPath as any,\n head: null,\n isHeadPartial: true,\n headVaryParams: null,\n dynamicStaleAt: computeDynamicStaleAt(now, UnknownDynamicStaleTime),\n }\n return navigateToKnownRoute(\n now,\n state,\n url,\n canonicalUrl,\n prefetchSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n map,\n null,\n route,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\n// Used to request all the dynamic data for a route, rather than just a subset,\n// e.g. during a refresh or a revalidation. Typically this gets constructed\n// during the normal flow when diffing the route tree, but for an unprefetched\n// navigation, where we don't know the structure of the target route, we use\n// this instead.\nconst DynamicRequestTreeForEntireRoute: FlightRouterState = [\n '',\n {},\n null,\n 'refetch',\n]\n\nasync function navigateToUnknownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n map: CacheMap<SegmentCacheEntry>\n): Promise<AppRouterState> {\n // Runs when a navigation happens but there's no cached prefetch we can use.\n // Don't bother to wait for a prefetch response; go straight to a full\n // navigation that contains both static and dynamic data in a single stream.\n // (This is unlike the old navigation implementation, which instead blocks\n // the dynamic request until a prefetch request is received.)\n //\n // To avoid duplication of logic, we're going to pretend that the tree\n // returned by the dynamic request is, in fact, a prefetch tree. Then we can\n // use the same server response to write the actual data into the CacheNode\n // tree. So it's the same flow as the \"happy path\" (prefetch, then\n // navigation), except we use a single server response for both stages.\n\n let dynamicRequestTree: FlightRouterState\n switch (freshnessPolicy) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.HistoryTraversal:\n case FreshnessPolicy.Gesture:\n dynamicRequestTree = currentFlightRouterState\n break\n case FreshnessPolicy.Hydration: // <- shouldn't happen during client nav\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n dynamicRequestTree = DynamicRequestTreeForEntireRoute\n break\n default:\n freshnessPolicy satisfies never\n dynamicRequestTree = currentFlightRouterState\n break\n }\n\n const promiseForDynamicServerResponse = fetchServerResponse(url, {\n flightRouterState: dynamicRequestTree,\n nextUrl,\n })\n const result = await promiseForDynamicServerResponse\n if (typeof result === 'string') {\n // This is an MPA navigation.\n const redirectUrl = new URL(result, location.origin)\n return completeHardNavigation(state, redirectUrl, navigateType)\n }\n\n const {\n transportData,\n canonicalUrl,\n renderedSearch,\n couldBeIntercepted,\n supportsPerSegmentPrefetching,\n dynamicStaleTime,\n staticStageData,\n runtimePrefetchStream,\n responseHeaders,\n debugInfo,\n } = result\n\n // Since the response format of dynamic requests and prefetches is slightly\n // different, we'll need to massage the data a bit. Create FlightRouterState\n // tree that simulates what we'd receive as the result of a prefetch.\n const navigationSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n transportData,\n renderedSearch,\n dynamicStaleTime\n )\n\n // Learn the route pattern so we can predict it for future navigations.\n // hasDynamicRewrite is false because this is a fresh navigation to an\n // unknown route - any rewrite detection happens during the traversal inside\n // discoverKnownRoute. The hasDynamicRewrite param is only set to true when\n // retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).\n const metadataVaryPath = navigationSeed.metadataVaryPath\n if (metadataVaryPath !== null) {\n discoverKnownRoute(\n now,\n url.pathname,\n url.search as NormalizedSearch,\n nextUrl,\n null, // No pending entry\n navigationSeed.routeTree,\n metadataVaryPath,\n couldBeIntercepted,\n // Store a hashless canonical URL: the entry is shared across hashes, and\n // a later same-route hash nav appends `url.hash` to it.\n createHrefFromUrl(canonicalUrl, false),\n supportsPerSegmentPrefetching,\n false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal\n )\n\n if (staticStageData !== null) {\n const { response: staticStageResponse, isResponsePartial } =\n staticStageData\n\n // Write the static stage of the response into the segment cache so that\n // subsequent navigations can serve cached static segments instantly.\n resolveStaleAt(now, staticStageResponse.s)\n .then((staleAt) => {\n const buildId =\n responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n staticStageResponse.b\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the\n // Cached Navigations behavior should work in combination with App\n // Shells.\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.t ?? null,\n buildId,\n staticStageResponse.r ?? null,\n staleAt,\n currentFlightRouterState,\n renderedSearch,\n isResponsePartial,\n map\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the navigation\n // completed normally, we just won't write into the cache.\n })\n }\n\n if (runtimePrefetchStream !== null) {\n processRuntimePrefetchStream(\n now,\n runtimePrefetchStream,\n currentFlightRouterState,\n renderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n now,\n FetchStrategy.PPRRuntime,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null,\n map\n )\n }\n })\n .catch(() => {\n // The runtime prefetch cache write failed. Not fatal — the\n // navigation completed normally, we just won't cache runtime data.\n })\n }\n }\n\n // In the streaming dev render, this single response's seed content may still\n // be streaming when we build the tree below. An unknown-route navigation\n // places that content inline (it has no prior cache entry, so the server\n // sends a full seed rather than the dynamic-only delta a known route gets),\n // and that inline content is not gated like a known route's deferred RSCs. So\n // React could read a still-pending chunk and flash a Suspense fallback\n // (wanted on a cold cache, but not on a warm one). Wait for the shell to\n // flush (`revealAfter`) first, so the inline seed content is decoded by the\n // time React reads it, the same way the known-route path gates its deferred\n // RSCs. `revealAfter` is null outside the streaming dev render. On a cache\n // miss it resolves early, so the cold-cache fallback is still shown.\n if (result.revealAfter !== null) {\n await result.revealAfter\n }\n\n return navigateToKnownRoute(\n now,\n state,\n url,\n createHrefFromUrl(canonicalUrl),\n navigationSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n map,\n debugInfo,\n // Unknown route navigations don't use route prediction - the route tree\n // came directly from the server. If a mismatch occurs during dynamic data\n // fetch, the retry handler will traverse the known route tree to mark the\n // entry as having a dynamic rewrite.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\nexport function completeHardNavigation(\n state: AppRouterState,\n url: URL,\n navigateType: 'push' | 'replace'\n): AppRouterState {\n if (isJavaScriptURLString(url.href)) {\n console.error(\n 'Next.js has blocked a javascript: URL as a security precaution.'\n )\n return state\n }\n const newState: AppRouterState = {\n canonicalUrl:\n url.origin === location.origin ? createHrefFromUrl(url) : url.href,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: true,\n preserveCustomHistoryState: false,\n },\n // TODO: None of the rest of these values are consistent with the incoming\n // navigation. We rely on the fact that AppRouter will suspend and trigger\n // a hard navigation before it accesses any of these values. But instead\n // we should trigger the hard navigation and blocking any subsequent\n // router updates without updating React.\n renderedSearch: state.renderedSearch,\n scrollRef: state.scrollRef,\n cache: state.cache,\n tree: state.tree,\n nextUrl: state.nextUrl,\n previousNextUrl: state.previousNextUrl,\n debugInfo: null,\n }\n return newState\n}\n\nexport function completeSoftNavigation(\n oldState: AppRouterState,\n url: URL,\n referringNextUrl: string | null,\n tree: FlightRouterState,\n cache: CacheNode,\n renderedSearch: string,\n canonicalUrl: string,\n navigateType: 'push' | 'replace',\n scrollBehavior: ScrollBehavior,\n scrollRef: ScrollRef | null,\n collectedDebugInfo: Array<unknown> | null\n) {\n // The \"Next-Url\" is a special representation of the URL that Next.js\n // uses to implement interception routes.\n // TODO: Get rid of this extra traversal by computing this during the\n // same traversal that computes the tree itself. We should also figure out\n // what is the minimum information needed for the server to correctly\n // intercept the route.\n const changedPath = computeChangedPath(oldState.tree, tree)\n const nextUrlForNewRoute = changedPath ? changedPath : oldState.nextUrl\n\n // This value is stored on the state as `previousNextUrl`; the naming is\n // confusing. What it represents is the \"Next-Url\" header that was used to\n // fetch the incoming route. It's essentially the refererer URL, but in a\n // Next.js specific format. During refreshes, this is sent back to the server\n // instead of the current route's \"Next-Url\" so that the same interception\n // logic is applied as during the original navigation.\n const previousNextUrl = referringNextUrl\n\n // Check if the only thing that changed was the hash fragment.\n const oldUrl = new URL(oldState.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\n // Determine whether and how the page should scroll after this\n // navigation.\n //\n // By default, we scroll to the segments that were navigated to — i.e.\n // segments in the new part of the route, as opposed to shared segments\n // that were already part of the previous route. All newly navigated\n // segments share a single ScrollRef. When they mount, the first one\n // to mount initiates the scroll. They share a ref so that only one\n // scroll happens per navigation.\n //\n // If a subsequent navigation produces new segments, those supersede\n // any pending scroll from the previous navigation by invalidating its\n // ScrollRef. If a navigation doesn't produce any new segments (e.g.\n // a refresh where the route structure didn't change), any pending\n // scrolls from previous navigations are unaffected.\n //\n // The branches below handle special cases layered on top of this\n // default model.\n let activeScrollRef: ScrollRef | null\n let forceScroll: boolean\n if (scrollBehavior === ScrollBehavior.NoScroll) {\n // The user explicitly opted out of scrolling (e.g. scroll={false}\n // on a Link or router.push).\n //\n // If this navigation created new scroll targets (scrollRef !== null),\n // neutralize them. If it didn't, any prior scroll targets carried\n // forward on the cache nodes via reuseSharedCacheNode remain active.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = oldState.scrollRef.scrollRef\n forceScroll = false\n } else if (onlyHashChange) {\n // Hash-only navigations should scroll regardless of per-node state.\n // Create a fresh ref so the first segment to scroll consumes it.\n //\n // Invalidate any scroll ref from a prior navigation that hasn't\n // been consumed yet.\n const oldScrollRef = oldState.scrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n // Also invalidate any per-node refs that were accumulated during\n // this navigation's tree construction — the hash-only ref\n // supersedes them.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = { current: true }\n forceScroll = true\n } else {\n // Default case. Use the accumulated scrollRef (may be null if no\n // new segments were created). The handler checks per-node refs, so\n // unchanged parallel route slots won't scroll.\n activeScrollRef = scrollRef\n\n // If this navigation created new scroll targets, invalidate any\n // pending scroll from a previous navigation.\n if (scrollRef !== null) {\n const oldScrollRef = oldState.scrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n }\n forceScroll = false\n }\n\n const newState: AppRouterState = {\n canonicalUrl,\n renderedSearch,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: false,\n preserveCustomHistoryState: false,\n },\n scrollRef: {\n scrollRef: activeScrollRef,\n forceScroll,\n onlyHashChange,\n hashFragment:\n // Remove leading # and decode hash to make non-latin hashes work.\n //\n // Empty hash should trigger default behavior of scrolling layout into\n // view. #top is handled in layout-router.\n //\n // Refer to `ScrollHandler` for details on how this is used.\n scrollBehavior !== ScrollBehavior.NoScroll && url.hash !== ''\n ? decodeURIComponent(url.hash.slice(1))\n : oldState.scrollRef.hashFragment,\n },\n cache,\n tree,\n nextUrl: nextUrlForNewRoute,\n previousNextUrl,\n debugInfo: collectedDebugInfo,\n }\n return newState\n}\n\nexport function completeTraverseNavigation(\n state: AppRouterState,\n url: URL,\n renderedSearch: string,\n cache: CacheNode,\n tree: FlightRouterState,\n nextUrl: string | null\n) {\n return {\n // Set canonical url\n canonicalUrl: createHrefFromUrl(url),\n renderedSearch,\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 scrollRef: state.scrollRef,\n cache,\n // Restore provided tree\n tree,\n nextUrl,\n // TODO: We need to restore previousNextUrl, too, which represents the\n // Next-Url that was used to fetch the data. Anywhere we fetch using the\n // canonical URL, there should be a corresponding Next-Url.\n previousNextUrl: null,\n debugInfo: null,\n }\n}\n\n/**\n * Instant Navigation Testing API: ensures a prefetch task has been initiated\n * and completed before proceeding with the navigation. This guarantees that\n * segment data requests are at least pending, even for routes whose route\n * tree is already cached.\n *\n * After the prefetch completes, delegates to the normal navigation flow.\n */\nasync function ensurePrefetchThenNavigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): Promise<AppRouterState> {\n const link = getLinkForCurrentNavigation()\n const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR\n\n const cacheKey = createCacheKey(url.href, nextUrl)\n\n // Create this navigation's \"wait for prefetch to fulfill\" state and schedule\n // the prefetch as a locked-navigation prefetch. The prefetch's promise\n // resolves when the task completes — after every segment response the task\n // cares about has settled — so the navigation below reads present data\n // rather than a still-in-flight entry.\n const { beginNavigationLockPrefetch } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const navigationLockPrefetch = beginNavigationLockPrefetch()\n const prefetchTask = schedulePrefetchTask(\n cacheKey,\n currentFlightRouterState,\n fetchStrategy,\n PrefetchPriority.Default,\n null, // onInvalidate\n navigationLockPrefetch\n )\n if (navigationLockPrefetch !== null) {\n await navigationLockPrefetch.promise\n }\n\n // Prefetch is complete. Proceed with the normal navigation flow, which\n // will now find the route in the cache. The navigation inherits the map of\n // the prefetch task that drives it: the task was scheduled inside the lock\n // scope, so this is the scope's private map, and the navigation reads only\n // data fetched under the lock.\n const result = await navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n prefetchTask.segmentCacheMap\n )\n\n // Only transition to captured-SPA once the navigation is known to be an SPA.\n // If the result is an MPA navigation, leave the cookie pending and let the new\n // document load transition it to captured-MPA.\n if (!result.pushRef.mpaNavigation) {\n const { updateCapturedSPAToTree } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n updateCapturedSPAToTree(currentFlightRouterState, result.tree)\n }\n\n return result\n}\n"],"names":["PrefetchHint","fetchServerResponse","startPPRNavigation","spawnDynamicRequests","FreshnessPolicy","beginLockedNavigation","createHrefFromUrl","NEXT_NAV_DEPLOYMENT_ID_HEADER","EntryStatus","segmentCacheMap","readRouteCacheEntry","deprecated_requestOptimisticRouteCacheEntry","resolveStaleAt","writePrerenderResponseIntoCache","processRuntimePrefetchStream","writeDynamicRenderResponseIntoCache","discoverKnownRoute","createCacheKey","schedulePrefetchTask","PrefetchPriority","FetchStrategy","getLinkForCurrentNavigation","ScrollBehavior","computeChangedPath","isJavaScriptURLString","UnknownDynamicStaleTime","computeDynamicStaleAt","createLinkPrefetchPartialError","convertServerPatchToFullTree","navigate","state","url","currentUrl","currentRenderedSearch","currentCacheNode","currentFlightRouterState","nextUrl","freshnessPolicy","scrollBehavior","navigateType","navigationLock","process","env","__NEXT_EXPOSE_TESTING_API","isNavigationLocked","require","ensurePrefetchThenNavigate","navigateImpl","map","now","Date","href","cacheKey","route","status","Fulfilled","navigateUsingPrefetchedRouteTree","__NEXT_OPTIMISTIC_ROUTING","Rejected","optimisticRoute","navigateToUnknownRoute","catch","navigateToKnownRoute","canonicalUrl","navigationSeed","debugInfo","routeCacheEntry","signal","NODE_ENV","__NEXT_CACHE_COMPONENTS","link","fetchStrategy","Full","routeTree","prefetchHints","SubtreeHasPartialPrefetching","SubtreeHasInstantFalse","error","pathname","ownerStack","undefined","console","stack","name","message","restrictToShell","shouldRestrictNavigationToShell","PPR","accumulation","separateRefreshUrls","scrollRef","isSamePageNavigation","task","metadataVaryPath","head","dynamicStaleAt","Gesture","completeSoftNavigation","node","renderedSearch","completeHardNavigation","tree","hash","prefetchSeed","metadata","varyPath","isHeadPartial","headVaryParams","DynamicRequestTreeForEntireRoute","dynamicRequestTree","Default","HistoryTraversal","Hydration","RefreshAll","HMRRefresh","promiseForDynamicServerResponse","flightRouterState","result","redirectUrl","URL","location","origin","transportData","couldBeIntercepted","supportsPerSegmentPrefetching","dynamicStaleTime","staticStageData","runtimePrefetchStream","responseHeaders","search","response","staticStageResponse","isResponsePartial","s","then","staleAt","buildId","get","b","t","r","processed","PPRRuntime","rootVaryParamsIterable","revealAfter","newState","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","cache","previousNextUrl","oldState","referringNextUrl","collectedDebugInfo","changedPath","nextUrlForNewRoute","oldUrl","onlyHashChange","activeScrollRef","forceScroll","NoScroll","current","oldScrollRef","hashFragment","decodeURIComponent","slice","completeTraverseNavigation","beginNavigationLockPrefetch","navigationLockPrefetch","prefetchTask","promise","updateCapturedSPAToTree"],"mappings":"AAKA,SAASA,YAAY,QAAQ,uCAAsC;AACnE,SAASC,mBAAmB,QAAQ,0CAAyC;AAC7E,SACEC,kBAAkB,EAClBC,oBAAoB,EACpBC,eAAe,EACfC,qBAAqB,QAGhB,oCAAmC;AAC1C,SAASC,iBAAiB,QAAQ,yCAAwC;AAC1E,SAASC,6BAA6B,QAAQ,yBAAwB;AACtE,SACEC,WAAW,EACXC,eAAe,EAEfC,mBAAmB,EACnBC,2CAA2C,EAC3CC,cAAc,EAC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ACD,eAAenB,2BACbhB,KAAqB,EACrBC,GAAQ,EACRC,UAAe,EACfC,qBAA6B,EAC7BC,gBAAkC,EAClCC,wBAA2C,EAC3CC,OAAsB,EACtBC,eAAgC,EAChCC,cAA8B,EAC9BC,YAAgC,EAChCC,cAAqC;IAErC,MAAM8B,OAAOjD;IACb,MAAMkD,gBAAgBD,SAAS,OAAOA,KAAKC,aAAa,GAAGnD,cAAcmE,GAAG;IAE5E,MAAMnC,WAAWnC,eAAec,IAAIoB,IAAI,EAAEf;IAE1C,6EAA6E;IAC7E,uEAAuE;IACvE,2EAA2E;IAC3E,uEAAuE;IACvE,uCAAuC;IACvC,MAAM,EAAEoI,2BAA2B,EAAE,GACnC3H,QAAQ;IACV,MAAM4H,yBAAyBD;IAC/B,MAAME,eAAexJ,qBACnBkC,UACAjB,0BACAoC,eACApD,iBAAiB2F,OAAO,EACxB,MACA2D;IAEF,IAAIA,2BAA2B,MAAM;QACnC,MAAMA,uBAAuBE,OAAO;IACtC;IAEA,uEAAuE;IACvE,2EAA2E;IAC3E,2EAA2E;IAC3E,2EAA2E;IAC3E,+BAA+B;IAC/B,MAAMtD,SAAS,MAAMtE,aACnBjB,OACAC,KACAC,YACAC,uBACAC,kBACAC,0BACAC,SACAC,iBACAC,gBACAC,cACAC,gBACAkI,aAAajK,eAAe;IAG9B,6EAA6E;IAC7E,+EAA+E;IAC/E,+CAA+C;IAC/C,IAAI,CAAC4G,OAAO6B,OAAO,CAACE,aAAa,EAAE;QACjC,MAAM,EAAEwB,uBAAuB,EAAE,GAC/B/H,QAAQ;QACV+H,wBAAwBzI,0BAA0BkF,OAAOhB,IAAI;IAC/D;IAEA,OAAOgB;AACT","ignoreList":[0]} |
@@ -28,3 +28,3 @@ /* global location */ // imports polyfill from `@next/polyfill-module` after build. | ||
| import { isNextRouterError } from './components/is-next-router-error'; | ||
| export const version = "16.3.1-canary.10"; | ||
| export const version = "16.3.1-canary.11"; | ||
| export let router; | ||
@@ -31,0 +31,0 @@ export const emitter = mitt(); |
@@ -349,3 +349,2 @@ import { createStaticWorker } from '../build'; | ||
| images: nextConfig.images, | ||
| htmlLimitedBots: nextConfig.htmlLimitedBots.source, | ||
| experimental: { | ||
@@ -352,0 +351,0 @@ clientTraceMetadata: nextConfig.experimental.clientTraceMetadata, |
@@ -20,3 +20,3 @@ import { readFileSync, writeFileSync } from 'fs'; | ||
| const data = await res.json(); | ||
| const versionData = data.versions["16.3.1-canary.10"]; | ||
| const versionData = data.versions["16.3.1-canary.11"]; | ||
| return { | ||
@@ -54,3 +54,3 @@ os: versionData.os, | ||
| lockfileParsed.dependencies[pkg] = { | ||
| version: "16.3.1-canary.10", | ||
| version: "16.3.1-canary.11", | ||
| resolved: pkgData.tarball, | ||
@@ -63,3 +63,3 @@ integrity: pkgData.integrity, | ||
| lockfileParsed.packages[pkg] = { | ||
| version: "16.3.1-canary.10", | ||
| version: "16.3.1-canary.11", | ||
| resolved: pkgData.tarball, | ||
@@ -66,0 +66,0 @@ integrity: pkgData.integrity, |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/app-render/types.ts"],"sourcesContent":["import type { LoadComponentsReturnType } from '../load-components'\nimport type { ServerRuntime, SizeLimit } from '../../types'\nimport type {\n ExperimentalConfig,\n NextConfigComplete,\n PrefetchInliningConfig,\n ValidationLevel,\n} from '../../server/config-shared'\nimport type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { AppPageModule } from '../route-modules/app-page/module'\nimport type { DeepReadonly } from '../../shared/lib/deep-readonly'\nimport type { ImageConfigComplete } from '../../shared/lib/image-config'\nimport type { __ApiPreviewProps } from '../api-utils'\n\nimport s from 'next/dist/compiled/superstruct'\nimport type { RequestLifecycleOpts } from '../base-server'\nimport type { InstrumentationOnRequestError } from '../instrumentation/types'\nimport type { NextRequestHint } from '../web/adapter'\nimport type { BaseNextRequest } from '../base-http'\nimport type { IncomingMessage } from 'http'\nimport type { RenderResumeDataCache } from '../resume-data-cache/resume-data-cache'\nimport type { ServerCacheStatus } from '../../next-devtools/dev-overlay/cache-indicator'\nimport type { PrefetchHints } from '../../shared/lib/app-router-types'\nimport type { AnyStream } from './stream-ops'\n\nconst dynamicParamTypesSchema = s.enums([\n 'c',\n 'ci(..)(..)',\n 'ci(.)',\n 'ci(..)',\n 'ci(...)',\n 'oc',\n 'd',\n 'di(..)(..)',\n 'di(.)',\n 'di(..)',\n 'di(...)',\n])\n\nconst segmentSchema = s.union([\n s.string(),\n\n s.tuple([\n // Param name\n s.string(),\n // Param cache key (almost the same as the value, but arrays are\n // concatenated into strings)\n // TODO: We should change this to just be the value. Currently we convert\n // it back to a value when passing to useParams. It only needs to be\n // a string when converted to a a cache key, but that doesn't mean we\n // need to store it as that representation.\n s.string(),\n // Dynamic param type\n dynamicParamTypesSchema,\n // Static siblings at the same URL level. Used by the client router to\n // determine if a prefetch can be reused when navigating to a static\n // sibling of a dynamic route. null means siblings are unknown.\n s.nullable(s.array(s.string())),\n ]),\n])\n\n// unfortunately the tuple is not understood well by Describe so we have to\n// use any here. This does not have any impact on the runtime type since the validation\n// does work correctly.\nexport const flightRouterStateSchema: s.Describe<any> = s.tuple([\n segmentSchema,\n s.record(\n s.string(),\n s.lazy(() => flightRouterStateSchema)\n ),\n s.optional(s.nullable(s.tuple([s.string(), s.string()]))),\n s.optional(\n s.nullable(\n s.union([\n s.literal('refetch'),\n s.literal('inside-shared-layout'),\n s.literal('metadata-only'),\n ])\n )\n ),\n s.optional(s.number()),\n])\n\nexport type ServerOnInstrumentationRequestError = (\n error: unknown,\n // The request could be middleware, node server or web server request,\n // we normalized them into an aligned format to `onRequestError` API later.\n request: NextRequestHint | BaseNextRequest | IncomingMessage,\n errorContext: Parameters<InstrumentationOnRequestError>[2],\n silenceLog: boolean\n) => void | Promise<void>\n\nexport interface RenderOptsPartial {\n dir?: string\n previewProps: __ApiPreviewProps | undefined\n err?: Error | null\n basePath: string\n cacheComponents: boolean\n partialPrefetching?: NextConfigComplete['partialPrefetching']\n validationLevel: ValidationLevel\n trailingSlash: boolean\n images: ImageConfigComplete\n supportsDynamicResponse: boolean\n runtime?: ServerRuntime\n serverComponents?: boolean\n enableTainting?: boolean\n assetPrefix?: string\n crossOrigin?: '' | 'anonymous' | 'use-credentials' | undefined\n nextFontManifest?: DeepReadonly<NextFontManifest>\n botType?: 'dom' | 'html' | undefined\n serveStreamingMetadata?: boolean\n incrementalCache?: import('../lib/incremental-cache').IncrementalCache\n cacheLifeProfiles: import('../config-shared').ResolvedCacheLifeProfiles\n staticPageGenerationTimeout: number\n isOnDemandRevalidate?: boolean\n isPossibleServerAction?: boolean\n setCacheStatus?: (status: ServerCacheStatus, htmlRequestId: string) => void\n setIsrStatus?: (key: string, value: boolean | undefined) => void\n setReactDebugChannel?: (\n debugChannel: { readable: AnyStream },\n htmlRequestId: string,\n requestId: string\n ) => void\n sendErrorsToBrowser?: (\n errorsRscStream: AnyStream,\n htmlRequestId: string\n ) => void\n isBuildTimePrerendering?: boolean\n nextConfigOutput?: 'standalone' | 'export'\n onInstrumentationRequestError?: ServerOnInstrumentationRequestError\n isDraftMode?: boolean\n onUpdateCookies?: (cookies: string[]) => void\n loadConfig?: (\n phase: string,\n dir: string,\n customConfig?: object | null,\n rawConfig?: boolean,\n silent?: boolean\n ) => Promise<NextConfigComplete>\n serverActions?: {\n bodySizeLimit?: SizeLimit\n allowedOrigins?: string[]\n }\n logServerFunctions?: boolean\n params?: ParsedUrlQuery\n isPrefetch?: boolean\n htmlLimitedBots: string | undefined\n experimental: {\n /**\n * When true, it indicates that the current page supports partial\n * prerendering.\n */\n isRoutePPREnabled?: boolean\n expireTime: number | undefined\n staleTimes: ExperimentalConfig['staleTimes'] | undefined\n clientTraceMetadata: string[] | undefined\n\n /**\n * The origins that are allowed to write the rewritten headers when\n * performing a non-relative rewrite. When undefined, no non-relative\n * rewrites will get the rewrite headers.\n */\n clientParamParsingOrigins: string[] | undefined\n dynamicOnHover: boolean\n optimisticRouting: boolean\n inlineCss: boolean\n prefetchInlining: PrefetchInliningConfig\n authInterrupts: boolean\n serverComponentsHmrCancellation?: boolean\n useCacheTimeout: number\n cachedNavigations: boolean\n\n /**\n * The maximum size (in bytes) of the postponed state body for PPR resume\n * requests. Used to calculate decompression limits (5x this value).\n */\n maxPostponedStateSizeBytes: number | undefined\n\n /**\n * Whether the Instant Navigation Testing API is exposed (dev mode or the\n * `exposeTestingApiInProductionBuild` flag). When true, the prerendered\n * shell and dynamic renders embed a cookie-guarded bootstrap script that\n * drives instant navigation tests.\n */\n exposeTestingApi: boolean\n }\n postponed?: string\n\n /**\n * A prefilled resume data cache. This was either generated for this page\n * during dev warmup, or when a page with defined params was previously\n * prerendered, and now its matching optional fallback shell is prerendered.\n */\n renderResumeDataCache?: RenderResumeDataCache\n\n /**\n * When true, the page will be rendered using the static rendering to detect\n * any dynamic API's that would have stopped the page from being fully\n * statically generated.\n */\n isDebugDynamicAccesses?: boolean\n\n /**\n /**\n * The maximum length of the headers that are emitted by React and added to\n * the response.\n */\n reactMaxHeadersLength: number | undefined\n\n /**\n * Per-route prefetch hints from prefetch-hints.json.\n * Loaded at server startup from the build output.\n */\n prefetchHints?: Record<string, PrefetchHints>\n\n /**\n * When true, the page is prerendered as a fallback shell, while allowing any\n * dynamic accesses to result in an empty shell. This is the case when there\n * are also routes prerendered with a more complete set of params.\n * Prerendering those routes would catch any invalid dynamic accesses.\n */\n allowEmptyStaticShell?: boolean\n\n /**\n * When true, attempt to run build-time instant validation for this prerender.\n * Only the first prerender per page sets this, since validation uses\n * instant.unstable_samples and is independent of actual route params.\n */\n runInstantValidation?: boolean\n\n /**\n * When true, a fallback shell produced for this render could later be\n * upgraded to a concrete version (at least one of its fallback params is a\n * candidate enumerated by `generateStaticParams`). Only such shells are\n * flagged `isUpgradeableISRFallback` so the client retries the prefetch; a route that\n * can never upgrade (no `generateStaticParams`) is left unflagged.\n */\n isFallbackUpgradeable?: boolean\n}\n\nexport type RenderOpts = LoadComponentsReturnType<AppPageModule> &\n RenderOptsPartial &\n RequestLifecycleOpts\n\nexport type PreloadCallbacks = (() => void)[]\n"],"names":["s","dynamicParamTypesSchema","enums","segmentSchema","union","string","tuple","nullable","array","flightRouterStateSchema","record","lazy","optional","literal","number"],"mappings":"AAeA,OAAOA,OAAO,iCAAgC;AAW9C,MAAMC,0BAA0BD,EAAEE,KAAK,CAAC;IACtC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,MAAMC,gBAAgBH,EAAEI,KAAK,CAAC;IAC5BJ,EAAEK,MAAM;IAERL,EAAEM,KAAK,CAAC;QACN,aAAa;QACbN,EAAEK,MAAM;QACR,gEAAgE;QAChE,6BAA6B;QAC7B,yEAAyE;QACzE,oEAAoE;QACpE,qEAAqE;QACrE,2CAA2C;QAC3CL,EAAEK,MAAM;QACR,qBAAqB;QACrBJ;QACA,sEAAsE;QACtE,oEAAoE;QACpE,+DAA+D;QAC/DD,EAAEO,QAAQ,CAACP,EAAEQ,KAAK,CAACR,EAAEK,MAAM;KAC5B;CACF;AAED,2EAA2E;AAC3E,uFAAuF;AACvF,uBAAuB;AACvB,OAAO,MAAMI,0BAA2CT,EAAEM,KAAK,CAAC;IAC9DH;IACAH,EAAEU,MAAM,CACNV,EAAEK,MAAM,IACRL,EAAEW,IAAI,CAAC,IAAMF;IAEfT,EAAEY,QAAQ,CAACZ,EAAEO,QAAQ,CAACP,EAAEM,KAAK,CAAC;QAACN,EAAEK,MAAM;QAAIL,EAAEK,MAAM;KAAG;IACtDL,EAAEY,QAAQ,CACRZ,EAAEO,QAAQ,CACRP,EAAEI,KAAK,CAAC;QACNJ,EAAEa,OAAO,CAAC;QACVb,EAAEa,OAAO,CAAC;QACVb,EAAEa,OAAO,CAAC;KACX;IAGLb,EAAEY,QAAQ,CAACZ,EAAEc,MAAM;CACpB,EAAC","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/app-render/types.ts"],"sourcesContent":["import type { LoadComponentsReturnType } from '../load-components'\nimport type { ServerRuntime, SizeLimit } from '../../types'\nimport type {\n ExperimentalConfig,\n NextConfigComplete,\n PrefetchInliningConfig,\n ValidationLevel,\n} from '../../server/config-shared'\nimport type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { AppPageModule } from '../route-modules/app-page/module'\nimport type { DeepReadonly } from '../../shared/lib/deep-readonly'\nimport type { ImageConfigComplete } from '../../shared/lib/image-config'\nimport type { __ApiPreviewProps } from '../api-utils'\n\nimport s from 'next/dist/compiled/superstruct'\nimport type { RequestLifecycleOpts } from '../base-server'\nimport type { InstrumentationOnRequestError } from '../instrumentation/types'\nimport type { NextRequestHint } from '../web/adapter'\nimport type { BaseNextRequest } from '../base-http'\nimport type { IncomingMessage } from 'http'\nimport type { RenderResumeDataCache } from '../resume-data-cache/resume-data-cache'\nimport type { ServerCacheStatus } from '../../next-devtools/dev-overlay/cache-indicator'\nimport type { PrefetchHints } from '../../shared/lib/app-router-types'\nimport type { AnyStream } from './stream-ops'\n\nconst dynamicParamTypesSchema = s.enums([\n 'c',\n 'ci(..)(..)',\n 'ci(.)',\n 'ci(..)',\n 'ci(...)',\n 'oc',\n 'd',\n 'di(..)(..)',\n 'di(.)',\n 'di(..)',\n 'di(...)',\n])\n\nconst segmentSchema = s.union([\n s.string(),\n\n s.tuple([\n // Param name\n s.string(),\n // Param cache key (almost the same as the value, but arrays are\n // concatenated into strings)\n // TODO: We should change this to just be the value. Currently we convert\n // it back to a value when passing to useParams. It only needs to be\n // a string when converted to a a cache key, but that doesn't mean we\n // need to store it as that representation.\n s.string(),\n // Dynamic param type\n dynamicParamTypesSchema,\n // Static siblings at the same URL level. Used by the client router to\n // determine if a prefetch can be reused when navigating to a static\n // sibling of a dynamic route. null means siblings are unknown.\n s.nullable(s.array(s.string())),\n ]),\n])\n\n// unfortunately the tuple is not understood well by Describe so we have to\n// use any here. This does not have any impact on the runtime type since the validation\n// does work correctly.\nexport const flightRouterStateSchema: s.Describe<any> = s.tuple([\n segmentSchema,\n s.record(\n s.string(),\n s.lazy(() => flightRouterStateSchema)\n ),\n s.optional(s.nullable(s.tuple([s.string(), s.string()]))),\n s.optional(\n s.nullable(\n s.union([\n s.literal('refetch'),\n s.literal('inside-shared-layout'),\n s.literal('metadata-only'),\n ])\n )\n ),\n s.optional(s.number()),\n])\n\nexport type ServerOnInstrumentationRequestError = (\n error: unknown,\n // The request could be middleware, node server or web server request,\n // we normalized them into an aligned format to `onRequestError` API later.\n request: NextRequestHint | BaseNextRequest | IncomingMessage,\n errorContext: Parameters<InstrumentationOnRequestError>[2],\n silenceLog: boolean\n) => void | Promise<void>\n\nexport interface RenderOptsPartial {\n dir?: string\n previewProps: __ApiPreviewProps | undefined\n err?: Error | null\n basePath: string\n cacheComponents: boolean\n partialPrefetching?: NextConfigComplete['partialPrefetching']\n validationLevel: ValidationLevel\n trailingSlash: boolean\n images: ImageConfigComplete\n supportsDynamicResponse: boolean\n runtime?: ServerRuntime\n serverComponents?: boolean\n enableTainting?: boolean\n assetPrefix?: string\n crossOrigin?: '' | 'anonymous' | 'use-credentials' | undefined\n nextFontManifest?: DeepReadonly<NextFontManifest>\n botType?: 'dom' | 'html' | undefined\n serveStreamingMetadata?: boolean\n incrementalCache?: import('../lib/incremental-cache').IncrementalCache\n cacheLifeProfiles: import('../config-shared').ResolvedCacheLifeProfiles\n staticPageGenerationTimeout: number\n isOnDemandRevalidate?: boolean\n isPossibleServerAction?: boolean\n setCacheStatus?: (status: ServerCacheStatus, htmlRequestId: string) => void\n setIsrStatus?: (key: string, value: boolean | undefined) => void\n setReactDebugChannel?: (\n debugChannel: { readable: AnyStream },\n htmlRequestId: string,\n requestId: string\n ) => void\n sendErrorsToBrowser?: (\n errorsRscStream: AnyStream,\n htmlRequestId: string\n ) => void\n isBuildTimePrerendering?: boolean\n nextConfigOutput?: 'standalone' | 'export'\n onInstrumentationRequestError?: ServerOnInstrumentationRequestError\n isDraftMode?: boolean\n onUpdateCookies?: (cookies: string[]) => void\n loadConfig?: (\n phase: string,\n dir: string,\n customConfig?: object | null,\n rawConfig?: boolean,\n silent?: boolean\n ) => Promise<NextConfigComplete>\n serverActions?: {\n bodySizeLimit?: SizeLimit\n allowedOrigins?: string[]\n }\n logServerFunctions?: boolean\n params?: ParsedUrlQuery\n isPrefetch?: boolean\n experimental: {\n /**\n * When true, it indicates that the current page supports partial\n * prerendering.\n */\n isRoutePPREnabled?: boolean\n expireTime: number | undefined\n staleTimes: ExperimentalConfig['staleTimes'] | undefined\n clientTraceMetadata: string[] | undefined\n\n /**\n * The origins that are allowed to write the rewritten headers when\n * performing a non-relative rewrite. When undefined, no non-relative\n * rewrites will get the rewrite headers.\n */\n clientParamParsingOrigins: string[] | undefined\n dynamicOnHover: boolean\n optimisticRouting: boolean\n inlineCss: boolean\n prefetchInlining: PrefetchInliningConfig\n authInterrupts: boolean\n serverComponentsHmrCancellation?: boolean\n useCacheTimeout: number\n cachedNavigations: boolean\n\n /**\n * The maximum size (in bytes) of the postponed state body for PPR resume\n * requests. Used to calculate decompression limits (5x this value).\n */\n maxPostponedStateSizeBytes: number | undefined\n\n /**\n * Whether the Instant Navigation Testing API is exposed (dev mode or the\n * `exposeTestingApiInProductionBuild` flag). When true, the prerendered\n * shell and dynamic renders embed a cookie-guarded bootstrap script that\n * drives instant navigation tests.\n */\n exposeTestingApi: boolean\n }\n postponed?: string\n\n /**\n * A prefilled resume data cache. This was either generated for this page\n * during dev warmup, or when a page with defined params was previously\n * prerendered, and now its matching optional fallback shell is prerendered.\n */\n renderResumeDataCache?: RenderResumeDataCache\n\n /**\n * When true, the page will be rendered using the static rendering to detect\n * any dynamic API's that would have stopped the page from being fully\n * statically generated.\n */\n isDebugDynamicAccesses?: boolean\n\n /**\n /**\n * The maximum length of the headers that are emitted by React and added to\n * the response.\n */\n reactMaxHeadersLength: number | undefined\n\n /**\n * Per-route prefetch hints from prefetch-hints.json.\n * Loaded at server startup from the build output.\n */\n prefetchHints?: Record<string, PrefetchHints>\n\n /**\n * When true, the page is prerendered as a fallback shell, while allowing any\n * dynamic accesses to result in an empty shell. This is the case when there\n * are also routes prerendered with a more complete set of params.\n * Prerendering those routes would catch any invalid dynamic accesses.\n */\n allowEmptyStaticShell?: boolean\n\n /**\n * When true, attempt to run build-time instant validation for this prerender.\n * Only the first prerender per page sets this, since validation uses\n * instant.unstable_samples and is independent of actual route params.\n */\n runInstantValidation?: boolean\n\n /**\n * When true, a fallback shell produced for this render could later be\n * upgraded to a concrete version (at least one of its fallback params is a\n * candidate enumerated by `generateStaticParams`). Only such shells are\n * flagged `isUpgradeableISRFallback` so the client retries the prefetch; a route that\n * can never upgrade (no `generateStaticParams`) is left unflagged.\n */\n isFallbackUpgradeable?: boolean\n}\n\nexport type RenderOpts = LoadComponentsReturnType<AppPageModule> &\n RenderOptsPartial &\n RequestLifecycleOpts\n\nexport type PreloadCallbacks = (() => void)[]\n"],"names":["s","dynamicParamTypesSchema","enums","segmentSchema","union","string","tuple","nullable","array","flightRouterStateSchema","record","lazy","optional","literal","number"],"mappings":"AAeA,OAAOA,OAAO,iCAAgC;AAW9C,MAAMC,0BAA0BD,EAAEE,KAAK,CAAC;IACtC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,MAAMC,gBAAgBH,EAAEI,KAAK,CAAC;IAC5BJ,EAAEK,MAAM;IAERL,EAAEM,KAAK,CAAC;QACN,aAAa;QACbN,EAAEK,MAAM;QACR,gEAAgE;QAChE,6BAA6B;QAC7B,yEAAyE;QACzE,oEAAoE;QACpE,qEAAqE;QACrE,2CAA2C;QAC3CL,EAAEK,MAAM;QACR,qBAAqB;QACrBJ;QACA,sEAAsE;QACtE,oEAAoE;QACpE,+DAA+D;QAC/DD,EAAEO,QAAQ,CAACP,EAAEQ,KAAK,CAACR,EAAEK,MAAM;KAC5B;CACF;AAED,2EAA2E;AAC3E,uFAAuF;AACvF,uBAAuB;AACvB,OAAO,MAAMI,0BAA2CT,EAAEM,KAAK,CAAC;IAC9DH;IACAH,EAAEU,MAAM,CACNV,EAAEK,MAAM,IACRL,EAAEW,IAAI,CAAC,IAAMF;IAEfT,EAAEY,QAAQ,CAACZ,EAAEO,QAAQ,CAACP,EAAEM,KAAK,CAAC;QAACN,EAAEK,MAAM;QAAIL,EAAEK,MAAM;KAAG;IACtDL,EAAEY,QAAQ,CACRZ,EAAEO,QAAQ,CACRP,EAAEI,KAAK,CAAC;QACNJ,EAAEa,OAAO,CAAC;QACVb,EAAEa,OAAO,CAAC;QACVb,EAAEa,OAAO,CAAC;KACX;IAGLb,EAAEY,QAAQ,CAACZ,EAAEc,MAAM;CACpB,EAAC","ignoreList":[0]} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/app-render/work-unit-async-storage.external.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport type { DraftModeProvider } from '../async-storage/draft-mode-provider'\nimport type { ResponseCookies } from '../web/spec-extension/cookies'\nimport type { ReadonlyHeaders } from '../web/spec-extension/adapters/headers'\nimport type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'\nimport type { CacheSignal } from './cache-signal'\nimport type { ResponseVaryParamsAccumulator } from './vary-params'\nimport type { DynamicTrackingState } from './dynamic-rendering'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\n\n// Share the instance module in the next-shared layer\nimport { workUnitAsyncStorageInstance } from './work-unit-async-storage-instance' with { 'turbopack-transition': 'next-shared' }\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport type {\n PrerenderResumeDataCache,\n ResumeDataCache,\n} from '../resume-data-cache/resume-data-cache'\nimport type { Params } from '../request/params'\nimport type { ImplicitTags } from '../lib/implicit-tags'\nimport type { WorkStore } from './work-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport type { StagedRenderingController } from './staged-rendering'\nimport type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'\nimport type { InstantValidationSampleTracking } from './instant-validation/instant-samples'\n\nexport type WorkUnitPhase = 'action' | 'render' | 'after'\n\nexport interface CommonWorkUnitStore {\n /** NOTE: Will be mutated as phases change */\n phase: WorkUnitPhase\n readonly implicitTags: ImplicitTags\n}\n\nexport interface RequestStore extends CommonWorkUnitStore {\n readonly type: 'request'\n\n /**\n * The URL of the request. This only specifies the pathname and the search\n * part of the URL.\n */\n readonly url: {\n /**\n * The pathname of the requested URL.\n */\n readonly pathname: string\n\n /**\n * The search part of the requested URL. If the request did not provide a\n * search part, this will be an empty string.\n */\n readonly search: string\n }\n\n readonly headers: ReadonlyHeaders\n // This is mutable because we need to reassign it when transitioning from the action phase to the render phase.\n // The cookie object itself is deliberately read only and thus can't be updated.\n cookies: ReadonlyRequestCookies\n readonly mutableCookies: ResponseCookies\n readonly userspaceMutableCookies: ResponseCookies\n readonly draftMode: DraftModeProvider\n readonly isHmrRefresh?: boolean\n readonly serverComponentsHmrCache?: ServerComponentsHmrCache\n readonly hmrRefreshHash?: string\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this request. Either a mutable\n * `PrerenderResumeDataCache` (e.g. during a dev warmup that fills caches) or\n * an immutable `RenderResumeDataCache` (e.g. when resuming from a postponed\n * state). Narrow via `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n stale?: number\n\n stagedRendering?: StagedRenderingController | null\n asyncApiPromises?: AsyncApiPromises\n needsSessionShell?: boolean // DEV-only\n cacheSignal?: CacheSignal | null\n fallbackParams?: OpaqueFallbackRouteParams | null\n varyParamsAccumulator?: ResponseVaryParamsAccumulator | null\n\n // Only in build-time instant-validation or when rendering\n // a secondary stream for static shell validation\n // We mirror the controller/renderSignal from prerender stores to allow aborting the render\n controller?: AbortController\n renderSignal?: AbortSignal\n\n // Only in build-time instant-validation\n validationSamples?: InstantValidationSamples\n validationSampleTracking?: InstantValidationSampleTracking | null\n\n // DEV-only\n usedDynamic?: boolean\n}\n\nexport type InstantValidationSamples = {\n params: Params | undefined\n searchParams: Record<string, string | string[] | null> | undefined\n}\n\nexport type AsyncApiPromises = {\n cookies: Promise<ReadonlyRequestCookies>\n mutableCookies: Promise<ReadonlyRequestCookies>\n headers: Promise<ReadonlyHeaders>\n sharedParamsParent: Promise<string>\n sharedSearchParamsParent: Promise<string>\n connection: Promise<undefined>\n io: Promise<undefined>\n}\n\n/**\n * The Prerender store is for tracking information related to prerenders.\n *\n * It can be used for both RSC and SSR prerendering and should be scoped as close\n * to the individual `renderTo...` API call as possible. To keep the type simple\n * we don't distinguish between RSC and SSR prerendering explicitly but instead\n * use conditional object properties to infer which mode we are in. For instance cache tracking\n * only needs to happen during the RSC prerender when we are prospectively prerendering\n * to fill all caches.\n */\nexport type PrerenderStoreModern =\n | PrerenderStoreModernClient\n | PrerenderStoreModernServer\n | PrerenderStoreModernRuntime\n | ValidationStoreClient\n\n/** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStoreModern = Exclude<\n PrerenderStoreModern,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface PrerenderStoreModernClient\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender-client'\n}\n\nexport interface ValidationStoreClient extends PrerenderStoreModernCommon {\n readonly type: 'validation-client'\n readonly boundaryState: ValidationBoundaryTracking | null\n validationSamples: InstantValidationSamples | null\n validationSampleTracking: InstantValidationSampleTracking | null\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStoreModernServer\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender'\n\n readonly stagedRendering: StagedRenderingController | null\n\n /**\n * When not null, records whether the render has accessed a data source\n * that hangs during a static prerender but would resolve during a runtime\n * prerender — cookies, headers, fallback params, searchParams, and cache\n * entries excluded only from static prerenders. Call sites go through\n * `trackRuntimeDataAccessed`, which resolves the promise `true` on the\n * first access; it's resolved `false` when the prerender completes without\n * one. Promise resolution is idempotent, so the flag is monotonic with no\n * extra state.\n *\n * The promise is embedded in the RSC payload (`InitialRSCPayload['u']`)\n * so the fulfillment row's stream position records the stage the access\n * happened in; the per-segment prefetch encoding (`collectSegmentData`)\n * extracts it from the page data to tell the client whether a runtime\n * prefetch request could be skipped. Tracking is page-global: an access\n * anywhere in the page poisons all segments (per-segment granularity is\n * recovered downstream for segments whose content is provably complete).\n * Shared between the payload prerender store and the render store because\n * request-data props are created during payload construction, before the\n * render store exists. Null for warmup, route-handler, and error prerender\n * stores.\n */\n readonly runtimeDataAccessed: PromiseWithResolvers<boolean> | null\n\n /**\n * Mutable single-boolean companion to `runtimeDataAccessed`, holding this\n * prerender's `PrefetchHint.ShouldAttemptStaticPrefetch` measurement\n * directly — the value that becomes the route's build-constant hint:\n * starts `true`, and a disqualifying runtime-data access flips it to\n * `false`. Not every access that resolves the promise disqualifies —\n * fallback-param accesses on a fallback-upgradeable route are transient\n * and leave the hint intact (see `trackRuntimeDataAccessed`, which applies\n * the rule at access time using `isFallbackUpgradeable` below). A plain\n * boolean suffices because the hint needs no stream positioning: unlike\n * `runtimeDataAccessed`, whose fulfillment position encodes which stage\n * the access happened in, this is read once after the prerender settles.\n * Held in a cell so it can be shared. Same sharing and null rules as\n * `runtimeDataAccessed`.\n */\n readonly shouldAttemptStaticPrefetch: { current: boolean } | null\n\n /**\n * Whether a fallback shell produced by this prerender could later be\n * upgraded to a concrete prerender (`renderOpts.isFallbackUpgradeable`:\n * at least one fallback param is a `generateStaticParams` candidate).\n * Consulted by `trackRuntimeDataAccessed` to decide whether a\n * fallback-param access disqualifies the static-prefetch hint.\n */\n readonly isFallbackUpgradeable: boolean\n}\n\nexport interface PrerenderStoreModernRuntime\n extends PrerenderStoreModernCommon {\n readonly type: 'prerender-runtime'\n\n /**\n * The staged rendering controller for this prerender. Models stage\n * transitions (Before → Static → Runtime → Dynamic). Null for prospective\n * renders where all stages run without sequencing.\n */\n readonly stagedRendering: StagedRenderingController | null\n readonly isSessionShell: boolean\n\n readonly headers: RequestStore['headers']\n readonly cookies: RequestStore['cookies']\n readonly draftMode: RequestStore['draftMode']\n}\n\nexport interface RevalidateStore {\n // Collected revalidate times and tags for this document during the prerender.\n revalidate: number // in seconds. 0 means dynamic. INFINITE_CACHE and higher means never revalidate.\n expire: number // server expiration time\n stale: number // client expiration time\n tags: null | string[]\n}\n\ninterface PrerenderStoreModernCommon\n extends CommonWorkUnitStore,\n RevalidateStore {\n /**\n * The render signal is aborted after React's `prerender` function is aborted\n * (using a separate signal), which happens in two cases:\n *\n * 1. When all caches are filled during the prospective prerender.\n * 2. When the final prerender is aborted immediately after the prerender was\n * started.\n *\n * It can be used to reject any pending I/O, including hanging promises. This\n * allows React to properly track the async I/O in dev mode, which yields\n * better owner stacks for dynamic validation errors.\n */\n readonly renderSignal: AbortSignal\n\n /**\n * This is the AbortController which represents the boundary between Prerender\n * and dynamic. In some renders it is the same as the controller for React,\n * but in others it is a separate controller. It should be aborted whenever we\n * are no longer in the prerender phase of rendering. Typically this is after\n * one task, or when you call a sync API which requires the prerender to end\n * immediately.\n */\n readonly controller: AbortController\n\n /**\n * When not null, this signal is used to track cache reads during prerendering\n * and to await all cache reads completing, before aborting the prerender.\n */\n readonly cacheSignal: null | CacheSignal\n\n /**\n * During some prerenders we want to track dynamic access.\n */\n readonly dynamicTracking: null | DynamicTrackingState\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this prerender. Either a mutable\n * `PrerenderResumeDataCache` that fills as this prerender runs, or an\n * immutable `RenderResumeDataCache` provided by an earlier phase when the\n * prerender is supposed to read from prefilled caches only (e.g. when\n * prerendering an optional fallback shell). Narrow via\n * `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n /**\n * The HMR refresh hash is only provided in dev mode. It is needed for the dev\n * warmup render to ensure that the cache keys will be identical for the\n * subsequent dynamic render.\n */\n readonly hmrRefreshHash: string | undefined\n\n /**\n * A mutable accumulator for per-segment vary params during prerender. Tracks\n * which route params each segment actually accesses, allowing the client\n * cache to re-key entries for better sharing across different param values.\n */\n readonly varyParamsAccumulator: ResponseVaryParamsAccumulator | null\n}\n\ninterface StaticPrerenderStoreCommon {\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStorePPR\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-ppr'\n readonly rootParams: Params\n readonly dynamicTracking: null | DynamicTrackingState\n\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n\n /**\n * The resume data cache for this prerender. Always mutable in PPR mode.\n */\n resumeDataCache: PrerenderResumeDataCache\n}\n\nexport interface PrerenderStoreLegacy\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-legacy'\n readonly rootParams: Params\n}\n\nexport type PrerenderStore =\n | PrerenderStoreLegacy\n | PrerenderStorePPR\n | PrerenderStoreModern\n\n// /** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStore = Exclude<\n PrerenderStore,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface CommonCacheStore\n extends Omit<CommonWorkUnitStore, 'implicitTags'> {\n /**\n * Whether this work unit will persist the results it consumes in a server\n * cache. This only describes the immediate consumer; it is not inherited\n * from outer scopes.\n */\n readonly consumerWillServerCache: boolean\n /**\n * A cache work unit store might not always have an outer work unit store,\n * from which implicit tags could be inherited.\n */\n readonly implicitTags: ImplicitTags | undefined\n /**\n * Draft mode is only available if the outer work unit store is a request\n * store and draft mode is enabled.\n */\n readonly draftMode: DraftModeProvider | undefined\n}\n\nexport interface CommonUseCacheStore extends CommonCacheStore, RevalidateStore {\n explicitRevalidate: undefined | number // explicit revalidate time from cacheLife() calls\n explicitExpire: undefined | number // server expiration time\n explicitStale: undefined | number // client expiration time\n readonly hmrRefreshHash: string | undefined\n readonly isHmrRefresh: boolean\n readonly serverComponentsHmrCache: ServerComponentsHmrCache | undefined\n readonly forceRevalidate: boolean\n readonly outerOwnerStack: string | undefined\n}\n\nexport interface PublicUseCacheStore extends CommonUseCacheStore {\n readonly type: 'cache'\n\n /**\n * The root params for the current route. `undefined` when nested inside\n * `unstable_cache`, which doesn't carry root params. Currently, `\"use cache\"`\n * inside `unstable_cache` is allowed, so this case must be handled. The error\n * message in `getRootParam` assumes this is the only scenario where\n * `rootParams` is `undefined`.\n */\n readonly rootParams: Params | undefined\n /**\n * Tracks which root param names were read during this cache invocation.\n */\n readonly readRootParamNames: Set<string>\n /**\n * The first nested public `'use cache'` invocation with a dynamic cache life\n * (`revalidate === 0` or `expire < MIN_PRERENDERABLE_EXPIRE`) that propagated\n * up to this store. Used as `cause` for the nested-dynamic cache error so the\n * redbox can point at the inner invocation site, not just the outer one.\n */\n dynamicNestedCacheError: Error | undefined\n}\n\nexport interface PrivateUseCacheStore extends CommonUseCacheStore {\n readonly type: 'private-cache'\n\n readonly headers: ReadonlyHeaders\n readonly cookies: ReadonlyRequestCookies\n\n readonly rootParams: Params\n\n /**\n * DEV-only: Tracks which root param names were read during this cache\n * invocation. In development, private caches are persisted (keyed by the\n * request's cookies and headers), so reads of different root param values\n * must produce different entries.\n */\n readonly readRootParamNames: Set<string> | undefined\n}\n\nexport type UseCacheStore = PublicUseCacheStore | PrivateUseCacheStore\n\nexport interface UnstableCacheStore extends CommonCacheStore {\n readonly type: 'unstable-cache'\n /**\n * Always `undefined` for `unstable_cache` — root params are not available in\n * this context. If a `\"use cache\"` function nested inside `unstable_cache`\n * tries to access root params, it will encounter `undefined` here and throw.\n */\n readonly rootParams: undefined\n}\n\n/**\n * The Cache store is for tracking information inside a \"use cache\" or\n * unstable_cache context. A cache store shadows an outer request store (if\n * present) as a work unit, so that we never accidentally expose any request or\n * page specific information to cache functions, unless it's explicitly desired.\n * For those exceptions, the data is copied over from the request store to the\n * cache store, instead of generally making the request store available to cache\n * functions.\n */\nexport type CacheStore = UseCacheStore | UnstableCacheStore\n\nexport interface GenerateStaticParamsStore extends CommonWorkUnitStore {\n readonly type: 'generate-static-params'\n readonly rootParams: Params\n}\n\nexport type WorkUnitStore =\n | RequestStore\n | CacheStore\n | PrerenderStore\n | GenerateStaticParamsStore\n\nexport function willConsumerServerCache(\n workUnitStore: WorkUnitStore | undefined\n): boolean {\n if (!workUnitStore) {\n return false\n }\n\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n return workUnitStore.consumerWillServerCache\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return true\n case 'request':\n case 'prerender-runtime':\n case 'validation-client':\n case 'generate-static-params':\n return false\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport type WorkUnitAsyncStorage = AsyncLocalStorage<WorkUnitStore>\n\nexport { workUnitAsyncStorageInstance as workUnitAsyncStorage }\n\nexport function throwForMissingRequestStore(callingExpression: string): never {\n throw new Error(\n `\\`${callingExpression}\\` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n}\n\nexport function throwInvariantForMissingStore(): never {\n throw new InvariantError('Expected workUnitAsyncStorage to have a store.')\n}\n\n/**\n * Returns the resume data cache for the given work unit store, regardless of\n * whether it is mutable (`PrerenderResumeDataCache`) or read-only\n * (`RenderResumeDataCache`). Use `resumeDataCache.mutable` to narrow.\n */\nexport function getResumeDataCache(\n workUnitStore: WorkUnitStore\n): ResumeDataCache | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n return workUnitStore.resumeDataCache\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-legacy':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getHmrRefreshHash(\n workUnitStore: WorkUnitStore\n): string | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.hmrRefreshHash\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function isHmrRefresh(workUnitStore: WorkUnitStore): boolean {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.isHmrRefresh ?? false\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return false\n}\n\nexport function getServerComponentsHmrCache(\n workUnitStore: WorkUnitStore\n): ServerComponentsHmrCache | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.serverComponentsHmrCache\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\n/**\n * Returns a draft mode provider only if draft mode is enabled.\n */\nexport function getDraftModeProviderForCacheScope(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): DraftModeProvider | undefined {\n if (workStore.isDraftMode) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.draftMode\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function getStagedRenderingController(\n workUnitStore: WorkUnitStore\n): StagedRenderingController | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender-runtime':\n case 'prerender':\n return workUnitStore.stagedRendering ?? null\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getCacheSignal(\n workUnitStore: WorkUnitStore\n): CacheSignal | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n return workUnitStore.cacheSignal\n case 'request': {\n // In dev, we might fill caches even during a dynamic request.\n if (workUnitStore.cacheSignal) {\n return workUnitStore.cacheSignal\n }\n // fallthrough\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getVaryParamsAccumulator(\n workUnitStore: WorkUnitStore\n): ResponseVaryParamsAccumulator | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime':\n case 'request': {\n return workUnitStore.varyParamsAccumulator ?? null\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'prerender-client':\n case 'validation-client':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n workUnitStore satisfies never\n return null\n }\n}\n"],"names":["workUnitAsyncStorageInstance","InvariantError","willConsumerServerCache","workUnitStore","type","consumerWillServerCache","workUnitAsyncStorage","throwForMissingRequestStore","callingExpression","Error","throwInvariantForMissingStore","getResumeDataCache","resumeDataCache","getHmrRefreshHash","process","env","__NEXT_DEV_SERVER","hmrRefreshHash","undefined","isHmrRefresh","getServerComponentsHmrCache","serverComponentsHmrCache","getDraftModeProviderForCacheScope","workStore","isDraftMode","draftMode","getStagedRenderingController","stagedRendering","getCacheSignal","cacheSignal","getVaryParamsAccumulator","varyParamsAccumulator"],"mappings":"AAUA,qDAAqD;AACrD,SAASA,4BAA4B,QAAQ,0CAA0C;IAAE,wBAAwB;AAAc,EAAC;AAShI,SAASC,cAAc,QAAQ,mCAAkC;AA2ajE,OAAO,SAASC,wBACdC,aAAwC;IAExC,IAAI,CAACA,eAAe;QAClB,OAAO;IACT;IAEA,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOD,cAAcE,uBAAuB;QAC9C,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAOF;IACX;AACF;AAIA,SAASH,gCAAgCM,oBAAoB,GAAE;AAE/D,OAAO,SAASC,4BAA4BC,iBAAyB;IACnE,MAAM,qBAEL,CAFK,IAAIC,MACR,CAAC,EAAE,EAAED,kBAAkB,iHAAiH,CAAC,GADrI,qBAAA;eAAA;oBAAA;sBAAA;IAEN;AACF;AAEA,OAAO,SAASE;IACd,MAAM,qBAAoE,CAApE,IAAIT,eAAe,mDAAnB,qBAAA;eAAA;oBAAA;sBAAA;IAAmE;AAC3E;AAEA;;;;CAIC,GACD,OAAO,SAASU,mBACdR,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOD,cAAcS,eAAe;QACtC,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAOT;IACX;AACF;AAEA,OAAO,SAASU,kBACdV,aAA4B;IAE5B,IAAIW,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QACjC,OAAQb,cAAcC,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH,OAAOD,cAAcc,cA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KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAOxB;IACX;AACF;AAEA,OAAO,SAASyB,eACdzB,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOD,cAAc0B,WAAW;QAClC,KAAK;YAAW;gBACd,8DAA8D;gBAC9D,IAAI1B,cAAc0B,WAAW,EAAE;oBAC7B,OAAO1B,cAAc0B,WAAW;gBAClC;YACA,cAAc;YAChB;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAO1B;IACX;AACF;AAEA,OAAO,SAAS2B,yBACd3B,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;YAAW;gBACd,OAAOD,cAAc4B,qBAAqB,IAAI;YAChD;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE5B;YACA,OAAO;IACX;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/app-render/work-unit-async-storage.external.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport type { DraftModeProvider } from '../async-storage/draft-mode-provider'\nimport type { ResponseCookies } from '../web/spec-extension/cookies'\nimport type { ReadonlyHeaders } from '../web/spec-extension/adapters/headers'\nimport type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'\nimport type { CacheSignal } from './cache-signal'\nimport type { ResponseVaryParamsAccumulator } from './vary-params'\nimport type { DynamicTrackingState } from './dynamic-rendering'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\n\n// Share the instance module in the next-shared layer\nimport { workUnitAsyncStorageInstance } from './work-unit-async-storage-instance' with { 'turbopack-transition': 'next-shared' }\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport type {\n PrerenderResumeDataCache,\n ResumeDataCache,\n} from '../resume-data-cache/resume-data-cache'\nimport type { Params } from '../request/params'\nimport type { ImplicitTags } from '../lib/implicit-tags'\nimport type { WorkStore } from './work-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport type { StagedRenderingController } from './staged-rendering'\nimport type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'\nimport type { InstantValidationSampleTracking } from './instant-validation/instant-samples'\n\nexport type WorkUnitPhase = 'action' | 'render' | 'after'\n\nexport interface CommonWorkUnitStore {\n /** NOTE: Will be mutated as phases change */\n phase: WorkUnitPhase\n readonly implicitTags: ImplicitTags\n}\n\nexport interface RequestStore extends CommonWorkUnitStore {\n readonly type: 'request'\n\n /**\n * The URL of the request. This only specifies the pathname and the search\n * part of the URL.\n */\n readonly url: {\n /**\n * The pathname of the requested URL.\n */\n readonly pathname: string\n\n /**\n * The search part of the requested URL. If the request did not provide a\n * search part, this will be an empty string.\n */\n readonly search: string\n }\n\n readonly headers: ReadonlyHeaders\n // This is mutable because we need to reassign it when transitioning from the action phase to the render phase.\n // The cookie object itself is deliberately read only and thus can't be updated.\n cookies: ReadonlyRequestCookies\n readonly mutableCookies: ResponseCookies\n readonly userspaceMutableCookies: ResponseCookies\n readonly draftMode: DraftModeProvider\n readonly isHmrRefresh?: boolean\n readonly serverComponentsHmrCache?: ServerComponentsHmrCache\n readonly hmrRefreshHash?: string\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this request. Either a mutable\n * `PrerenderResumeDataCache` (e.g. during a dev warmup that fills caches) or\n * an immutable `RenderResumeDataCache` (e.g. when resuming from a postponed\n * state). Narrow via `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n stale?: number\n\n stagedRendering?: StagedRenderingController | null\n asyncApiPromises?: AsyncApiPromises\n\n /**\n * DEV-only.\n * Certain APIs have different behavior in static and runtime prerenders.\n * - if `false`, they will follow static semantics\n * - if `true`, they will follow runtime semantics\n * */\n needsAppShell?: boolean // DEV-only\n /**\n * DEV-only, mutable.\n * Whether any APIs that resolve in different stages in static and\n * runtime prerenders (i.e. whose behavior varies on `needsAppShell`)\n * were used during this render.\n * */\n hasIncompatibleShellContent?: boolean\n\n cacheSignal?: CacheSignal | null\n fallbackParams?: OpaqueFallbackRouteParams | null\n varyParamsAccumulator?: ResponseVaryParamsAccumulator | null\n\n // Only in build-time instant-validation or when rendering\n // a secondary stream for static shell validation\n // We mirror the controller/renderSignal from prerender stores to allow aborting the render\n controller?: AbortController\n renderSignal?: AbortSignal\n\n // Only in build-time instant-validation\n validationSamples?: InstantValidationSamples\n validationSampleTracking?: InstantValidationSampleTracking | null\n\n // DEV-only\n usedDynamic?: boolean\n}\n\nexport type InstantValidationSamples = {\n params: Params | undefined\n searchParams: Record<string, string | string[] | null> | undefined\n}\n\nexport type AsyncApiPromises = {\n cookies: Promise<ReadonlyRequestCookies>\n mutableCookies: Promise<ReadonlyRequestCookies>\n headers: Promise<ReadonlyHeaders>\n sharedParamsParent: Promise<string>\n sharedSearchParamsParent: Promise<string>\n connection: Promise<undefined>\n io: Promise<undefined>\n}\n\n/**\n * The Prerender store is for tracking information related to prerenders.\n *\n * It can be used for both RSC and SSR prerendering and should be scoped as close\n * to the individual `renderTo...` API call as possible. To keep the type simple\n * we don't distinguish between RSC and SSR prerendering explicitly but instead\n * use conditional object properties to infer which mode we are in. For instance cache tracking\n * only needs to happen during the RSC prerender when we are prospectively prerendering\n * to fill all caches.\n */\nexport type PrerenderStoreModern =\n | PrerenderStoreModernClient\n | PrerenderStoreModernServer\n | PrerenderStoreModernRuntime\n | ValidationStoreClient\n\n/** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStoreModern = Exclude<\n PrerenderStoreModern,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface PrerenderStoreModernClient\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender-client'\n}\n\nexport interface ValidationStoreClient extends PrerenderStoreModernCommon {\n readonly type: 'validation-client'\n readonly boundaryState: ValidationBoundaryTracking | null\n validationSamples: InstantValidationSamples | null\n validationSampleTracking: InstantValidationSampleTracking | null\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStoreModernServer\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender'\n\n readonly stagedRendering: StagedRenderingController | null\n\n /**\n * When not null, records whether the render has accessed a data source\n * that hangs during a static prerender but would resolve during a runtime\n * prerender — cookies, headers, fallback params, searchParams, and cache\n * entries excluded only from static prerenders. Call sites go through\n * `trackRuntimeDataAccessed`, which resolves the promise `true` on the\n * first access; it's resolved `false` when the prerender completes without\n * one. Promise resolution is idempotent, so the flag is monotonic with no\n * extra state.\n *\n * The promise is embedded in the RSC payload (`InitialRSCPayload['u']`)\n * so the fulfillment row's stream position records the stage the access\n * happened in; the per-segment prefetch encoding (`collectSegmentData`)\n * extracts it from the page data to tell the client whether a runtime\n * prefetch request could be skipped. Tracking is page-global: an access\n * anywhere in the page poisons all segments (per-segment granularity is\n * recovered downstream for segments whose content is provably complete).\n * Shared between the payload prerender store and the render store because\n * request-data props are created during payload construction, before the\n * render store exists. Null for warmup, route-handler, and error prerender\n * stores.\n */\n readonly runtimeDataAccessed: PromiseWithResolvers<boolean> | null\n\n /**\n * Mutable single-boolean companion to `runtimeDataAccessed`, holding this\n * prerender's `PrefetchHint.ShouldAttemptStaticPrefetch` measurement\n * directly — the value that becomes the route's build-constant hint:\n * starts `true`, and a disqualifying runtime-data access flips it to\n * `false`. Not every access that resolves the promise disqualifies —\n * fallback-param accesses on a fallback-upgradeable route are transient\n * and leave the hint intact (see `trackRuntimeDataAccessed`, which applies\n * the rule at access time using `isFallbackUpgradeable` below). A plain\n * boolean suffices because the hint needs no stream positioning: unlike\n * `runtimeDataAccessed`, whose fulfillment position encodes which stage\n * the access happened in, this is read once after the prerender settles.\n * Held in a cell so it can be shared. Same sharing and null rules as\n * `runtimeDataAccessed`.\n */\n readonly shouldAttemptStaticPrefetch: { current: boolean } | null\n\n /**\n * Whether a fallback shell produced by this prerender could later be\n * upgraded to a concrete prerender (`renderOpts.isFallbackUpgradeable`:\n * at least one fallback param is a `generateStaticParams` candidate).\n * Consulted by `trackRuntimeDataAccessed` to decide whether a\n * fallback-param access disqualifies the static-prefetch hint.\n */\n readonly isFallbackUpgradeable: boolean\n}\n\nexport interface PrerenderStoreModernRuntime\n extends PrerenderStoreModernCommon {\n readonly type: 'prerender-runtime'\n\n /**\n * The staged rendering controller for this prerender. Models stage\n * transitions (Before → Static → Runtime → Dynamic). Null for prospective\n * renders where all stages run without sequencing.\n */\n readonly stagedRendering: StagedRenderingController | null\n readonly isSessionShell: boolean\n\n readonly headers: RequestStore['headers']\n readonly cookies: RequestStore['cookies']\n readonly draftMode: RequestStore['draftMode']\n}\n\nexport interface RevalidateStore {\n // Collected revalidate times and tags for this document during the prerender.\n revalidate: number // in seconds. 0 means dynamic. INFINITE_CACHE and higher means never revalidate.\n expire: number // server expiration time\n stale: number // client expiration time\n tags: null | string[]\n}\n\ninterface PrerenderStoreModernCommon\n extends CommonWorkUnitStore,\n RevalidateStore {\n /**\n * The render signal is aborted after React's `prerender` function is aborted\n * (using a separate signal), which happens in two cases:\n *\n * 1. When all caches are filled during the prospective prerender.\n * 2. When the final prerender is aborted immediately after the prerender was\n * started.\n *\n * It can be used to reject any pending I/O, including hanging promises. This\n * allows React to properly track the async I/O in dev mode, which yields\n * better owner stacks for dynamic validation errors.\n */\n readonly renderSignal: AbortSignal\n\n /**\n * This is the AbortController which represents the boundary between Prerender\n * and dynamic. In some renders it is the same as the controller for React,\n * but in others it is a separate controller. It should be aborted whenever we\n * are no longer in the prerender phase of rendering. Typically this is after\n * one task, or when you call a sync API which requires the prerender to end\n * immediately.\n */\n readonly controller: AbortController\n\n /**\n * When not null, this signal is used to track cache reads during prerendering\n * and to await all cache reads completing, before aborting the prerender.\n */\n readonly cacheSignal: null | CacheSignal\n\n /**\n * During some prerenders we want to track dynamic access.\n */\n readonly dynamicTracking: null | DynamicTrackingState\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this prerender. Either a mutable\n * `PrerenderResumeDataCache` that fills as this prerender runs, or an\n * immutable `RenderResumeDataCache` provided by an earlier phase when the\n * prerender is supposed to read from prefilled caches only (e.g. when\n * prerendering an optional fallback shell). Narrow via\n * `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n /**\n * The HMR refresh hash is only provided in dev mode. It is needed for the dev\n * warmup render to ensure that the cache keys will be identical for the\n * subsequent dynamic render.\n */\n readonly hmrRefreshHash: string | undefined\n\n /**\n * A mutable accumulator for per-segment vary params during prerender. Tracks\n * which route params each segment actually accesses, allowing the client\n * cache to re-key entries for better sharing across different param values.\n */\n readonly varyParamsAccumulator: ResponseVaryParamsAccumulator | null\n}\n\ninterface StaticPrerenderStoreCommon {\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStorePPR\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-ppr'\n readonly rootParams: Params\n readonly dynamicTracking: null | DynamicTrackingState\n\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n\n /**\n * The resume data cache for this prerender. Always mutable in PPR mode.\n */\n resumeDataCache: PrerenderResumeDataCache\n}\n\nexport interface PrerenderStoreLegacy\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-legacy'\n readonly rootParams: Params\n}\n\nexport type PrerenderStore =\n | PrerenderStoreLegacy\n | PrerenderStorePPR\n | PrerenderStoreModern\n\n// /** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStore = Exclude<\n PrerenderStore,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface CommonCacheStore\n extends Omit<CommonWorkUnitStore, 'implicitTags'> {\n /**\n * Whether this work unit will persist the results it consumes in a server\n * cache. This only describes the immediate consumer; it is not inherited\n * from outer scopes.\n */\n readonly consumerWillServerCache: boolean\n /**\n * A cache work unit store might not always have an outer work unit store,\n * from which implicit tags could be inherited.\n */\n readonly implicitTags: ImplicitTags | undefined\n /**\n * Draft mode is only available if the outer work unit store is a request\n * store and draft mode is enabled.\n */\n readonly draftMode: DraftModeProvider | undefined\n}\n\nexport interface CommonUseCacheStore extends CommonCacheStore, RevalidateStore {\n explicitRevalidate: undefined | number // explicit revalidate time from cacheLife() calls\n explicitExpire: undefined | number // server expiration time\n explicitStale: undefined | number // client expiration time\n readonly hmrRefreshHash: string | undefined\n readonly isHmrRefresh: boolean\n readonly serverComponentsHmrCache: ServerComponentsHmrCache | undefined\n readonly forceRevalidate: boolean\n readonly outerOwnerStack: string | undefined\n}\n\nexport interface PublicUseCacheStore extends CommonUseCacheStore {\n readonly type: 'cache'\n\n /**\n * The root params for the current route. `undefined` when nested inside\n * `unstable_cache`, which doesn't carry root params. Currently, `\"use cache\"`\n * inside `unstable_cache` is allowed, so this case must be handled. The error\n * message in `getRootParam` assumes this is the only scenario where\n * `rootParams` is `undefined`.\n */\n readonly rootParams: Params | undefined\n /**\n * Tracks which root param names were read during this cache invocation.\n */\n readonly readRootParamNames: Set<string>\n /**\n * The first nested public `'use cache'` invocation with a dynamic cache life\n * (`revalidate === 0` or `expire < MIN_PRERENDERABLE_EXPIRE`) that propagated\n * up to this store. Used as `cause` for the nested-dynamic cache error so the\n * redbox can point at the inner invocation site, not just the outer one.\n */\n dynamicNestedCacheError: Error | undefined\n}\n\nexport interface PrivateUseCacheStore extends CommonUseCacheStore {\n readonly type: 'private-cache'\n\n readonly headers: ReadonlyHeaders\n readonly cookies: ReadonlyRequestCookies\n\n readonly rootParams: Params\n\n /**\n * DEV-only: Tracks which root param names were read during this cache\n * invocation. In development, private caches are persisted (keyed by the\n * request's cookies and headers), so reads of different root param values\n * must produce different entries.\n */\n readonly readRootParamNames: Set<string> | undefined\n}\n\nexport type UseCacheStore = PublicUseCacheStore | PrivateUseCacheStore\n\nexport interface UnstableCacheStore extends CommonCacheStore {\n readonly type: 'unstable-cache'\n /**\n * Always `undefined` for `unstable_cache` — root params are not available in\n * this context. If a `\"use cache\"` function nested inside `unstable_cache`\n * tries to access root params, it will encounter `undefined` here and throw.\n */\n readonly rootParams: undefined\n}\n\n/**\n * The Cache store is for tracking information inside a \"use cache\" or\n * unstable_cache context. A cache store shadows an outer request store (if\n * present) as a work unit, so that we never accidentally expose any request or\n * page specific information to cache functions, unless it's explicitly desired.\n * For those exceptions, the data is copied over from the request store to the\n * cache store, instead of generally making the request store available to cache\n * functions.\n */\nexport type CacheStore = UseCacheStore | UnstableCacheStore\n\nexport interface GenerateStaticParamsStore extends CommonWorkUnitStore {\n readonly type: 'generate-static-params'\n readonly rootParams: Params\n}\n\nexport type WorkUnitStore =\n | RequestStore\n | CacheStore\n | PrerenderStore\n | GenerateStaticParamsStore\n\nexport function willConsumerServerCache(\n workUnitStore: WorkUnitStore | undefined\n): boolean {\n if (!workUnitStore) {\n return false\n }\n\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n return workUnitStore.consumerWillServerCache\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return true\n case 'request':\n case 'prerender-runtime':\n case 'validation-client':\n case 'generate-static-params':\n return false\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport type WorkUnitAsyncStorage = AsyncLocalStorage<WorkUnitStore>\n\nexport { workUnitAsyncStorageInstance as workUnitAsyncStorage }\n\nexport function throwForMissingRequestStore(callingExpression: string): never {\n throw new Error(\n `\\`${callingExpression}\\` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n}\n\nexport function throwInvariantForMissingStore(): never {\n throw new InvariantError('Expected workUnitAsyncStorage to have a store.')\n}\n\n/**\n * Returns the resume data cache for the given work unit store, regardless of\n * whether it is mutable (`PrerenderResumeDataCache`) or read-only\n * (`RenderResumeDataCache`). Use `resumeDataCache.mutable` to narrow.\n */\nexport function getResumeDataCache(\n workUnitStore: WorkUnitStore\n): ResumeDataCache | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n return workUnitStore.resumeDataCache\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-legacy':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getHmrRefreshHash(\n workUnitStore: WorkUnitStore\n): string | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.hmrRefreshHash\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function isHmrRefresh(workUnitStore: WorkUnitStore): boolean {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.isHmrRefresh ?? false\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return false\n}\n\nexport function getServerComponentsHmrCache(\n workUnitStore: WorkUnitStore\n): ServerComponentsHmrCache | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.serverComponentsHmrCache\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\n/**\n * Returns a draft mode provider only if draft mode is enabled.\n */\nexport function getDraftModeProviderForCacheScope(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): DraftModeProvider | undefined {\n if (workStore.isDraftMode) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.draftMode\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function getStagedRenderingController(\n workUnitStore: WorkUnitStore\n): StagedRenderingController | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender-runtime':\n case 'prerender':\n return workUnitStore.stagedRendering ?? null\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getCacheSignal(\n workUnitStore: WorkUnitStore\n): CacheSignal | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n return workUnitStore.cacheSignal\n case 'request': {\n // In dev, we might fill caches even during a dynamic request.\n if (workUnitStore.cacheSignal) {\n return workUnitStore.cacheSignal\n }\n // fallthrough\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getVaryParamsAccumulator(\n workUnitStore: WorkUnitStore\n): ResponseVaryParamsAccumulator | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime':\n case 'request': {\n return workUnitStore.varyParamsAccumulator ?? null\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'prerender-client':\n case 'validation-client':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n workUnitStore satisfies never\n return null\n }\n}\n"],"names":["workUnitAsyncStorageInstance","InvariantError","willConsumerServerCache","workUnitStore","type","consumerWillServerCache","workUnitAsyncStorage","throwForMissingRequestStore","callingExpression","Error","throwInvariantForMissingStore","getResumeDataCache","resumeDataCache","getHmrRefreshHash","process","env","__NEXT_DEV_SERVER","hmrRefreshHash","undefined","isHmrRefresh","getServerComponentsHmrCache","serverComponentsHmrCache","getDraftModeProviderForCacheScope","workStore","isDraftMode","draftMode","getStagedRenderingController","stagedRendering","getCacheSignal","cacheSignal","getVaryParamsAccumulator","varyParamsAccumulator"],"mappings":"AAUA,qDAAqD;AACrD,SAASA,4BAA4B,QAAQ,0CAA0C;IAAE,wBAAwB;AAAc,EAAC;AAShI,SAASC,cAAc,QAAQ,mCAAkC;AA0bjE,OAAO,SAASC,wBACdC,aAAwC;IAExC,IAAI,CAACA,eAAe;QAClB,OAAO;IACT;IAEA,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOD,cAAcE,uBAAuB;QAC9C,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAOF;IACX;AACF;AAIA,SAASH,gCAAgCM,oBAAoB,GAAE;AAE/D,OAAO,SAASC,4BAA4BC,iBAAyB;IACnE,MAAM,qBAEL,CAFK,IAAIC,MACR,CAAC,EAAE,EAAED,kBAAkB,iHAAiH,CAAC,GADrI,qBAAA;eAAA;oBAAA;sBAAA;IAEN;AACF;AAEA,OAAO,SAASE;IACd,MAAM,qBAAoE,CAApE,IAAIT,eAAe,mDAAnB,qBAAA;eAA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SAASI,kCACdC,SAAoB,EACpBpB,aAA4B;IAE5B,IAAIoB,UAAUC,WAAW,EAAE;QACzB,OAAQrB,cAAcC,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH,OAAOD,cAAcsB,SAAS;YAChC,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH;YACF;gBACEtB;QACJ;IACF;IAEA,OAAOe;AACT;AAEA,OAAO,SAASQ,6BACdvB,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOD,cAAcwB,eAAe,IAAI;QAC1C,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAOxB;IACX;AACF;AAEA,OAAO,SAASyB,eACdzB,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOD,cAAc0B,WAAW;QAClC,KAAK;YAAW;gBACd,8DAA8D;gBAC9D,IAAI1B,cAAc0B,WAAW,EAAE;oBAC7B,OAAO1B,cAAc0B,WAAW;gBAClC;YACA,cAAc;YAChB;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAO1B;IACX;AACF;AAEA,OAAO,SAAS2B,yBACd3B,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;YAAW;gBACd,OAAOD,cAAc4B,qBAAqB,IAAI;YAChD;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE5B;YACA,OAAO;IACX;AACF","ignoreList":[0]} |
| // Combined load times for loading client components | ||
| let clientComponentLoadStart = 0; | ||
| let clientComponentLoadEnd = 0; | ||
| let clientComponentLoadTimes = 0; | ||
@@ -19,3 +20,5 @@ let clientComponentLoadCount = 0; | ||
| } finally{ | ||
| clientComponentLoadTimes += performance.now() - startTime; | ||
| const endTime = performance.now(); | ||
| clientComponentLoadEnd = endTime; | ||
| clientComponentLoadTimes += endTime - startTime; | ||
| } | ||
@@ -25,8 +28,14 @@ }, | ||
| const startTime = performance.now(); | ||
| if (clientComponentLoadStart === 0) { | ||
| clientComponentLoadStart = startTime; | ||
| } | ||
| const result = ComponentMod.__next_app__.loadChunk(...args); | ||
| // Avoid wrapping `loadChunk`'s result in an extra promise in case something like React depends on its identity. | ||
| // We only need to know when it's settled. | ||
| result.finally(()=>{ | ||
| clientComponentLoadTimes += performance.now() - startTime; | ||
| }); | ||
| const onSettled = ()=>{ | ||
| const endTime = performance.now(); | ||
| clientComponentLoadEnd = endTime; | ||
| clientComponentLoadTimes += endTime - startTime; | ||
| }; | ||
| result.then(onSettled, onSettled); | ||
| return result; | ||
@@ -39,2 +48,3 @@ } | ||
| clientComponentLoadStart, | ||
| clientComponentLoadEnd, | ||
| clientComponentLoadTimes, | ||
@@ -45,2 +55,3 @@ clientComponentLoadCount | ||
| clientComponentLoadStart = 0; | ||
| clientComponentLoadEnd = 0; | ||
| clientComponentLoadTimes = 0; | ||
@@ -47,0 +58,0 @@ clientComponentLoadCount = 0; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/client-component-renderer-logger.ts"],"sourcesContent":["import type { AppPageModule } from './route-modules/app-page/module'\n\n// Combined load times for loading client components\nlet clientComponentLoadStart = 0\nlet clientComponentLoadTimes = 0\nlet clientComponentLoadCount = 0\n\nexport function wrapClientComponentLoader(\n ComponentMod: AppPageModule,\n isTracingEnabled: boolean\n): AppPageModule['__next_app__'] {\n if (\n !('performance' in globalThis) ||\n (!process.env.NEXT_OTEL_PERFORMANCE_PREFIX && !isTracingEnabled)\n ) {\n return ComponentMod.__next_app__\n }\n\n return {\n require: (...args) => {\n const startTime = performance.now()\n\n if (clientComponentLoadStart === 0) {\n clientComponentLoadStart = startTime\n }\n\n try {\n clientComponentLoadCount += 1\n return ComponentMod.__next_app__.require(...args)\n } finally {\n clientComponentLoadTimes += performance.now() - startTime\n }\n },\n loadChunk: (...args) => {\n const startTime = performance.now()\n const result = ComponentMod.__next_app__.loadChunk(...args)\n // Avoid wrapping `loadChunk`'s result in an extra promise in case something like React depends on its identity.\n // We only need to know when it's settled.\n result.finally(() => {\n clientComponentLoadTimes += performance.now() - startTime\n })\n return result\n },\n }\n}\n\nexport function getClientComponentLoaderMetrics(\n options: { reset?: boolean } = {}\n) {\n const metrics =\n clientComponentLoadStart === 0\n ? undefined\n : {\n clientComponentLoadStart,\n clientComponentLoadTimes,\n clientComponentLoadCount,\n }\n\n if (options.reset) {\n clientComponentLoadStart = 0\n clientComponentLoadTimes = 0\n clientComponentLoadCount = 0\n }\n\n return metrics\n}\n"],"names":["clientComponentLoadStart","clientComponentLoadTimes","clientComponentLoadCount","wrapClientComponentLoader","ComponentMod","isTracingEnabled","globalThis","process","env","NEXT_OTEL_PERFORMANCE_PREFIX","__next_app__","require","args","startTime","performance","now","loadChunk","result","finally","getClientComponentLoaderMetrics","options","metrics","undefined","reset"],"mappings":"AAEA,oDAAoD;AACpD,IAAIA,2BAA2B;AAC/B,IAAIC,2BAA2B;AAC/B,IAAIC,2BAA2B;AAE/B,OAAO,SAASC,0BACdC,YAA2B,EAC3BC,gBAAyB;IAEzB,IACE,CAAE,CAAA,iBAAiBC,UAAS,KAC3B,CAACC,QAAQC,GAAG,CAACC,4BAA4B,IAAI,CAACJ,kBAC/C;QACA,OAAOD,aAAaM,YAAY;IAClC;IAEA,OAAO;QACLC,SAAS,CAAC,GAAGC;YACX,MAAMC,YAAYC,YAAYC,GAAG;YAEjC,IAAIf,6BAA6B,GAAG;gBAClCA,2BAA2Ba;YAC7B;YAEA,IAAI;gBACFX,4BAA4B;gBAC5B,OAAOE,aAAaM,YAAY,CAACC,OAAO,IAAIC;YAC9C,SAAU;gBACRX,4BAA4Ba,YAAYC,GAAG,KAAKF;YAClD;QACF;QACAG,WAAW,CAAC,GAAGJ;YACb,MAAMC,YAAYC,YAAYC,GAAG;YACjC,MAAME,SAASb,aAAaM,YAAY,CAACM,SAAS,IAAIJ;YACtD,gHAAgH;YAChH,0CAA0C;YAC1CK,OAAOC,OAAO,CAAC;gBACbjB,4BAA4Ba,YAAYC,GAAG,KAAKF;YAClD;YACA,OAAOI;QACT;IACF;AACF;AAEA,OAAO,SAASE,gCACdC,UAA+B,CAAC,CAAC;IAEjC,MAAMC,UACJrB,6BAA6B,IACzBsB,YACA;QACEtB;QACAC;QACAC;IACF;IAEN,IAAIkB,QAAQG,KAAK,EAAE;QACjBvB,2BAA2B;QAC3BC,2BAA2B;QAC3BC,2BAA2B;IAC7B;IAEA,OAAOmB;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/client-component-renderer-logger.ts"],"sourcesContent":["import type { AppPageModule } from './route-modules/app-page/module'\n\n// Combined load times for loading client components\nlet clientComponentLoadStart = 0\nlet clientComponentLoadEnd = 0\nlet clientComponentLoadTimes = 0\nlet clientComponentLoadCount = 0\n\nexport function wrapClientComponentLoader(\n ComponentMod: AppPageModule,\n isTracingEnabled: boolean\n): AppPageModule['__next_app__'] {\n if (\n !('performance' in globalThis) ||\n (!process.env.NEXT_OTEL_PERFORMANCE_PREFIX && !isTracingEnabled)\n ) {\n return ComponentMod.__next_app__\n }\n\n return {\n require: (...args) => {\n const startTime = performance.now()\n\n if (clientComponentLoadStart === 0) {\n clientComponentLoadStart = startTime\n }\n\n try {\n clientComponentLoadCount += 1\n return ComponentMod.__next_app__.require(...args)\n } finally {\n const endTime = performance.now()\n clientComponentLoadEnd = endTime\n clientComponentLoadTimes += endTime - startTime\n }\n },\n loadChunk: (...args) => {\n const startTime = performance.now()\n\n if (clientComponentLoadStart === 0) {\n clientComponentLoadStart = startTime\n }\n\n const result = ComponentMod.__next_app__.loadChunk(...args)\n // Avoid wrapping `loadChunk`'s result in an extra promise in case something like React depends on its identity.\n // We only need to know when it's settled.\n const onSettled = () => {\n const endTime = performance.now()\n clientComponentLoadEnd = endTime\n clientComponentLoadTimes += endTime - startTime\n }\n result.then(onSettled, onSettled)\n return result\n },\n }\n}\n\nexport function getClientComponentLoaderMetrics(\n options: { reset?: boolean } = {}\n) {\n const metrics =\n clientComponentLoadStart === 0\n ? undefined\n : {\n clientComponentLoadStart,\n clientComponentLoadEnd,\n clientComponentLoadTimes,\n clientComponentLoadCount,\n }\n\n if (options.reset) {\n clientComponentLoadStart = 0\n clientComponentLoadEnd = 0\n clientComponentLoadTimes = 0\n clientComponentLoadCount = 0\n }\n\n return metrics\n}\n"],"names":["clientComponentLoadStart","clientComponentLoadEnd","clientComponentLoadTimes","clientComponentLoadCount","wrapClientComponentLoader","ComponentMod","isTracingEnabled","globalThis","process","env","NEXT_OTEL_PERFORMANCE_PREFIX","__next_app__","require","args","startTime","performance","now","endTime","loadChunk","result","onSettled","then","getClientComponentLoaderMetrics","options","metrics","undefined","reset"],"mappings":"AAEA,oDAAoD;AACpD,IAAIA,2BAA2B;AAC/B,IAAIC,yBAAyB;AAC7B,IAAIC,2BAA2B;AAC/B,IAAIC,2BAA2B;AAE/B,OAAO,SAASC,0BACdC,YAA2B,EAC3BC,gBAAyB;IAEzB,IACE,CAAE,CAAA,iBAAiBC,UAAS,KAC3B,CAACC,QAAQC,GAAG,CAACC,4BAA4B,IAAI,CAACJ,kBAC/C;QACA,OAAOD,aAAaM,YAAY;IAClC;IAEA,OAAO;QACLC,SAAS,CAAC,GAAGC;YACX,MAAMC,YAAYC,YAAYC,GAAG;YAEjC,IAAIhB,6BAA6B,GAAG;gBAClCA,2BAA2Bc;YAC7B;YAEA,IAAI;gBACFX,4BAA4B;gBAC5B,OAAOE,aAAaM,YAAY,CAACC,OAAO,IAAIC;YAC9C,SAAU;gBACR,MAAMI,UAAUF,YAAYC,GAAG;gBAC/Bf,yBAAyBgB;gBACzBf,4BAA4Be,UAAUH;YACxC;QACF;QACAI,WAAW,CAAC,GAAGL;YACb,MAAMC,YAAYC,YAAYC,GAAG;YAEjC,IAAIhB,6BAA6B,GAAG;gBAClCA,2BAA2Bc;YAC7B;YAEA,MAAMK,SAASd,aAAaM,YAAY,CAACO,SAAS,IAAIL;YACtD,gHAAgH;YAChH,0CAA0C;YAC1C,MAAMO,YAAY;gBAChB,MAAMH,UAAUF,YAAYC,GAAG;gBAC/Bf,yBAAyBgB;gBACzBf,4BAA4Be,UAAUH;YACxC;YACAK,OAAOE,IAAI,CAACD,WAAWA;YACvB,OAAOD;QACT;IACF;AACF;AAEA,OAAO,SAASG,gCACdC,UAA+B,CAAC,CAAC;IAEjC,MAAMC,UACJxB,6BAA6B,IACzByB,YACA;QACEzB;QACAC;QACAC;QACAC;IACF;IAEN,IAAIoB,QAAQG,KAAK,EAAE;QACjB1B,2BAA2B;QAC3BC,yBAAyB;QACzBC,2BAA2B;QAC3BC,2BAA2B;IAC7B;IAEA,OAAOqB;AACT","ignoreList":[0]} |
@@ -7,2 +7,26 @@ import { Worker } from 'next/dist/compiled/jest-worker'; | ||
| /** | ||
| * Replays a change the dev server made to its own module state in the | ||
| * validation worker. Installed alongside the worker, so it is absent when no | ||
| * worker runs (`experimental.devValidationWorker: false`, or Webpack). | ||
| */ let mirrorModuleState; | ||
| /** | ||
| * Drops the validation worker. Called when the dev server cannot repair its own | ||
| * module state in place and re-evaluates every module from disk, which the | ||
| * worker matches by starting over: the next validation spawns a worker that | ||
| * loads the current build output. | ||
| * | ||
| * A worker dropped on its own, by a failed replay or a crash, is the one case | ||
| * where the two can diverge. The dev server keeps the modules it evaluated from | ||
| * earlier updates, and a worker spawned afterwards has no way to obtain those | ||
| * scripts, so frames naming them stay unresolved until those modules change | ||
| * again. The validation itself is unaffected, because the worker loads the | ||
| * current code from disk. | ||
| */ let dropWorker; | ||
| export function mirrorModuleStateToDevValidationWorker(change) { | ||
| mirrorModuleState == null ? void 0 : mirrorModuleState(change); | ||
| } | ||
| export function dropDevValidationWorker() { | ||
| dropWorker == null ? void 0 : dropWorker(); | ||
| } | ||
| /** | ||
| * Wire up the dev-server's validation worker: register the HMR teardown | ||
@@ -25,4 +49,35 @@ * listener and install the hook that `runDevValidationInBackground` calls once | ||
| // across independent requests (e.g. multiple tabs) show a validation-latency | ||
| // tail. | ||
| // tail. Raising it means `mirrorChange` has to reach every worker instead of | ||
| // whichever one the pool hands the call to, and the ordering it relies on | ||
| // holds per worker rather than across them. | ||
| let pool; | ||
| const mirrorChange = (change)=>{ | ||
| const current = pool; | ||
| if (!current) { | ||
| // No worker to keep current, and nothing to replay into a later one: the | ||
| // compilation that produced this change also wrote the updated chunk to | ||
| // disk, so a worker spawning after it reads the current code through | ||
| // `loadComponents`. Evaluating the update is what an isolate that is | ||
| // already running needs, not what a new one does. | ||
| return; | ||
| } | ||
| // The worker runs one call at a time, in the order the calls were made | ||
| // (see `numWorkers` below), so this is replayed before any validation | ||
| // requested after it, and never in the middle of one. That ordering is by | ||
| // call time, which is why the call is made here, as the change arrives, | ||
| // rather than deferred onto a queue of our own. A validation already | ||
| // queued runs first, which is what its render needs: it was produced | ||
| // before this change. The dev server does not hold its own updates back | ||
| // for a validation running in process either. | ||
| const replayed = change.type === 'invalidate' ? current.invalidateCaches(change.filePaths, change.evictModules) : current.applyHmrUpdate(change.update).then(async (outcome)=>{ | ||
| if (outcome === 'failed') { | ||
| await tearDownPool(); | ||
| } | ||
| }); | ||
| void replayed.catch(async ()=>{ | ||
| // A replay that failed leaves the worker's state unknown, so it is | ||
| // dropped rather than trusted. | ||
| await tearDownPool(); | ||
| }); | ||
| }; | ||
| const getPool = ()=>{ | ||
@@ -63,3 +118,5 @@ if (pool) { | ||
| exposedMethods: [ | ||
| 'runDevValidation' | ||
| 'runDevValidation', | ||
| 'applyHmrUpdate', | ||
| 'invalidateCaches' | ||
| ], | ||
@@ -141,9 +198,15 @@ forkOptions: { | ||
| }; | ||
| // The dev server can't reach into the worker to clear its `require.cache` or | ||
| // manifest caches, so we drop the worker whenever the parent's caches are | ||
| // invalidated (HMR, route recompile). The next validation lazy-spawns a fresh | ||
| // worker with empty caches. | ||
| onCacheInvalidation(()=>{ | ||
| // The dev server just cleared these paths from its own `require.cache` and | ||
| // manifest caches. The worker clears them from its copies. | ||
| onCacheInvalidation((filePaths)=>{ | ||
| mirrorChange({ | ||
| type: 'invalidate', | ||
| filePaths, | ||
| evictModules: true | ||
| }); | ||
| }); | ||
| mirrorModuleState = mirrorChange; | ||
| dropWorker = ()=>{ | ||
| void tearDownPool(); | ||
| }); | ||
| }; | ||
| setDevValidationWorker(runValidation); | ||
@@ -150,0 +213,0 @@ } |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/dev/dev-validation-worker-pool.ts"],"sourcesContent":["import type { NextConfigComplete } from '../config-shared'\nimport type { runDevValidation } from './dev-validation-worker'\nimport type {\n DevValidationSnapshot,\n DevValidationWorkerMessage,\n DevValidationWorkerResult,\n} from '../app-render/dev-validation-worker-globals'\n\nimport { Worker } from 'next/dist/compiled/jest-worker'\nimport { setDevValidationWorker } from '../app-render/dev-validation-worker-globals'\nimport { onCacheInvalidation } from './require-cache'\nimport { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'\nimport { needsExperimentalReact } from '../../lib/needs-experimental-react'\n\ninterface InstallOptions {\n distDir: string\n buildId: string\n deploymentId: string\n nextConfig: NextConfigComplete\n}\n\ntype ValidationPool = { [key: string]: any } & {\n runDevValidation: typeof runDevValidation\n}\n\n/**\n * Wire up the dev-server's validation worker: register the HMR teardown\n * listener and install the hook that `runDevValidationInBackground` calls once\n * a render has settled. The worker thread is spawned lazily, so nothing is\n * created until the first navigation actually validates.\n */\nexport function installDevValidationWorker(options: InstallOptions): void {\n const { distDir, buildId, deploymentId, nextConfig } = options\n\n // A single worker, not a pool. Validation for one navigation runs its depth\n // loop sequentially, and a newer navigation supersedes the previous one\n // (aborting it mid-run) rather than running concurrently, so there's no\n // per-request fan-out to parallelize (unlike the `'use cache'` probe, where\n // one request fans out into concurrent probes). One worker already frees the\n // main thread, which is the whole point; it also keeps each request's CLI\n // marker block contiguous in the piped output. Torn down on HMR (stale user\n // modules) and on crash.\n //\n // TODO(dev-validation-worker): raise `numWorkers` if concurrent navigations\n // across independent requests (e.g. multiple tabs) show a validation-latency\n // tail.\n let pool: ValidationPool | undefined\n\n const getPool = (): ValidationPool => {\n if (pool) {\n return pool\n }\n // Strip `--inspect` from any inherited `NODE_OPTIONS` so the worker doesn't\n // fight the parent for the same debug port.\n const workerNodeOptions = getFormattedNodeOptionsWithoutInspect()\n\n // The worker is shipped as four pre-bundled dev-only artifacts\n // ({webpack,turbopack} × {stable,experimental}), one per combination of the\n // user's bundler and vendored React channel. Pick the matching artifact\n // from runtime env so the worker stays in lockstep with the user's app\n // bundle. `needsExperimentalReact` is the same predicate `define-env.ts`\n // uses to wire `__NEXT_EXPERIMENTAL_REACT`.\n const turbo = process.env.TURBOPACK ? '-turbo' : ''\n const channel = needsExperimentalReact(nextConfig) ? '-experimental' : ''\n const workerPath = require.resolve(\n `next/dist/compiled/next-server/dev-validation-worker${turbo}${channel}.runtime.dev.js`\n )\n\n const worker = new Worker(workerPath, {\n maxRetries: 0,\n numWorkers: 1,\n // Always worker-threads, regardless of `experimental.workerThreads`.\n // Unlike the `'use cache'` probe (which follows the flag), validation has\n // no reason to prefer a child process: it doesn't need process-level\n // isolation (a worker thread already has its own V8 heap and module\n // registry, so the reloaded route is isolated from the main thread), and\n // threads let a superseded validation be aborted mid-run through a shared\n // `SharedArrayBuffer`, which a separate process can't receive. Threads\n // also carry the transported Flight bytes as typed arrays via structured\n // clone, with no JSON round-trip to corrupt them.\n enableWorkerThreads: true,\n // Listing the method explicitly tells jest-worker to skip the discovery\n // `require()` it would otherwise do in the parent process to enumerate\n // the module's exports. This worker's top-level imports (`require-hook`,\n // `node-environment`) run runtime setup meant only for the isolated\n // worker thread, so they must not be evaluated in the parent.\n exposedMethods: ['runDevValidation'],\n forkOptions: {\n env: {\n ...process.env,\n NODE_OPTIONS: workerNodeOptions,\n },\n },\n }) as Worker & ValidationPool\n worker.getStdout().pipe(process.stdout)\n worker.getStderr().pipe(process.stderr)\n pool = worker\n return worker\n }\n\n const tearDownPool = async (): Promise<void> => {\n const current = pool\n if (!current) {\n return\n }\n pool = undefined\n await current.end().catch(() => {\n // The worker thread exits on its own once its work settles; a failed\n // `.end()` here just means we couldn't wait for it cleanly.\n })\n }\n\n const runValidation = async (\n snapshot: DevValidationSnapshot,\n validationAbortSignal: AbortSignal\n ): Promise<DevValidationWorkerResult> => {\n let activePool: ValidationPool\n try {\n activePool = getPool()\n } catch {\n return null\n }\n\n const message: DevValidationWorkerMessage = {\n ...snapshot,\n distDir,\n buildId,\n deploymentId,\n nextConfigSerializable: {\n httpAgentOptions: nextConfig.httpAgentOptions,\n cacheLifeProfiles: nextConfig.cacheLife,\n useCacheTimeout: nextConfig.experimental.useCacheTimeout,\n staticPageGenerationTimeout: nextConfig.staticPageGenerationTimeout,\n },\n }\n\n // The worker runs as a thread (see `enableWorkerThreads` above), so an\n // abort reaches it through a one-slot shared flag rather than the abort\n // signal directly (a signal can't cross the thread boundary). Mirror an\n // abort of `validationAbortSignal` into the buffer and wake the worker's\n // `Atomics.waitAsync` on it, so it aborts the in-flight run at its next\n // depth boundary.\n const abortBuffer = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)\n const abortFlag = new Int32Array(abortBuffer)\n const propagateAbort = () => {\n Atomics.store(abortFlag, 0, 1)\n Atomics.notify(abortFlag, 0)\n }\n if (validationAbortSignal.aborted) {\n propagateAbort()\n } else {\n validationAbortSignal.addEventListener('abort', propagateAbort, {\n once: true,\n })\n }\n\n try {\n return await activePool.runDevValidation(message, abortBuffer)\n } catch {\n // Worker crash or IPC error: tear down so the next validation starts\n // fresh. The main thread treats a missing result as \"nothing to deliver.\"\n await tearDownPool()\n return null\n } finally {\n // `once` only auto-removes the listener if it fired, so remove it\n // explicitly to bound its lifetime to this run when validation completed\n // without being superseded.\n validationAbortSignal.removeEventListener('abort', propagateAbort)\n }\n }\n\n // The dev server can't reach into the worker to clear its `require.cache` or\n // manifest caches, so we drop the worker whenever the parent's caches are\n // invalidated (HMR, route recompile). The next validation lazy-spawns a fresh\n // worker with empty caches.\n onCacheInvalidation(() => {\n void tearDownPool()\n })\n\n setDevValidationWorker(runValidation)\n}\n"],"names":["Worker","setDevValidationWorker","onCacheInvalidation","getFormattedNodeOptionsWithoutInspect","needsExperimentalReact","installDevValidationWorker","options","distDir","buildId","deploymentId","nextConfig","pool","getPool","workerNodeOptions","turbo","process","env","TURBOPACK","channel","workerPath","require","resolve","worker","maxRetries","numWorkers","enableWorkerThreads","exposedMethods","forkOptions","NODE_OPTIONS","getStdout","pipe","stdout","getStderr","stderr","tearDownPool","current","undefined","end","catch","runValidation","snapshot","validationAbortSignal","activePool","message","nextConfigSerializable","httpAgentOptions","cacheLifeProfiles","cacheLife","useCacheTimeout","experimental","staticPageGenerationTimeout","abortBuffer","SharedArrayBuffer","Int32Array","BYTES_PER_ELEMENT","abortFlag","propagateAbort","Atomics","store","notify","aborted","addEventListener","once","runDevValidation","removeEventListener"],"mappings":"AAQA,SAASA,MAAM,QAAQ,iCAAgC;AACvD,SAASC,sBAAsB,QAAQ,8CAA6C;AACpF,SAASC,mBAAmB,QAAQ,kBAAiB;AACrD,SAASC,qCAAqC,QAAQ,eAAc;AACpE,SAASC,sBAAsB,QAAQ,qCAAoC;AAa3E;;;;;CAKC,GACD,OAAO,SAASC,2BAA2BC,OAAuB;IAChE,MAAM,EAAEC,OAAO,EAAEC,OAAO,EAAEC,YAAY,EAAEC,UAAU,EAAE,GAAGJ;IAEvD,4EAA4E;IAC5E,wEAAwE;IACxE,wEAAwE;IACxE,4EAA4E;IAC5E,6EAA6E;IAC7E,0EAA0E;IAC1E,4EAA4E;IAC5E,yBAAyB;IACzB,EAAE;IACF,4EAA4E;IAC5E,6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;YACN,OAAO;QACT;QAEA,MAAM+B,UAAsC;YAC1C,GAAGH,QAAQ;YACXjC;YACAC;YACAC;YACAmC,wBAAwB;gBACtBC,kBAAkBnC,WAAWmC,gBAAgB;gBAC7CC,mBAAmBpC,WAAWqC,SAAS;gBACvCC,iBAAiBtC,WAAWuC,YAAY,CAACD,eAAe;gBACxDE,6BAA6BxC,WAAWwC,2BAA2B;YACrE;QACF;QAEA,uEAAuE;QACvE,wEAAwE;QACxE,wEAAwE;QACxE,yEAAyE;QACzE,wEAAwE;QACxE,kBAAkB;QAClB,MAAMC,cAAc,IAAIC,kBAAkBC,WAAWC,iBAAiB;QACtE,MAAMC,YAAY,IAAIF,WAAWF;QACjC,MAAMK,iBAAiB;YACrBC,QAAQC,KAAK,CAACH,WAAW,GAAG;YAC5BE,QAAQE,MAAM,CAACJ,WAAW;QAC5B;QACA,IAAId,sBAAsBmB,OAAO,EAAE;YACjCJ;QACF,OAAO;YACLf,sBAAsBoB,gBAAgB,CAAC,SAASL,gBAAgB;gBAC9DM,MAAM;YACR;QACF;QAEA,IAAI;YACF,OAAO,MAAMpB,WAAWqB,gBAAgB,CAACpB,SAASQ;QACpD,EAAE,OAAM;YACN,qEAAqE;YACrE,0EAA0E;YAC1E,MAAMjB;YACN,OAAO;QACT,SAAU;YACR,kEAAkE;YAClE,yEAAyE;YACzE,4BAA4B;YAC5BO,sBAAsBuB,mBAAmB,CAAC,SAASR;QACrD;IACF;IAEA,6EAA6E;IAC7E,0EAA0E;IAC1E,8EAA8E;IAC9E,4BAA4B;IAC5BtD,oBAAoB;QAClB,KAAKgC;IACP;IAEAjC,uBAAuBsC;AACzB","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/dev/dev-validation-worker-pool.ts"],"sourcesContent":["import type { NextConfigComplete } from '../config-shared'\nimport type { NodeJsPartialHmrUpdate } from '../../build/swc/types'\nimport type {\n applyHmrUpdate,\n invalidateCaches,\n runDevValidation,\n} from './dev-validation-worker'\nimport type {\n DevValidationSnapshot,\n DevValidationWorkerMessage,\n DevValidationWorkerResult,\n} from '../app-render/dev-validation-worker-globals'\n\nimport { Worker } from 'next/dist/compiled/jest-worker'\nimport { setDevValidationWorker } from '../app-render/dev-validation-worker-globals'\nimport { onCacheInvalidation } from './require-cache'\nimport { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'\nimport { needsExperimentalReact } from '../../lib/needs-experimental-react'\n\ninterface InstallOptions {\n distDir: string\n buildId: string\n deploymentId: string\n nextConfig: NextConfigComplete\n}\n\ntype ValidationPool = { [key: string]: any } & {\n runDevValidation: typeof runDevValidation\n applyHmrUpdate: typeof applyHmrUpdate\n invalidateCaches: typeof invalidateCaches\n}\n\n/**\n * One change the dev server made to its own module state — the modules it has\n * loaded, and the manifest caches that describe them.\n *\n * The worker holds the same state, seeded from the same build output, and\n * replays every change the dev server reports, so its state is the dev server's\n * state by construction.\n */\ntype DevModuleStateChange =\n | { type: 'apply'; update: NodeJsPartialHmrUpdate }\n | { type: 'invalidate'; filePaths: string[]; evictModules: boolean }\n\n/**\n * Replays a change the dev server made to its own module state in the\n * validation worker. Installed alongside the worker, so it is absent when no\n * worker runs (`experimental.devValidationWorker: false`, or Webpack).\n */\nlet mirrorModuleState: ((change: DevModuleStateChange) => void) | undefined\n\n/**\n * Drops the validation worker. Called when the dev server cannot repair its own\n * module state in place and re-evaluates every module from disk, which the\n * worker matches by starting over: the next validation spawns a worker that\n * loads the current build output.\n *\n * A worker dropped on its own, by a failed replay or a crash, is the one case\n * where the two can diverge. The dev server keeps the modules it evaluated from\n * earlier updates, and a worker spawned afterwards has no way to obtain those\n * scripts, so frames naming them stay unresolved until those modules change\n * again. The validation itself is unaffected, because the worker loads the\n * current code from disk.\n */\nlet dropWorker: (() => void) | undefined\n\nexport function mirrorModuleStateToDevValidationWorker(\n change: DevModuleStateChange\n): void {\n mirrorModuleState?.(change)\n}\n\nexport function dropDevValidationWorker(): void {\n dropWorker?.()\n}\n\n/**\n * Wire up the dev-server's validation worker: register the HMR teardown\n * listener and install the hook that `runDevValidationInBackground` calls once\n * a render has settled. The worker thread is spawned lazily, so nothing is\n * created until the first navigation actually validates.\n */\nexport function installDevValidationWorker(options: InstallOptions): void {\n const { distDir, buildId, deploymentId, nextConfig } = options\n\n // A single worker, not a pool. Validation for one navigation runs its depth\n // loop sequentially, and a newer navigation supersedes the previous one\n // (aborting it mid-run) rather than running concurrently, so there's no\n // per-request fan-out to parallelize (unlike the `'use cache'` probe, where\n // one request fans out into concurrent probes). One worker already frees the\n // main thread, which is the whole point; it also keeps each request's CLI\n // marker block contiguous in the piped output. Torn down on HMR (stale user\n // modules) and on crash.\n //\n // TODO(dev-validation-worker): raise `numWorkers` if concurrent navigations\n // across independent requests (e.g. multiple tabs) show a validation-latency\n // tail. Raising it means `mirrorChange` has to reach every worker instead of\n // whichever one the pool hands the call to, and the ordering it relies on\n // holds per worker rather than across them.\n let pool: ValidationPool | undefined\n\n const mirrorChange = (change: DevModuleStateChange): void => {\n const current = pool\n if (!current) {\n // No worker to keep current, and nothing to replay into a later one: the\n // compilation that produced this change also wrote the updated chunk to\n // disk, so a worker spawning after it reads the current code through\n // `loadComponents`. Evaluating the update is what an isolate that is\n // already running needs, not what a new one does.\n return\n }\n\n // The worker runs one call at a time, in the order the calls were made\n // (see `numWorkers` below), so this is replayed before any validation\n // requested after it, and never in the middle of one. That ordering is by\n // call time, which is why the call is made here, as the change arrives,\n // rather than deferred onto a queue of our own. A validation already\n // queued runs first, which is what its render needs: it was produced\n // before this change. The dev server does not hold its own updates back\n // for a validation running in process either.\n const replayed =\n change.type === 'invalidate'\n ? current.invalidateCaches(change.filePaths, change.evictModules)\n : current.applyHmrUpdate(change.update).then(async (outcome) => {\n if (outcome === 'failed') {\n await tearDownPool()\n }\n })\n\n void replayed.catch(async () => {\n // A replay that failed leaves the worker's state unknown, so it is\n // dropped rather than trusted.\n await tearDownPool()\n })\n }\n\n const getPool = (): ValidationPool => {\n if (pool) {\n return pool\n }\n // Strip `--inspect` from any inherited `NODE_OPTIONS` so the worker doesn't\n // fight the parent for the same debug port.\n const workerNodeOptions = getFormattedNodeOptionsWithoutInspect()\n\n // The worker is shipped as four pre-bundled dev-only artifacts\n // ({webpack,turbopack} × {stable,experimental}), one per combination of the\n // user's bundler and vendored React channel. Pick the matching artifact\n // from runtime env so the worker stays in lockstep with the user's app\n // bundle. `needsExperimentalReact` is the same predicate `define-env.ts`\n // uses to wire `__NEXT_EXPERIMENTAL_REACT`.\n const turbo = process.env.TURBOPACK ? '-turbo' : ''\n const channel = needsExperimentalReact(nextConfig) ? '-experimental' : ''\n const workerPath = require.resolve(\n `next/dist/compiled/next-server/dev-validation-worker${turbo}${channel}.runtime.dev.js`\n )\n\n const worker = new Worker(workerPath, {\n maxRetries: 0,\n numWorkers: 1,\n // Always worker-threads, regardless of `experimental.workerThreads`.\n // Unlike the `'use cache'` probe (which follows the flag), validation has\n // no reason to prefer a child process: it doesn't need process-level\n // isolation (a worker thread already has its own V8 heap and module\n // registry, so the reloaded route is isolated from the main thread), and\n // threads let a superseded validation be aborted mid-run through a shared\n // `SharedArrayBuffer`, which a separate process can't receive. Threads\n // also carry the transported Flight bytes as typed arrays via structured\n // clone, with no JSON round-trip to corrupt them.\n enableWorkerThreads: true,\n // Listing the method explicitly tells jest-worker to skip the discovery\n // `require()` it would otherwise do in the parent process to enumerate\n // the module's exports. This worker's top-level imports (`require-hook`,\n // `node-environment`) run runtime setup meant only for the isolated\n // worker thread, so they must not be evaluated in the parent.\n exposedMethods: [\n 'runDevValidation',\n 'applyHmrUpdate',\n 'invalidateCaches',\n ],\n forkOptions: {\n env: {\n ...process.env,\n NODE_OPTIONS: workerNodeOptions,\n },\n },\n }) as Worker & ValidationPool\n worker.getStdout().pipe(process.stdout)\n worker.getStderr().pipe(process.stderr)\n pool = worker\n return worker\n }\n\n const tearDownPool = async (): Promise<void> => {\n const current = pool\n if (!current) {\n return\n }\n pool = undefined\n await current.end().catch(() => {\n // The worker thread exits on its own once its work settles; a failed\n // `.end()` here just means we couldn't wait for it cleanly.\n })\n }\n\n const runValidation = async (\n snapshot: DevValidationSnapshot,\n validationAbortSignal: AbortSignal\n ): Promise<DevValidationWorkerResult> => {\n let activePool: ValidationPool\n try {\n activePool = getPool()\n } catch {\n return null\n }\n\n const message: DevValidationWorkerMessage = {\n ...snapshot,\n distDir,\n buildId,\n deploymentId,\n nextConfigSerializable: {\n httpAgentOptions: nextConfig.httpAgentOptions,\n cacheLifeProfiles: nextConfig.cacheLife,\n useCacheTimeout: nextConfig.experimental.useCacheTimeout,\n staticPageGenerationTimeout: nextConfig.staticPageGenerationTimeout,\n },\n }\n\n // The worker runs as a thread (see `enableWorkerThreads` above), so an\n // abort reaches it through a one-slot shared flag rather than the abort\n // signal directly (a signal can't cross the thread boundary). Mirror an\n // abort of `validationAbortSignal` into the buffer and wake the worker's\n // `Atomics.waitAsync` on it, so it aborts the in-flight run at its next\n // depth boundary.\n const abortBuffer = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)\n const abortFlag = new Int32Array(abortBuffer)\n const propagateAbort = () => {\n Atomics.store(abortFlag, 0, 1)\n Atomics.notify(abortFlag, 0)\n }\n if (validationAbortSignal.aborted) {\n propagateAbort()\n } else {\n validationAbortSignal.addEventListener('abort', propagateAbort, {\n once: true,\n })\n }\n\n try {\n return await activePool.runDevValidation(message, abortBuffer)\n } catch {\n // Worker crash or IPC error: tear down so the next validation starts\n // fresh. The main thread treats a missing result as \"nothing to deliver.\"\n await tearDownPool()\n return null\n } finally {\n // `once` only auto-removes the listener if it fired, so remove it\n // explicitly to bound its lifetime to this run when validation completed\n // without being superseded.\n validationAbortSignal.removeEventListener('abort', propagateAbort)\n }\n }\n\n // The dev server just cleared these paths from its own `require.cache` and\n // manifest caches. The worker clears them from its copies.\n onCacheInvalidation((filePaths) => {\n mirrorChange({\n type: 'invalidate',\n filePaths,\n evictModules: true,\n })\n })\n\n mirrorModuleState = mirrorChange\n dropWorker = () => {\n void tearDownPool()\n }\n\n setDevValidationWorker(runValidation)\n}\n"],"names":["Worker","setDevValidationWorker","onCacheInvalidation","getFormattedNodeOptionsWithoutInspect","needsExperimentalReact","mirrorModuleState","dropWorker","mirrorModuleStateToDevValidationWorker","change","dropDevValidationWorker","installDevValidationWorker","options","distDir","buildId","deploymentId","nextConfig","pool","mirrorChange","current","replayed","type","invalidateCaches","filePaths","evictModules","applyHmrUpdate","update","then","outcome","tearDownPool","catch","getPool","workerNodeOptions","turbo","process","env","TURBOPACK","channel","workerPath","require","resolve","worker","maxRetries","numWorkers","enableWorkerThreads","exposedMethods","forkOptions","NODE_OPTIONS","getStdout","pipe","stdout","getStderr","stderr","undefined","end","runValidation","snapshot","validationAbortSignal","activePool","message","nextConfigSerializable","httpAgentOptions","cacheLifeProfiles","cacheLife","useCacheTimeout","experimental","staticPageGenerationTimeout","abortBuffer","SharedArrayBuffer","Int32Array","BYTES_PER_ELEMENT","abortFlag","propagateAbort","Atomics","store","notify","aborted","addEventListener","once","runDevValidation","removeEventListener"],"mappings":"AAaA,SAASA,MAAM,QAAQ,iCAAgC;AACvD,SAASC,sBAAsB,QAAQ,8CAA6C;AACpF,SAASC,mBAAmB,QAAQ,kBAAiB;AACrD,SAASC,qCAAqC,QAAQ,eAAc;AACpE,SAASC,sBAAsB,QAAQ,qCAAoC;AA2B3E;;;;CAIC,GACD,IAAIC;AAEJ;;;;;;;;;;;;CAYC,GACD,IAAIC;AAEJ,OAAO,SAASC,uCACdC,MAA4B;IAE5BH,qCAAAA,kBAAoBG;AACtB;AAEA,OAAO,SAASC;IACdH,8BAAAA;AACF;AAEA;;;;;CAKC,GACD,OAAO,SAASI,2BAA2BC,OAAuB;IAChE,MAAM,EAAEC,OAAO,EAAEC,OAAO,EAAEC,YAAY,EAAEC,UAAU,EAAE,GAAGJ;IAEvD,4EAA4E;IAC5E,wEAAwE;IACxE,wEAAwE;IACxE,4EAA4E;IAC5E,6EAA6E;IAC7E,0EAA0E;IAC1E,4EAA4E;IAC5E,yBAAyB;IAC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QACF,OAAO;YACLf,sBAAsBoB,gBAAgB,CAAC,SAASL,gBAAgB;gBAC9DM,MAAM;YACR;QACF;QAEA,IAAI;YACF,OAAO,MAAMpB,WAAWqB,gBAAgB,CAACpB,SAASQ;QACpD,EAAE,OAAM;YACN,qEAAqE;YACrE,0EAA0E;YAC1E,MAAMtC;YACN,OAAO;QACT,SAAU;YACR,kEAAkE;YAClE,yEAAyE;YACzE,4BAA4B;YAC5B4B,sBAAsBuB,mBAAmB,CAAC,SAASR;QACrD;IACF;IAEA,2EAA2E;IAC3E,2DAA2D;IAC3DrE,oBAAoB,CAACoB;QACnBL,aAAa;YACXG,MAAM;YACNE;YACAC,cAAc;QAChB;IACF;IAEAlB,oBAAoBY;IACpBX,aAAa;QACX,KAAKsB;IACP;IAEA3B,uBAAuBqD;AACzB","ignoreList":[0]} |
@@ -12,2 +12,4 @@ import '../require-hook'; | ||
| import { formatValidationEvent } from '../app-render/dev-validation-events'; | ||
| import { clearManifestCache } from '../load-manifest.external'; | ||
| import { deleteCache } from './require-cache'; | ||
| import { getServerActionsManifest, setManifestsSingleton } from '../app-render/manifests-singleton'; | ||
@@ -27,7 +29,8 @@ import { setBundlerFindSourceMapImplementation } from '../patch-error-inspect'; | ||
| * | ||
| * This only helps Turbopack, which writes a `.map` beside every chunk. Webpack | ||
| * keeps its dev source maps in the compiler rather than on disk, so its frames | ||
| * from chunks this thread never evaluated stay unresolved, and its module URLs | ||
| * (`webpack-internal://…`) are declined below for the same reason. Frames from | ||
| * dependencies that are not bundled never reach this point, because | ||
| * Reading from disk covers the chunks, because the worker only runs under | ||
| * Turbopack (see `next-dev-server.ts`), which writes a `.map` beside every one | ||
| * of them. A module the server updated in place has no chunk of its own and is | ||
| * covered instead by this thread applying the same update (see | ||
| * `applyHmrUpdate`), which leaves its inline map in Node.js' cache here. Frames | ||
| * from dependencies that are not bundled never reach this point, because | ||
| * `filterStackFrameDEV` drops `node_modules` and `node:` frames; bundled | ||
@@ -54,3 +57,3 @@ * dependencies appear as chunks inside `distDir` like any other code. | ||
| if (!isAbsolute(chunkPath)) { | ||
| // Not an emitted chunk, e.g. `webpack-internal://` or `<anonymous>`. | ||
| // Not an emitted chunk, e.g. `<anonymous>`. | ||
| return undefined; | ||
@@ -184,2 +187,41 @@ } | ||
| /** | ||
| * Applies a server HMR update to this thread's module registry, mirroring the | ||
| * apply the dev server performed on its own. | ||
| * | ||
| * Turbopack's Node.js runtime registers the apply machinery per isolate (see | ||
| * `dev-nodejs.ts`), and `loadComponents` evaluates that runtime here, so this | ||
| * thread patches the same modules the dev server does. The apply also leaves | ||
| * the updated module's inline source map in this thread's Node.js cache, which | ||
| * is what makes a stack frame in that module source-mappable here. | ||
| */ export async function applyHmrUpdate(update) { | ||
| if (typeof __turbopack_server_hmr_apply__ !== 'function') { | ||
| return 'no-runtime'; | ||
| } | ||
| try { | ||
| __turbopack_server_hmr_apply__(update); | ||
| } catch { | ||
| // The dev server responds to the same failure by re-evaluating every | ||
| // module from disk. This thread cannot be repaired in place either, so the | ||
| // caller drops it. | ||
| return 'failed'; | ||
| } | ||
| return 'applied'; | ||
| } | ||
| /** | ||
| * Clears the same caches the dev server cleared, for the same paths. | ||
| * | ||
| * `evictModules` follows the dev server's own split: an applied update patches | ||
| * modules in place and clears only the manifest cache for the updated chunks, | ||
| * while a recompile evicts `require.cache` as well. This thread follows both, | ||
| * so its module state stays the dev server's module state. | ||
| */ export async function invalidateCaches(filePaths, evictModules) { | ||
| if (evictModules) { | ||
| deleteCache(filePaths); | ||
| return; | ||
| } | ||
| for (const filePath of filePaths){ | ||
| clearManifestCache(filePath); | ||
| } | ||
| } | ||
| /** | ||
| * Runs the dev instant/static-shell validation passes off the main thread. | ||
@@ -186,0 +228,0 @@ * Reloads the route's compiled module, then delegates the whole validation to |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/dev/dev-validation-worker.ts"],"sourcesContent":["import type { AppPageModule } from '../route-modules/app-page/module'\nimport type {\n DevValidationWorkerMessage,\n DevValidationWorkerResult,\n} from '../app-render/dev-validation-worker-globals'\n\nimport '../require-hook'\nimport '../node-environment'\n\nimport { isAbsolute, relative } from 'path'\nimport { readFileSync, realpathSync } from 'fs'\nimport { fileURLToPath } from 'url'\nimport { installBindings } from '../../build/swc/install-bindings'\nimport { installCodeFrameSupport } from '../lib/install-code-frame'\nimport {\n loadClientReferenceManifestForPage,\n loadComponents,\n} from '../load-components'\nimport { setHttpClientAndAgentOptions } from '../setup-http-agent-env'\nimport { serializeValidationErrorsToFlight } from '../app-render/dev-validation-error-delivery'\nimport { formatValidationEvent } from '../app-render/dev-validation-events'\nimport {\n getServerActionsManifest,\n setManifestsSingleton,\n} from '../app-render/manifests-singleton'\nimport { setBundlerFindSourceMapImplementation } from '../patch-error-inspect'\nimport type { ModernSourceMapPayload } from '../lib/source-maps'\n\n/**\n * Resolves a chunk's source map by reading the `.map` file the bundler emitted\n * next to it, for chunks inside `distDir`.\n *\n * The main thread answers the same question through the Turbopack project\n * handle, which cannot cross a thread boundary. Reading from disk is\n * project-free and, more importantly, does not depend on the chunk having been\n * evaluated in this thread: Node.js caches source maps per isolate, and the\n * worker never renders server components, so it holds maps only for the chunks\n * `loadComponents` pulled in. Frames arriving in the transported payload can\n * point at any chunk the main render touched.\n *\n * This only helps Turbopack, which writes a `.map` beside every chunk. Webpack\n * keeps its dev source maps in the compiler rather than on disk, so its frames\n * from chunks this thread never evaluated stay unresolved, and its module URLs\n * (`webpack-internal://…`) are declined below for the same reason. Frames from\n * dependencies that are not bundled never reach this point, because\n * `filterStackFrameDEV` drops `node_modules` and `node:` frames; bundled\n * dependencies appear as chunks inside `distDir` like any other code.\n */\nfunction createDiskSourceMapLookup(\n distDir: string\n): (sourceURL: string) => ModernSourceMapPayload | undefined {\n // The frames carry resolved paths, so compare against the resolved `distDir`\n // to keep the containment check meaningful when the project sits behind a\n // symlink.\n let canonicalDistDir = distDir\n try {\n canonicalDistDir = realpathSync(distDir)\n } catch {}\n\n const payloads = new Map<string, ModernSourceMapPayload | undefined>()\n\n return function findSourceMapPayloadOnDisk(sourceURL) {\n let chunkPath = sourceURL\n\n if (chunkPath.startsWith('file://')) {\n try {\n chunkPath = fileURLToPath(chunkPath)\n } catch {\n return undefined\n }\n }\n\n if (!isAbsolute(chunkPath)) {\n // Not an emitted chunk, e.g. `webpack-internal://` or `<anonymous>`.\n return undefined\n }\n\n const cached = payloads.get(chunkPath)\n if (cached !== undefined || payloads.has(chunkPath)) {\n return cached\n }\n\n let payload: ModernSourceMapPayload | undefined\n const relativePath = relative(canonicalDistDir, chunkPath)\n\n // Only chunks emitted into `distDir` have a source map to point at, and\n // this keeps the lookup from reading arbitrary paths off disk.\n if (!relativePath.startsWith('..') && !isAbsolute(relativePath)) {\n try {\n payload = JSON.parse(readFileSync(chunkPath + '.map', 'utf8'))\n } catch {\n payload = undefined\n }\n }\n\n payloads.set(chunkPath, payload)\n\n return payload\n }\n}\n\n// Match the main dev server (`next-dev-server.ts`), which raises this so the\n// server captures deeper stacks. React's owner-stack capture during the\n// validation prerenders depends on it, so without it the worker's errors lose\n// their owner-stack source attribution.\ntry {\n Error.stackTraceLimit = 50\n} catch {}\n\n// The lifecycle markers E2E tests read from the CLI. Emitted on the worker's\n// stdout (piped to the parent) so they interleave with the parent's captured\n// output the same way the in-process `runWithDevValidationLogging` markers do.\n// Gated on the same test env that path checks.\nconst isTestLoggingEnabled = !!(\n process.env.__NEXT_TEST_MODE && process.env.NEXT_TEST_LOG_VALIDATION\n)\n\n/**\n * Adapts the pool's supersede flag into an `AbortSignal` the validation passes\n * check at their depth/yield boundaries. The pool shares an `Int32Array`-backed\n * `SharedArrayBuffer` whose first slot the main thread flips to non-zero (with\n * `Atomics.store` + `Atomics.notify`) when a newer navigation supersedes this\n * one. We wait for that notification with `Atomics.waitAsync`, which is\n * event-driven rather than polled. A validation that finishes without being\n * superseded calls `cleanup()`, which wakes our own still-pending wait so it\n * leaves no waiter (and no retained buffer) behind.\n */\nfunction createSupersedeSignal(abortBuffer: SharedArrayBuffer): {\n signal: AbortSignal\n cleanup: () => void\n} {\n const controller = new AbortController()\n const flag = new Int32Array(abortBuffer)\n\n if (Atomics.load(flag, 0) !== 0) {\n controller.abort()\n return { signal: controller.signal, cleanup: () => {} }\n }\n\n let settled = false\n const wait = Atomics.waitAsync(flag, 0, 0)\n if (wait.async) {\n wait.value.then(() => {\n if (settled) {\n return\n }\n settled = true\n // Woken either by a real supersede or by `cleanup()`; only the former\n // leaves the flag set.\n if (Atomics.load(flag, 0) !== 0) {\n controller.abort()\n }\n })\n } else if (Atomics.load(flag, 0) !== 0) {\n // The flag flipped between the load above and the wait.\n controller.abort()\n }\n\n return {\n signal: controller.signal,\n cleanup: () => {\n if (!settled) {\n Atomics.notify(flag, 0)\n }\n },\n }\n}\n\n/**\n * Waits out the test-only validation delay, resolving early if the render is\n * superseded. Mirrors the delay in `runWithDevValidationLogging` so scheduler\n * tests observe the same in-flight window on the worker path.\n */\nasync function applyTestValidationDelay(signal: AbortSignal): Promise<void> {\n const delayMs = Number(process.env.NEXT_TEST_DEV_VALIDATION_DELAY_MS)\n if (!Number.isFinite(delayMs) || delayMs <= 0 || signal.aborted) {\n return\n }\n\n await new Promise<void>((resolve) => {\n const finishDelay = () => {\n clearTimeout(timeout)\n signal.removeEventListener('abort', finishDelay)\n resolve()\n }\n const timeout = setTimeout(finishDelay, delayMs)\n signal.addEventListener('abort', finishDelay, { once: true })\n })\n}\n\n/**\n * Registers the client reference manifests of the pages that supplied client\n * references to the render being validated, beyond the validated route's own\n * manifest. This thread has its own manifests singleton, which `loadComponents`\n * seeds with only the validated route, so without these the dev-only cross-page\n * lookup in `createProxiedClientReferenceManifest` has no other manifest to\n * search and decoding the transported payload fails. Usually a no-op, since the\n * main thread only records a page when React's I/O tracking actually carried a\n * reference across pages.\n */\nasync function registerAdditionalClientReferenceManifests(\n distDir: string,\n pages: string[]\n): Promise<void> {\n if (pages.length === 0) {\n return\n }\n\n // Set by `loadComponents`. One server actions manifest covers the whole app,\n // so the pages registered here share the validated route's.\n const serverActionsManifest = getServerActionsManifest()\n\n await Promise.all(\n pages.map(async (page) => {\n const clientReferenceManifest = await loadClientReferenceManifestForPage(\n distDir,\n page\n )\n\n if (clientReferenceManifest) {\n setManifestsSingleton({\n page,\n clientReferenceManifest,\n serverActionsManifest,\n })\n }\n })\n )\n}\n\n/**\n * Runs the dev instant/static-shell validation passes off the main thread.\n * Reloads the route's compiled module, then delegates the whole validation to\n * that module via `ComponentMod.routeModule.runValidationInDev`, so every\n * render (flight re-encodes and client prerenders) runs inside the app-page\n * bundle's single React instance. Logs any returned errors to the worker's\n * stderr with source-mapped code frames, then encodes them as RSC Flight bytes\n * for the main thread to forward to the dev overlay. Returns `null` when\n * validation was superseded or produced no errors.\n */\nexport async function runDevValidation(\n message: DevValidationWorkerMessage,\n abortBuffer: SharedArrayBuffer\n): Promise<DevValidationWorkerResult> {\n // Load the native SWC bindings and wire the code-frame renderer so the errors\n // logged below render with a source-mapped code frame, matching the\n // in-process dev output (the E2E tests snapshot the CLI text between the\n // validation markers). The `build/swc` graph these pull in is bundled as a\n // runtime external (see `next-runtime.webpack-config.js`), so it resolves\n // from the installed `next/dist` tree rather than being compiled into this\n // worker bundle, the same way the unbundled build worker loads it.\n await installBindings()\n installCodeFrameSupport()\n setBundlerFindSourceMapImplementation(\n createDiskSourceMapLookup(message.distDir)\n )\n setHttpClientAndAgentOptions({\n httpAgentOptions: message.nextConfigSerializable.httpAgentOptions,\n })\n\n // Populates the manifests singleton for the route via `setManifestsSingleton`\n // inside `loadComponents`, exactly as a real request does. The pool tears the\n // worker down on HMR / route recompile so the next validation reloads from a\n // clean require cache.\n const { ComponentMod } = await loadComponents<AppPageModule>({\n distDir: message.distDir,\n page: message.page,\n isAppPath: true,\n isDev: true,\n sriEnabled: false,\n needsManifestsForLegacyReasons: true,\n })\n\n await registerAdditionalClientReferenceManifests(\n message.distDir,\n message.additionalClientReferenceManifestPages\n )\n\n const { signal, cleanup } = createSupersedeSignal(abortBuffer)\n\n if (isTestLoggingEnabled) {\n console.log(\n formatValidationEvent({\n type: 'validation_start',\n requestId: message.requestId,\n url: message.request.urlPathname + message.request.urlSearch,\n responseFinished: message.responseFinished,\n })\n )\n }\n\n try {\n if (isTestLoggingEnabled) {\n await applyTestValidationDelay(signal)\n }\n\n if (signal.aborted) {\n return null\n }\n\n // Crossing into the app-page bundle: the entire validation runs there, so\n // the client prerenders use the same React the user's client components\n // resolve through `ComponentMod`.\n const validationErrors = await ComponentMod.routeModule.runValidationInDev(\n ComponentMod,\n message,\n signal\n )\n\n if (validationErrors === undefined || signal.aborted) {\n return null\n }\n\n const errors: Error[] = []\n for (const validationError of validationErrors) {\n // Log to the worker's stderr; `node-environment` +\n // `installCodeFrameSupport` render the source-mapped stack and code frame\n // there, matching the in-process CLI output.\n console.error(validationError)\n if (validationError instanceof Error) {\n errors.push(validationError)\n }\n }\n\n if (errors.length === 0) {\n return null\n }\n\n return await serializeValidationErrorsToFlight(ComponentMod, errors)\n } finally {\n cleanup()\n if (isTestLoggingEnabled) {\n console.log(\n formatValidationEvent({\n type: signal.aborted ? 'validation_aborted' : 'validation_end',\n requestId: message.requestId,\n url: message.request.urlPathname + message.request.urlSearch,\n })\n )\n }\n }\n}\n"],"names":["isAbsolute","relative","readFileSync","realpathSync","fileURLToPath","installBindings","installCodeFrameSupport","loadClientReferenceManifestForPage","loadComponents","setHttpClientAndAgentOptions","serializeValidationErrorsToFlight","formatValidationEvent","getServerActionsManifest","setManifestsSingleton","setBundlerFindSourceMapImplementation","createDiskSourceMapLookup","distDir","canonicalDistDir","payloads","Map","findSourceMapPayloadOnDisk","sourceURL","chunkPath","startsWith","undefined","cached","get","has","payload","relativePath","JSON","parse","set","Error","stackTraceLimit","isTestLoggingEnabled","process","env","__NEXT_TEST_MODE","NEXT_TEST_LOG_VALIDATION","createSupersedeSignal","abortBuffer","controller","AbortController","flag","Int32Array","Atomics","load","abort","signal","cleanup","settled","wait","waitAsync","async","value","then","notify","applyTestValidationDelay","delayMs","Number","NEXT_TEST_DEV_VALIDATION_DELAY_MS","isFinite","aborted","Promise","resolve","finishDelay","clearTimeout","timeout","removeEventListener","setTimeout","addEventListener","once","registerAdditionalClientReferenceManifests","pages","length","serverActionsManifest","all","map","page","clientReferenceManifest","runDevValidation","message","httpAgentOptions","nextConfigSerializable","ComponentMod","isAppPath","isDev","sriEnabled","needsManifestsForLegacyReasons","additionalClientReferenceManifestPages","console","log","type","requestId","url","request","urlPathname","urlSearch","responseFinished","validationErrors","routeModule","runValidationInDev","errors","validationError","error","push"],"mappings":"AAMA,OAAO,kBAAiB;AACxB,OAAO,sBAAqB;AAE5B,SAASA,UAAU,EAAEC,QAAQ,QAAQ,OAAM;AAC3C,SAASC,YAAY,EAAEC,YAAY,QAAQ,KAAI;AAC/C,SAASC,aAAa,QAAQ,MAAK;AACnC,SAASC,eAAe,QAAQ,mCAAkC;AAClE,SAASC,uBAAuB,QAAQ,4BAA2B;AACnE,SACEC,kCAAkC,EAClCC,cAAc,QACT,qBAAoB;AAC3B,SAASC,4BAA4B,QAAQ,0BAAyB;AACtE,SAASC,iCAAiC,QAAQ,8CAA6C;AAC/F,SAASC,qBAAqB,QAAQ,sCAAqC;AAC3E,SACEC,wBAAwB,EACxBC,qBAAqB,QAChB,oCAAmC;AAC1C,SAASC,qCAAqC,QAAQ,yBAAwB;AAG9E;;;;;;;;;;;;;;;;;;;CAmBC,GACD,SAASC,0BACPC,OAAe;IAEf,6EAA6E;IAC7E,0EAA0E;IAC1E,WAAW;IACX,IAAIC,mBAAmBD;IACvB,IAAI;QACFC,mBAAmBd,aAAaa;IAClC,EAAE,OAAM,CAAC;IAET,MAAME,WAAW,IAAIC;IAErB,OAAO,SAASC,2BAA2BC,SAAS;QAClD,IAAIC,YAAYD;QAEhB,IAAIC,UAAUC,UAAU,CAAC,YAAY;YACnC,IAAI;gBACFD,YAAYlB,cAAckB;YAC5B,EAAE,OAAM;gBACN,OAAOE;YACT;QACF;QAEA,IAAI,CA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AAOG,IAAI,CAACF;YACd;QACF;QAEA,IAAID,OAAO5B,MAAM,KAAK,GAAG;YACvB,OAAO;QACT;QAEA,OAAO,MAAMjE,kCAAkC2E,cAAckB;IAC/D,SAAU;QACRrD;QACA,IAAIf,sBAAsB;YACxBwD,QAAQC,GAAG,CACTjF,sBAAsB;gBACpBkF,MAAM5C,OAAOc,OAAO,GAAG,uBAAuB;gBAC9C+B,WAAWZ,QAAQY,SAAS;gBAC5BC,KAAKb,QAAQc,OAAO,CAACC,WAAW,GAAGf,QAAQc,OAAO,CAACE,SAAS;YAC9D;QAEJ;IACF;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/dev/dev-validation-worker.ts"],"sourcesContent":["import type { AppPageModule } from '../route-modules/app-page/module'\nimport type {\n DevValidationWorkerMessage,\n DevValidationWorkerResult,\n} from '../app-render/dev-validation-worker-globals'\nimport type { NodeJsPartialHmrUpdate } from '../../build/swc/types'\n\nimport '../require-hook'\nimport '../node-environment'\n\nimport { isAbsolute, relative } from 'path'\nimport { readFileSync, realpathSync } from 'fs'\nimport { fileURLToPath } from 'url'\nimport { installBindings } from '../../build/swc/install-bindings'\nimport { installCodeFrameSupport } from '../lib/install-code-frame'\nimport {\n loadClientReferenceManifestForPage,\n loadComponents,\n} from '../load-components'\nimport { setHttpClientAndAgentOptions } from '../setup-http-agent-env'\nimport { serializeValidationErrorsToFlight } from '../app-render/dev-validation-error-delivery'\nimport { formatValidationEvent } from '../app-render/dev-validation-events'\nimport { clearManifestCache } from '../load-manifest.external'\nimport { deleteCache } from './require-cache'\nimport {\n getServerActionsManifest,\n setManifestsSingleton,\n} from '../app-render/manifests-singleton'\nimport { setBundlerFindSourceMapImplementation } from '../patch-error-inspect'\nimport type { ModernSourceMapPayload } from '../lib/source-maps'\n\n/**\n * Resolves a chunk's source map by reading the `.map` file the bundler emitted\n * next to it, for chunks inside `distDir`.\n *\n * The main thread answers the same question through the Turbopack project\n * handle, which cannot cross a thread boundary. Reading from disk is\n * project-free and, more importantly, does not depend on the chunk having been\n * evaluated in this thread: Node.js caches source maps per isolate, and the\n * worker never renders server components, so it holds maps only for the chunks\n * `loadComponents` pulled in. Frames arriving in the transported payload can\n * point at any chunk the main render touched.\n *\n * Reading from disk covers the chunks, because the worker only runs under\n * Turbopack (see `next-dev-server.ts`), which writes a `.map` beside every one\n * of them. A module the server updated in place has no chunk of its own and is\n * covered instead by this thread applying the same update (see\n * `applyHmrUpdate`), which leaves its inline map in Node.js' cache here. Frames\n * from dependencies that are not bundled never reach this point, because\n * `filterStackFrameDEV` drops `node_modules` and `node:` frames; bundled\n * dependencies appear as chunks inside `distDir` like any other code.\n */\nfunction createDiskSourceMapLookup(\n distDir: string\n): (sourceURL: string) => ModernSourceMapPayload | undefined {\n // The frames carry resolved paths, so compare against the resolved `distDir`\n // to keep the containment check meaningful when the project sits behind a\n // symlink.\n let canonicalDistDir = distDir\n try {\n canonicalDistDir = realpathSync(distDir)\n } catch {}\n\n const payloads = new Map<string, ModernSourceMapPayload | undefined>()\n\n return function findSourceMapPayloadOnDisk(sourceURL) {\n let chunkPath = sourceURL\n\n if (chunkPath.startsWith('file://')) {\n try {\n chunkPath = fileURLToPath(chunkPath)\n } catch {\n return undefined\n }\n }\n\n if (!isAbsolute(chunkPath)) {\n // Not an emitted chunk, e.g. `<anonymous>`.\n return undefined\n }\n\n const cached = payloads.get(chunkPath)\n if (cached !== undefined || payloads.has(chunkPath)) {\n return cached\n }\n\n let payload: ModernSourceMapPayload | undefined\n const relativePath = relative(canonicalDistDir, chunkPath)\n\n // Only chunks emitted into `distDir` have a source map to point at, and\n // this keeps the lookup from reading arbitrary paths off disk.\n if (!relativePath.startsWith('..') && !isAbsolute(relativePath)) {\n try {\n payload = JSON.parse(readFileSync(chunkPath + '.map', 'utf8'))\n } catch {\n payload = undefined\n }\n }\n\n payloads.set(chunkPath, payload)\n\n return payload\n }\n}\n\n// Match the main dev server (`next-dev-server.ts`), which raises this so the\n// server captures deeper stacks. React's owner-stack capture during the\n// validation prerenders depends on it, so without it the worker's errors lose\n// their owner-stack source attribution.\ntry {\n Error.stackTraceLimit = 50\n} catch {}\n\n// The lifecycle markers E2E tests read from the CLI. Emitted on the worker's\n// stdout (piped to the parent) so they interleave with the parent's captured\n// output the same way the in-process `runWithDevValidationLogging` markers do.\n// Gated on the same test env that path checks.\nconst isTestLoggingEnabled = !!(\n process.env.__NEXT_TEST_MODE && process.env.NEXT_TEST_LOG_VALIDATION\n)\n\n/**\n * Adapts the pool's supersede flag into an `AbortSignal` the validation passes\n * check at their depth/yield boundaries. The pool shares an `Int32Array`-backed\n * `SharedArrayBuffer` whose first slot the main thread flips to non-zero (with\n * `Atomics.store` + `Atomics.notify`) when a newer navigation supersedes this\n * one. We wait for that notification with `Atomics.waitAsync`, which is\n * event-driven rather than polled. A validation that finishes without being\n * superseded calls `cleanup()`, which wakes our own still-pending wait so it\n * leaves no waiter (and no retained buffer) behind.\n */\nfunction createSupersedeSignal(abortBuffer: SharedArrayBuffer): {\n signal: AbortSignal\n cleanup: () => void\n} {\n const controller = new AbortController()\n const flag = new Int32Array(abortBuffer)\n\n if (Atomics.load(flag, 0) !== 0) {\n controller.abort()\n return { signal: controller.signal, cleanup: () => {} }\n }\n\n let settled = false\n const wait = Atomics.waitAsync(flag, 0, 0)\n if (wait.async) {\n wait.value.then(() => {\n if (settled) {\n return\n }\n settled = true\n // Woken either by a real supersede or by `cleanup()`; only the former\n // leaves the flag set.\n if (Atomics.load(flag, 0) !== 0) {\n controller.abort()\n }\n })\n } else if (Atomics.load(flag, 0) !== 0) {\n // The flag flipped between the load above and the wait.\n controller.abort()\n }\n\n return {\n signal: controller.signal,\n cleanup: () => {\n if (!settled) {\n Atomics.notify(flag, 0)\n }\n },\n }\n}\n\n/**\n * Waits out the test-only validation delay, resolving early if the render is\n * superseded. Mirrors the delay in `runWithDevValidationLogging` so scheduler\n * tests observe the same in-flight window on the worker path.\n */\nasync function applyTestValidationDelay(signal: AbortSignal): Promise<void> {\n const delayMs = Number(process.env.NEXT_TEST_DEV_VALIDATION_DELAY_MS)\n if (!Number.isFinite(delayMs) || delayMs <= 0 || signal.aborted) {\n return\n }\n\n await new Promise<void>((resolve) => {\n const finishDelay = () => {\n clearTimeout(timeout)\n signal.removeEventListener('abort', finishDelay)\n resolve()\n }\n const timeout = setTimeout(finishDelay, delayMs)\n signal.addEventListener('abort', finishDelay, { once: true })\n })\n}\n\n/**\n * Registers the client reference manifests of the pages that supplied client\n * references to the render being validated, beyond the validated route's own\n * manifest. This thread has its own manifests singleton, which `loadComponents`\n * seeds with only the validated route, so without these the dev-only cross-page\n * lookup in `createProxiedClientReferenceManifest` has no other manifest to\n * search and decoding the transported payload fails. Usually a no-op, since the\n * main thread only records a page when React's I/O tracking actually carried a\n * reference across pages.\n */\nasync function registerAdditionalClientReferenceManifests(\n distDir: string,\n pages: string[]\n): Promise<void> {\n if (pages.length === 0) {\n return\n }\n\n // Set by `loadComponents`. One server actions manifest covers the whole app,\n // so the pages registered here share the validated route's.\n const serverActionsManifest = getServerActionsManifest()\n\n await Promise.all(\n pages.map(async (page) => {\n const clientReferenceManifest = await loadClientReferenceManifestForPage(\n distDir,\n page\n )\n\n if (clientReferenceManifest) {\n setManifestsSingleton({\n page,\n clientReferenceManifest,\n serverActionsManifest,\n })\n }\n })\n )\n}\n\ndeclare const __turbopack_server_hmr_apply__:\n | ((update: NodeJsPartialHmrUpdate) => void)\n | undefined\n\n/**\n * What this thread did with a forwarded HMR update.\n *\n * `no-runtime` is not a failure: no runtime the update routes to had been\n * loaded here, so there was nothing to patch, and whatever loads that route\n * later reads the updated chunk from disk.\n */\nexport type HmrApplyOutcome = 'applied' | 'no-runtime' | 'failed'\n\n/**\n * Applies a server HMR update to this thread's module registry, mirroring the\n * apply the dev server performed on its own.\n *\n * Turbopack's Node.js runtime registers the apply machinery per isolate (see\n * `dev-nodejs.ts`), and `loadComponents` evaluates that runtime here, so this\n * thread patches the same modules the dev server does. The apply also leaves\n * the updated module's inline source map in this thread's Node.js cache, which\n * is what makes a stack frame in that module source-mappable here.\n */\nexport async function applyHmrUpdate(\n update: NodeJsPartialHmrUpdate\n): Promise<HmrApplyOutcome> {\n if (typeof __turbopack_server_hmr_apply__ !== 'function') {\n return 'no-runtime'\n }\n\n try {\n __turbopack_server_hmr_apply__(update)\n } catch {\n // The dev server responds to the same failure by re-evaluating every\n // module from disk. This thread cannot be repaired in place either, so the\n // caller drops it.\n return 'failed'\n }\n\n return 'applied'\n}\n\n/**\n * Clears the same caches the dev server cleared, for the same paths.\n *\n * `evictModules` follows the dev server's own split: an applied update patches\n * modules in place and clears only the manifest cache for the updated chunks,\n * while a recompile evicts `require.cache` as well. This thread follows both,\n * so its module state stays the dev server's module state.\n */\nexport async function invalidateCaches(\n filePaths: string[],\n evictModules: boolean\n): Promise<void> {\n if (evictModules) {\n deleteCache(filePaths)\n return\n }\n\n for (const filePath of filePaths) {\n clearManifestCache(filePath)\n }\n}\n\n/**\n * Runs the dev instant/static-shell validation passes off the main thread.\n * Reloads the route's compiled module, then delegates the whole validation to\n * that module via `ComponentMod.routeModule.runValidationInDev`, so every\n * render (flight re-encodes and client prerenders) runs inside the app-page\n * bundle's single React instance. Logs any returned errors to the worker's\n * stderr with source-mapped code frames, then encodes them as RSC Flight bytes\n * for the main thread to forward to the dev overlay. Returns `null` when\n * validation was superseded or produced no errors.\n */\nexport async function runDevValidation(\n message: DevValidationWorkerMessage,\n abortBuffer: SharedArrayBuffer\n): Promise<DevValidationWorkerResult> {\n // Load the native SWC bindings and wire the code-frame renderer so the errors\n // logged below render with a source-mapped code frame, matching the\n // in-process dev output (the E2E tests snapshot the CLI text between the\n // validation markers). The `build/swc` graph these pull in is bundled as a\n // runtime external (see `next-runtime.webpack-config.js`), so it resolves\n // from the installed `next/dist` tree rather than being compiled into this\n // worker bundle, the same way the unbundled build worker loads it.\n await installBindings()\n installCodeFrameSupport()\n setBundlerFindSourceMapImplementation(\n createDiskSourceMapLookup(message.distDir)\n )\n setHttpClientAndAgentOptions({\n httpAgentOptions: message.nextConfigSerializable.httpAgentOptions,\n })\n\n // Populates the manifests singleton for the route via `setManifestsSingleton`\n // inside `loadComponents`, exactly as a real request does. The pool tears the\n // worker down on HMR / route recompile so the next validation reloads from a\n // clean require cache.\n const { ComponentMod } = await loadComponents<AppPageModule>({\n distDir: message.distDir,\n page: message.page,\n isAppPath: true,\n isDev: true,\n sriEnabled: false,\n needsManifestsForLegacyReasons: true,\n })\n\n await registerAdditionalClientReferenceManifests(\n message.distDir,\n message.additionalClientReferenceManifestPages\n )\n\n const { signal, cleanup } = createSupersedeSignal(abortBuffer)\n\n if (isTestLoggingEnabled) {\n console.log(\n formatValidationEvent({\n type: 'validation_start',\n requestId: message.requestId,\n url: message.request.urlPathname + message.request.urlSearch,\n responseFinished: message.responseFinished,\n })\n )\n }\n\n try {\n if (isTestLoggingEnabled) {\n await applyTestValidationDelay(signal)\n }\n\n if (signal.aborted) {\n return null\n }\n\n // Crossing into the app-page bundle: the entire validation runs there, so\n // the client prerenders use the same React the user's client components\n // resolve through `ComponentMod`.\n const validationErrors = await ComponentMod.routeModule.runValidationInDev(\n ComponentMod,\n message,\n signal\n )\n\n if (validationErrors === undefined || signal.aborted) {\n return null\n }\n\n const errors: Error[] = []\n for (const validationError of validationErrors) {\n // Log to the worker's stderr; `node-environment` +\n // `installCodeFrameSupport` render the source-mapped stack and code frame\n // there, matching the in-process CLI output.\n console.error(validationError)\n if (validationError instanceof Error) {\n errors.push(validationError)\n }\n }\n\n if (errors.length === 0) {\n return null\n }\n\n return await serializeValidationErrorsToFlight(ComponentMod, errors)\n } finally {\n cleanup()\n if (isTestLoggingEnabled) {\n console.log(\n formatValidationEvent({\n type: signal.aborted ? 'validation_aborted' : 'validation_end',\n requestId: message.requestId,\n url: message.request.urlPathname + message.request.urlSearch,\n })\n )\n }\n }\n}\n"],"names":["isAbsolute","relative","readFileSync","realpathSync","fileURLToPath","installBindings","installCodeFrameSupport","loadClientReferenceManifestForPage","loadComponents","setHttpClientAndAgentOptions","serializeValidationErrorsToFlight","formatValidationEvent","clearManifestCache","deleteCache","getServerActionsManifest","setManifestsSingleton","setBundlerFindSourceMapImplementation","createDiskSourceMapLookup","distDir","canonicalDistDir","payloads","Map","findSourceMapPayloadOnDisk","sourceURL","chunkPath","startsWith","undefined","cached","get","has","payload","relativePath","JSON","parse","set","Error","stackTraceLimit","isTestLoggingEnabled","process","env","__NEXT_TEST_MODE","NEXT_TEST_LOG_VALIDATION","createSupersedeSignal","abortBuffer","controller","AbortController","flag","Int32Array","Atomics","load","abort","signal","cleanup","settled","wait","waitAsync","async","value","then","notify","applyTestValidationDelay","delayMs","Number","NEXT_TEST_DEV_VALIDATION_DELAY_MS","isFinite","aborted","Promise","resolve","finishDelay","clearTimeout","timeout","removeEventListener","setTimeout","addEventListener","once","registerAdditionalClientReferenceManifests","pages","length","serverActionsManifest","all","map","page","clientReferenceManifest","applyHmrUpdate","update","__turbopack_server_hmr_apply__","invalidateCaches","filePaths","evictModules","filePath","runDevValidation","message","httpAgentOptions","nextConfigSerializable","ComponentMod","isAppPath","isDev","sriEnabled","needsManifestsForLegacyReasons","additionalClientReferenceManifestPages","console","log","type","requestId","url","request","urlPathname","urlSearch","responseFinished","validationErrors","routeModule","runValidationInDev","errors","validationError","error","push"],"mappings":"AAOA,OAAO,kBAAiB;AACxB,OAAO,sBAAqB;AAE5B,SAASA,UAAU,EAAEC,QAAQ,QAAQ,OAAM;AAC3C,SAASC,YAAY,EAAEC,YAAY,QAAQ,KAAI;AAC/C,SAASC,aAAa,QAAQ,MAAK;AACnC,SAASC,eAAe,QAAQ,mCAAkC;AAClE,SAASC,uBAAuB,QAAQ,4BAA2B;AACnE,SACEC,kCAAkC,EAClCC,cAAc,QACT,qBAAoB;AAC3B,SAASC,4BAA4B,QAAQ,0BAAyB;AACtE,SAASC,iCAAiC,QAAQ,8CAA6C;AAC/F,SAASC,qBAAqB,QAAQ,sCAAqC;AAC3E,SAASC,kBAAkB,QAAQ,4BAA2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,CAACC,WAAW,GAAGf,QAAQc,OAAO,CAACE,SAAS;YAC9D;QAEJ;IACF;AACF","ignoreList":[0]} |
| import { RenderStage } from './app-render/staged-rendering'; | ||
| import { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'; | ||
| import { getServerReact, getClientReact } from './runtime-reacts.external'; | ||
| import { ReflectAdapter } from './web/spec-extension/adapters/reflect'; | ||
| export function isHangingPromiseRejectionError(err) { | ||
@@ -200,2 +201,5 @@ if (typeof err !== 'object' || err === null || !('digest' in err)) { | ||
| } | ||
| export function trackIncompatibleShellContent(workUnitStore) { | ||
| workUnitStore.hasIncompatibleShellContent = true; | ||
| } | ||
| export function makeClientHookHangingPromise(signal, error) { | ||
@@ -259,2 +263,30 @@ return makeHangingPromiseWithError(signal, error); | ||
| } | ||
| /** Invokes `onUse` whenever `then()/catch()/finally()` are called on the promise. */ export function trackPromiseUsed(promise, onUse) { | ||
| const methodCache = {}; | ||
| return new Proxy(promise, { | ||
| get (target, prop, receiver) { | ||
| if (prop === 'then' || prop === 'catch' || prop === 'finally') { | ||
| let patchedMethod = methodCache[prop]; | ||
| if (patchedMethod !== undefined) { | ||
| return patchedMethod; | ||
| } | ||
| const originalMethod = ReflectAdapter.get(target, prop, receiver); | ||
| patchedMethod = ({ | ||
| [prop]: (...args)=>{ | ||
| try { | ||
| onUse(); | ||
| } catch (err) { | ||
| // We don't want to break the method even if our tracking errored. | ||
| console.error(err); | ||
| } | ||
| return originalMethod.apply(target, args); | ||
| } | ||
| })[prop]; | ||
| methodCache[prop] = patchedMethod; | ||
| return patchedMethod; | ||
| } | ||
| return ReflectAdapter.get(target, prop, receiver); | ||
| } | ||
| }); | ||
| } | ||
| export const RENDER_STAGES_BY_DATA_KIND = { | ||
@@ -261,0 +293,0 @@ sessionData: RenderStage.ShellRuntime, |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/dynamic-rendering-utils.ts"],"sourcesContent":["import {\n RenderStage,\n type AdvanceableRenderStage,\n} from './app-render/staged-rendering'\nimport type {\n RequestStore,\n WorkUnitStore,\n} from './app-render/work-unit-async-storage.external'\nimport { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'\nimport { getServerReact, getClientReact } from './runtime-reacts.external'\n\nexport function isHangingPromiseRejectionError(\n err: unknown\n): err is HangingPromiseRejectionError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === HANGING_PROMISE_REJECTION\n}\n\nconst HANGING_PROMISE_REJECTION = 'HANGING_PROMISE_REJECTION'\n\nclass HangingPromiseRejectionError extends Error {\n public readonly digest = HANGING_PROMISE_REJECTION\n\n constructor(\n public readonly route: string,\n public readonly expression: string\n ) {\n super(\n `During prerendering, ${expression} rejects when the prerender is complete. Typically these errors are handled by React but if you move ${expression} to a different context by using \\`setTimeout\\`, \\`after\\`, or similar functions you may observe this error and you should handle it in that context. This occurred at route \"${route}\".`\n )\n }\n}\n\nconst CLIENT_HOOK_DYNAMIC = 'CLIENT_HOOK_DYNAMIC'\n\nexport class ClientHookDynamicError extends Error {\n public readonly digest = CLIENT_HOOK_DYNAMIC\n\n constructor(route: string, expression: string) {\n super(\n `Route \"${route}\": Next.js encountered URL data \\`${expression}\\` in a Client Component outside of \\`<Suspense>\\`.\\n\\n` +\n `This blocks prerendering because the value is only available at runtime.\\n\\n` +\n `Ways to fix this:\\n` +\n ` - [stream] Wrap the component in \\`<Suspense fallback={...}>\\` so the hook value streams in after prerendering\\n` +\n ` - [block] Set \\`export const instant = false\\` to allow a blocking route\\n\\n` +\n `Learn more: https://nextjs.org/docs/messages/blocking-prerender-client-hook`\n )\n }\n}\n\nexport function isClientHookDynamicError(\n err: unknown\n): err is ClientHookDynamicError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === CLIENT_HOOK_DYNAMIC\n}\n\ntype AbortListeners = Array<() => void>\nconst abortListenersBySignal = new WeakMap<AbortSignal, AbortListeners>()\n\n/**\n * Constructs a promise that never resolves, standing in for *dynamic* data:\n * data that is only available during a real dynamic request and hangs in\n * every kind of prerender — `io()`, `connection()`, uncached `fetch()`.\n *\n * This is primarily useful for cacheComponents where we use promise\n * resolution timing to determine which parts of a render can be included in a\n * prerender.\n *\n * Records nothing on the prerender store: the promise's holes are only ever\n * filled by a real dynamic request, so a runtime prefetch response would have\n * the same holes as the static one. If the data source would resolve during a\n * runtime prerender, use `makeRuntimeHangingPromise` instead.\n *\n * @internal\n */\nexport function makeDynamicHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\nexport function makeUntrackedHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for *runtime* data:\n * data that hangs during a static prerender but is available during a runtime\n * prerender (the kind that backs a runtime prefetch request: request data\n * like cookies and headers is available, but the render is still not a real\n * dynamic request). Examples: cookies, headers, fallback params,\n * searchParams, and cache entries that are excluded only from static\n * prerenders.\n *\n * Creating one of these during a static prerender records on the prerender\n * store that a runtime prefetch would produce more content than the static\n * response (`runtimeDataAccessed`), which the segment prefetch encoding uses\n * to tell the client whether a runtime prefetch request could be skipped.\n *\n * When unsure whether data is dynamic or runtime, prefer this method — the\n * cost of over-recording is a redundant runtime prefetch request; the cost of\n * under-recording is a permanently missing one.\n *\n * `workUnitStore` may be null ONLY when the caller tracks the access itself\n * at observation time instead of creation time. This is for promises the\n * framework creates eagerly whether or not anything reads them (e.g. the\n * `searchParams` prop constructed for every page): recording at creation\n * would mark every render. Such a caller MUST call `trackRuntimeDataAccessed`\n * from every path that observes the promise (e.g. the proxy traps for\n * `then`/`status`), against the work unit store active at access time.\n *\n * For fallback-param data — data a concrete (ISR-upgraded) prerender would\n * resolve — use `makeFallbackParamsHangingPromise` instead, so the access\n * is recorded with the right effect on the static-prefetch hint.\n *\n * @internal\n */\nexport function makeRuntimeHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore | null\n): Promise<T> {\n if (workUnitStore !== null) {\n trackRuntimeDataAccessed(workUnitStore)\n }\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Variant of `makeRuntimeHangingPromise` for *fallback-param* data: fallback\n * route params and values derived solely from them (`params`, `rootParams`,\n * `pathname` during a fallback prerender). Like every runtime data access it\n * records the access on the prerender store's response-level flag, but its\n * effect on the build-time static-prefetch hint differs — on a\n * fallback-upgradeable route the access is transient (a concrete prerender\n * resolves it), so it leaves the hint intact. See\n * `trackFallbackParamsAccessed`.\n *\n * As with `makeRuntimeHangingPromise`, `workUnitStore` may be null ONLY when\n * the caller tracks the access itself at observation time instead of creation\n * time, by calling `trackFallbackParamsAccessed` from every path that\n * observes the promise.\n *\n * @internal\n */\nexport function makeFallbackParamsHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore | null\n): Promise<T> {\n if (workUnitStore !== null) {\n trackFallbackParamsAccessed(workUnitStore)\n }\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for data that is only\n * accessible in a later *stage* of rendering than this render reaches — e.g.\n * a prefetchable short-stale cache entry that's excluded from shells when the\n * render ends at the shell stage, or params during a runtime-prefetch render\n * that stops before the stage where params resolve.\n *\n * A render that runs through the later stage would include the data; in\n * particular a runtime prefetch renders through its later stages, so on a\n * static prerender store this records `runtimeDataAccessed`, same as\n * `makeRuntimeHangingPromise`.\n *\n * @internal\n */\nexport function makeStageHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore\n): Promise<T> {\n trackRuntimeDataAccessed(workUnitStore)\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Records on a static prerender store that the render accessed a data source\n * which would have resolved during a runtime prerender. No-op for all other\n * store types.\n *\n * `makeRuntimeHangingPromise` and `makeStageHangingPromise` call this\n * automatically; call it directly only where the access is observed\n * separately from the promise's creation (see the null `workUnitStore` case\n * of `makeRuntimeHangingPromise`), or where the prerender is aborted\n * synchronously instead of hanging.\n *\n * For fallback-param data, use `trackFallbackParamsAccessed` instead. When\n * unsure, this is the conservative choice: it unconditionally clears the\n * static-prefetch hint.\n */\nexport function trackRuntimeDataAccessed(workUnitStore: WorkUnitStore): void {\n trackRuntimeDataAccessedImpl(workUnitStore, false)\n}\n\n/**\n * Fallback-param variant of `trackRuntimeDataAccessed`, for accesses of\n * fallback route params and values derived solely from them. It records the\n * response-level flag all the same, but only clears the build-time\n * static-prefetch hint when the route is not fallback-upgradeable — on an\n * upgradeable route the access is transient, since ISR later produces a\n * concrete prerender that resolves it.\n */\nexport function trackFallbackParamsAccessed(\n workUnitStore: WorkUnitStore\n): void {\n trackRuntimeDataAccessedImpl(workUnitStore, true)\n}\n\nfunction trackRuntimeDataAccessedImpl(\n workUnitStore: WorkUnitStore,\n isFallbackParamAccess: boolean\n): void {\n switch (workUnitStore.type) {\n case 'prerender': {\n // Response-level flag (the payload's `u`, forwarded to segment\n // responses as `needsRuntimeRequest`): resolved for every kind of\n // access — a pre-upgrade fallback response must keep reporting that\n // a runtime request would return more. The fulfillment row lands at\n // the current position in the Flight stream, which is what makes the\n // value rewindable per stage. Promise resolution is idempotent, so\n // repeated accesses are free.\n workUnitStore.runtimeDataAccessed?.resolve(true)\n\n // Hint cell (holds the build-constant\n // PrefetchHint.ShouldAttemptStaticPrefetch value directly): a\n // fallback-param access is transient when the route is\n // fallback-upgradeable — ISR later produces the concrete prerender a\n // static prefetch attempt would hit — so it leaves the hint intact.\n // (Until that upgrade, the response-level flag above keeps directing\n // the client to a runtime fallback; the hint only costs a wasted\n // static attempt in the interim.) Every other access clears it.\n const hintCell = workUnitStore.shouldAttemptStaticPrefetch\n if (\n hintCell !== null &&\n (!isFallbackParamAccess || !workUnitStore.isFallbackUpgradeable)\n ) {\n hintCell.current = false\n }\n break\n }\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'validation-client':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n // Only the modern server prerender tracks this; see the field docs on\n // PrerenderStoreModernServer.\n break\n default:\n workUnitStore satisfies never\n }\n}\n\nexport function makeClientHookHangingPromise<T>(\n signal: AbortSignal,\n error: ClientHookDynamicError\n): Promise<T> {\n return makeHangingPromiseWithError(signal, error)\n}\n\nfunction makeHangingPromiseWithError<T>(\n signal: AbortSignal,\n error: Error\n): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(error)\n } else {\n const hangingPromise = new Promise<T>((_, reject) => {\n const boundRejection = reject.bind(null, error)\n let currentListeners = abortListenersBySignal.get(signal)\n if (currentListeners) {\n currentListeners.push(boundRejection)\n } else {\n const listeners = [boundRejection]\n abortListenersBySignal.set(signal, listeners)\n signal.addEventListener(\n 'abort',\n () => {\n for (let i = 0; i < listeners.length; i++) {\n listeners[i]()\n }\n },\n { once: true }\n )\n }\n })\n // We are fine if no one actually awaits this promise. We shouldn't consider this an unhandled rejection so\n // we attach a noop catch handler here to suppress this warning. If you actually await somewhere or construct\n // your own promise out of it you'll need to ensure you handle the error when it rejects.\n hangingPromise.catch(ignoreReject)\n return hangingPromise\n }\n}\n\nfunction ignoreReject() {}\n\n/**\n * Creates a promise that will be triggered when another promise resolves.\n * It will not emit unhandled rejections, which is important if the trigger\n * is a promise that might itself get rejected (e.g. when a prerender/render\n * are aborted due to sync IO)\n */\nexport function makePromiseFromTrigger<T>(\n trigger: Promise<any>,\n value: T\n): Promise<T> {\n const promise = trigger.then(() => value)\n promise.catch(ignoreReject)\n return promise\n}\n\nexport function makeDevtoolsIOAwarePromise<T>(\n underlying: T,\n requestStore: RequestStore,\n stage: AdvanceableRenderStage\n): Promise<T> {\n if (requestStore.stagedRendering) {\n // We resolve each stage in a timeout, so React DevTools will pick this up as IO.\n return requestStore.stagedRendering.delayUntilStage(\n stage,\n undefined,\n underlying\n )\n }\n // in React DevTools if we resolve in a setTimeout we will observe\n // the promise resolution as something that can suspend a boundary or root.\n return new Promise<T>((resolve) => {\n // Must use setTimeout to be considered IO React DevTools. setImmediate will not work.\n setTimeout(() => {\n resolve(underlying)\n }, 0)\n })\n}\n\nexport const RENDER_STAGES_BY_DATA_KIND = {\n sessionData: RenderStage.ShellRuntime as const,\n staticLinkData: RenderStage.Static as const,\n runtimeLinkData: RenderStage.Runtime as const,\n}\n\nexport function applyOwnerStack(error: Error): Error {\n if (process.env.NODE_ENV !== 'production') {\n let ownerStack: string | undefined | null\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // captureOwnerStack() returns the owner stack for the current React\n // rendering context. Inside a cache scope this only includes the inner\n // component tree. The outer owner stack (captured before entering the\n // cache boundary in use-cache-wrapper.ts) is stored on the cache store.\n // We concatenate both to get the full component tree.\n const innerOwnerStack =\n getClientReact()?.captureOwnerStack?.() ??\n getServerReact()?.captureOwnerStack?.()\n\n switch (workUnitStore?.type) {\n case 'cache':\n case 'private-cache':\n ownerStack =\n (innerOwnerStack || '') + (workUnitStore.outerOwnerStack || '') ||\n undefined\n break\n case 'unstable-cache':\n case 'request':\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'generate-static-params':\n case undefined:\n ownerStack = innerOwnerStack\n break\n default:\n workUnitStore satisfies never\n }\n\n if (ownerStack) {\n let stack = ownerStack\n\n if (error.stack) {\n const frames: string[] = []\n\n for (const frame of error.stack.split('\\n').slice(1)) {\n if (frame.includes('react_stack_bottom_frame')) {\n break\n }\n\n frames.push(frame)\n }\n\n stack = '\\n' + frames.join('\\n') + stack\n }\n\n error.stack = error.name + ': ' + error.message + stack\n }\n }\n\n return error\n}\n"],"names":["RenderStage","workUnitAsyncStorage","getServerReact","getClientReact","isHangingPromiseRejectionError","err","digest","HANGING_PROMISE_REJECTION","HangingPromiseRejectionError","Error","constructor","route","expression","CLIENT_HOOK_DYNAMIC","ClientHookDynamicError","isClientHookDynamicError","abortListenersBySignal","WeakMap","makeDynamicHangingPromise","signal","makeHangingPromiseWithError","makeUntrackedHangingPromise","makeRuntimeHangingPromise","workUnitStore","trackRuntimeDataAccessed","makeFallbackParamsHangingPromise","trackFallbackParamsAccessed","makeStageHangingPromise","trackRuntimeDataAccessedImpl","isFallbackParamAccess","type","runtimeDataAccessed","resolve","hintCell","shouldAttemptStaticPrefetch","isFallbackUpgradeable","current","makeClientHookHangingPromise","error","aborted","Promise","reject","hangingPromise","_","boundRejection","bind","currentListeners","get","push","listeners","set","addEventListener","i","length","once","catch","ignoreReject","makePromiseFromTrigger","trigger","value","promise","then","makeDevtoolsIOAwarePromise","underlying","requestStore","stage","stagedRendering","delayUntilStage","undefined","setTimeout","RENDER_STAGES_BY_DATA_KIND","sessionData","ShellRuntime","staticLinkData","Static","runtimeLinkData","Runtime","applyOwnerStack","process","env","NODE_ENV","ownerStack","getStore","innerOwnerStack","captureOwnerStack","outerOwnerStack","stack","frames","frame","split","slice","includes","join","name","message"],"mappings":"AAAA,SACEA,WAAW,QAEN,gCAA+B;AAKtC,SAASC,oBAAoB,QAAQ,gDAA+C;AACpF,SAASC,cAAc,EAAEC,cAAc,QAAQ,4BAA2B;AAE1E,OAAO,SAASC,+BACdC,GAAY;IAEZ,IAAI,OAAOA,QAAQ,YAAYA,QAAQ,QAAQ,CAAE,CAAA,YAAYA,GAAE,GAAI;QACjE,OAAO;IACT;IAEA,OAAOA,IAAIC,MAAM,KAAKC;AACxB;AAEA,MAAMA,4BAA4B;AAElC,MAAMC,qCAAqCC;IAGzCC,YACE,AAAgBC,KAAa,EAC7B,AAAgBC,UAAkB,CAClC;QACA,KAAK,CACH,CAAC,qBAAqB,EAAE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,GAAGhD,MAAMuD,IAAI,GAAG,OAAOvD,MAAMwD,OAAO,GAAGR;QACpD;IACF;IAEA,OAAOhD;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/dynamic-rendering-utils.ts"],"sourcesContent":["import {\n RenderStage,\n type AdvanceableRenderStage,\n} from './app-render/staged-rendering'\nimport type {\n RequestStore,\n WorkUnitStore,\n} from './app-render/work-unit-async-storage.external'\nimport { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'\nimport { getServerReact, getClientReact } from './runtime-reacts.external'\nimport { ReflectAdapter } from './web/spec-extension/adapters/reflect'\n\nexport function isHangingPromiseRejectionError(\n err: unknown\n): err is HangingPromiseRejectionError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === HANGING_PROMISE_REJECTION\n}\n\nconst HANGING_PROMISE_REJECTION = 'HANGING_PROMISE_REJECTION'\n\nclass HangingPromiseRejectionError extends Error {\n public readonly digest = HANGING_PROMISE_REJECTION\n\n constructor(\n public readonly route: string,\n public readonly expression: string\n ) {\n super(\n `During prerendering, ${expression} rejects when the prerender is complete. Typically these errors are handled by React but if you move ${expression} to a different context by using \\`setTimeout\\`, \\`after\\`, or similar functions you may observe this error and you should handle it in that context. This occurred at route \"${route}\".`\n )\n }\n}\n\nconst CLIENT_HOOK_DYNAMIC = 'CLIENT_HOOK_DYNAMIC'\n\nexport class ClientHookDynamicError extends Error {\n public readonly digest = CLIENT_HOOK_DYNAMIC\n\n constructor(route: string, expression: string) {\n super(\n `Route \"${route}\": Next.js encountered URL data \\`${expression}\\` in a Client Component outside of \\`<Suspense>\\`.\\n\\n` +\n `This blocks prerendering because the value is only available at runtime.\\n\\n` +\n `Ways to fix this:\\n` +\n ` - [stream] Wrap the component in \\`<Suspense fallback={...}>\\` so the hook value streams in after prerendering\\n` +\n ` - [block] Set \\`export const instant = false\\` to allow a blocking route\\n\\n` +\n `Learn more: https://nextjs.org/docs/messages/blocking-prerender-client-hook`\n )\n }\n}\n\nexport function isClientHookDynamicError(\n err: unknown\n): err is ClientHookDynamicError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === CLIENT_HOOK_DYNAMIC\n}\n\ntype AbortListeners = Array<() => void>\nconst abortListenersBySignal = new WeakMap<AbortSignal, AbortListeners>()\n\n/**\n * Constructs a promise that never resolves, standing in for *dynamic* data:\n * data that is only available during a real dynamic request and hangs in\n * every kind of prerender — `io()`, `connection()`, uncached `fetch()`.\n *\n * This is primarily useful for cacheComponents where we use promise\n * resolution timing to determine which parts of a render can be included in a\n * prerender.\n *\n * Records nothing on the prerender store: the promise's holes are only ever\n * filled by a real dynamic request, so a runtime prefetch response would have\n * the same holes as the static one. If the data source would resolve during a\n * runtime prerender, use `makeRuntimeHangingPromise` instead.\n *\n * @internal\n */\nexport function makeDynamicHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\nexport function makeUntrackedHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for *runtime* data:\n * data that hangs during a static prerender but is available during a runtime\n * prerender (the kind that backs a runtime prefetch request: request data\n * like cookies and headers is available, but the render is still not a real\n * dynamic request). Examples: cookies, headers, fallback params,\n * searchParams, and cache entries that are excluded only from static\n * prerenders.\n *\n * Creating one of these during a static prerender records on the prerender\n * store that a runtime prefetch would produce more content than the static\n * response (`runtimeDataAccessed`), which the segment prefetch encoding uses\n * to tell the client whether a runtime prefetch request could be skipped.\n *\n * When unsure whether data is dynamic or runtime, prefer this method — the\n * cost of over-recording is a redundant runtime prefetch request; the cost of\n * under-recording is a permanently missing one.\n *\n * `workUnitStore` may be null ONLY when the caller tracks the access itself\n * at observation time instead of creation time. This is for promises the\n * framework creates eagerly whether or not anything reads them (e.g. the\n * `searchParams` prop constructed for every page): recording at creation\n * would mark every render. Such a caller MUST call `trackRuntimeDataAccessed`\n * from every path that observes the promise (e.g. the proxy traps for\n * `then`/`status`), against the work unit store active at access time.\n *\n * For fallback-param data — data a concrete (ISR-upgraded) prerender would\n * resolve — use `makeFallbackParamsHangingPromise` instead, so the access\n * is recorded with the right effect on the static-prefetch hint.\n *\n * @internal\n */\nexport function makeRuntimeHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore | null\n): Promise<T> {\n if (workUnitStore !== null) {\n trackRuntimeDataAccessed(workUnitStore)\n }\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Variant of `makeRuntimeHangingPromise` for *fallback-param* data: fallback\n * route params and values derived solely from them (`params`, `rootParams`,\n * `pathname` during a fallback prerender). Like every runtime data access it\n * records the access on the prerender store's response-level flag, but its\n * effect on the build-time static-prefetch hint differs — on a\n * fallback-upgradeable route the access is transient (a concrete prerender\n * resolves it), so it leaves the hint intact. See\n * `trackFallbackParamsAccessed`.\n *\n * As with `makeRuntimeHangingPromise`, `workUnitStore` may be null ONLY when\n * the caller tracks the access itself at observation time instead of creation\n * time, by calling `trackFallbackParamsAccessed` from every path that\n * observes the promise.\n *\n * @internal\n */\nexport function makeFallbackParamsHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore | null\n): Promise<T> {\n if (workUnitStore !== null) {\n trackFallbackParamsAccessed(workUnitStore)\n }\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for data that is only\n * accessible in a later *stage* of rendering than this render reaches — e.g.\n * a prefetchable short-stale cache entry that's excluded from shells when the\n * render ends at the shell stage, or params during a runtime-prefetch render\n * that stops before the stage where params resolve.\n *\n * A render that runs through the later stage would include the data; in\n * particular a runtime prefetch renders through its later stages, so on a\n * static prerender store this records `runtimeDataAccessed`, same as\n * `makeRuntimeHangingPromise`.\n *\n * @internal\n */\nexport function makeStageHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore\n): Promise<T> {\n trackRuntimeDataAccessed(workUnitStore)\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Records on a static prerender store that the render accessed a data source\n * which would have resolved during a runtime prerender. No-op for all other\n * store types.\n *\n * `makeRuntimeHangingPromise` and `makeStageHangingPromise` call this\n * automatically; call it directly only where the access is observed\n * separately from the promise's creation (see the null `workUnitStore` case\n * of `makeRuntimeHangingPromise`), or where the prerender is aborted\n * synchronously instead of hanging.\n *\n * For fallback-param data, use `trackFallbackParamsAccessed` instead. When\n * unsure, this is the conservative choice: it unconditionally clears the\n * static-prefetch hint.\n */\nexport function trackRuntimeDataAccessed(workUnitStore: WorkUnitStore): void {\n trackRuntimeDataAccessedImpl(workUnitStore, false)\n}\n\n/**\n * Fallback-param variant of `trackRuntimeDataAccessed`, for accesses of\n * fallback route params and values derived solely from them. It records the\n * response-level flag all the same, but only clears the build-time\n * static-prefetch hint when the route is not fallback-upgradeable — on an\n * upgradeable route the access is transient, since ISR later produces a\n * concrete prerender that resolves it.\n */\nexport function trackFallbackParamsAccessed(\n workUnitStore: WorkUnitStore\n): void {\n trackRuntimeDataAccessedImpl(workUnitStore, true)\n}\n\nfunction trackRuntimeDataAccessedImpl(\n workUnitStore: WorkUnitStore,\n isFallbackParamAccess: boolean\n): void {\n switch (workUnitStore.type) {\n case 'prerender': {\n // Response-level flag (the payload's `u`, forwarded to segment\n // responses as `needsRuntimeRequest`): resolved for every kind of\n // access — a pre-upgrade fallback response must keep reporting that\n // a runtime request would return more. The fulfillment row lands at\n // the current position in the Flight stream, which is what makes the\n // value rewindable per stage. Promise resolution is idempotent, so\n // repeated accesses are free.\n workUnitStore.runtimeDataAccessed?.resolve(true)\n\n // Hint cell (holds the build-constant\n // PrefetchHint.ShouldAttemptStaticPrefetch value directly): a\n // fallback-param access is transient when the route is\n // fallback-upgradeable — ISR later produces the concrete prerender a\n // static prefetch attempt would hit — so it leaves the hint intact.\n // (Until that upgrade, the response-level flag above keeps directing\n // the client to a runtime fallback; the hint only costs a wasted\n // static attempt in the interim.) Every other access clears it.\n const hintCell = workUnitStore.shouldAttemptStaticPrefetch\n if (\n hintCell !== null &&\n (!isFallbackParamAccess || !workUnitStore.isFallbackUpgradeable)\n ) {\n hintCell.current = false\n }\n break\n }\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'validation-client':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n // Only the modern server prerender tracks this; see the field docs on\n // PrerenderStoreModernServer.\n break\n default:\n workUnitStore satisfies never\n }\n}\n\nexport function trackIncompatibleShellContent(workUnitStore: RequestStore) {\n workUnitStore.hasIncompatibleShellContent = true\n}\n\nexport function makeClientHookHangingPromise<T>(\n signal: AbortSignal,\n error: ClientHookDynamicError\n): Promise<T> {\n return makeHangingPromiseWithError(signal, error)\n}\n\nfunction makeHangingPromiseWithError<T>(\n signal: AbortSignal,\n error: Error\n): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(error)\n } else {\n const hangingPromise = new Promise<T>((_, reject) => {\n const boundRejection = reject.bind(null, error)\n let currentListeners = abortListenersBySignal.get(signal)\n if (currentListeners) {\n currentListeners.push(boundRejection)\n } else {\n const listeners = [boundRejection]\n abortListenersBySignal.set(signal, listeners)\n signal.addEventListener(\n 'abort',\n () => {\n for (let i = 0; i < listeners.length; i++) {\n listeners[i]()\n }\n },\n { once: true }\n )\n }\n })\n // We are fine if no one actually awaits this promise. We shouldn't consider this an unhandled rejection so\n // we attach a noop catch handler here to suppress this warning. If you actually await somewhere or construct\n // your own promise out of it you'll need to ensure you handle the error when it rejects.\n hangingPromise.catch(ignoreReject)\n return hangingPromise\n }\n}\n\nfunction ignoreReject() {}\n\n/**\n * Creates a promise that will be triggered when another promise resolves.\n * It will not emit unhandled rejections, which is important if the trigger\n * is a promise that might itself get rejected (e.g. when a prerender/render\n * are aborted due to sync IO)\n */\nexport function makePromiseFromTrigger<T>(\n trigger: Promise<any>,\n value: T\n): Promise<T> {\n const promise = trigger.then(() => value)\n promise.catch(ignoreReject)\n return promise\n}\n\nexport function makeDevtoolsIOAwarePromise<T>(\n underlying: T,\n requestStore: RequestStore,\n stage: AdvanceableRenderStage\n): Promise<T> {\n if (requestStore.stagedRendering) {\n // We resolve each stage in a timeout, so React DevTools will pick this up as IO.\n return requestStore.stagedRendering.delayUntilStage(\n stage,\n undefined,\n underlying\n )\n }\n // in React DevTools if we resolve in a setTimeout we will observe\n // the promise resolution as something that can suspend a boundary or root.\n return new Promise<T>((resolve) => {\n // Must use setTimeout to be considered IO React DevTools. setImmediate will not work.\n setTimeout(() => {\n resolve(underlying)\n }, 0)\n })\n}\n\n/** Invokes `onUse` whenever `then()/catch()/finally()` are called on the promise. */\nexport function trackPromiseUsed<T>(promise: Promise<T>, onUse: () => void) {\n const methodCache: Record<string, (...args: any[]) => any> = {}\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n let patchedMethod = methodCache[prop]\n if (patchedMethod !== undefined) {\n return patchedMethod\n }\n\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n patchedMethod = {\n [prop]: (...args: unknown[]) => {\n try {\n onUse()\n } catch (err) {\n // We don't want to break the method even if our tracking errored.\n console.error(err)\n }\n\n return originalMethod.apply(target, args)\n },\n }[prop]\n\n methodCache[prop] = patchedMethod\n return patchedMethod\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n}\n\nexport const RENDER_STAGES_BY_DATA_KIND = {\n sessionData: RenderStage.ShellRuntime as const,\n staticLinkData: RenderStage.Static as const,\n runtimeLinkData: RenderStage.Runtime as const,\n}\n\nexport function applyOwnerStack(error: Error): Error {\n if (process.env.NODE_ENV !== 'production') {\n let ownerStack: string | undefined | null\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // captureOwnerStack() returns the owner stack for the current React\n // rendering context. Inside a cache scope this only includes the inner\n // component tree. The outer owner stack (captured before entering the\n // cache boundary in use-cache-wrapper.ts) is stored on the cache store.\n // We concatenate both to get the full component tree.\n const innerOwnerStack =\n getClientReact()?.captureOwnerStack?.() ??\n getServerReact()?.captureOwnerStack?.()\n\n switch (workUnitStore?.type) {\n case 'cache':\n case 'private-cache':\n ownerStack =\n (innerOwnerStack || '') + (workUnitStore.outerOwnerStack || '') ||\n undefined\n break\n case 'unstable-cache':\n case 'request':\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'generate-static-params':\n case undefined:\n ownerStack = innerOwnerStack\n break\n default:\n workUnitStore satisfies never\n }\n\n if (ownerStack) {\n let stack = ownerStack\n\n if (error.stack) {\n const frames: string[] = []\n\n for (const frame of error.stack.split('\\n').slice(1)) {\n if (frame.includes('react_stack_bottom_frame')) {\n break\n }\n\n frames.push(frame)\n }\n\n stack = '\\n' + frames.join('\\n') + stack\n }\n\n error.stack = error.name + ': ' + error.message + stack\n }\n }\n\n return error\n}\n"],"names":["RenderStage","workUnitAsyncStorage","getServerReact","getClientReact","ReflectAdapter","isHangingPromiseRejectionError","err","digest","HANGING_PROMISE_REJECTION","HangingPromiseRejectionError","Error","constructor","route","expression","CLIENT_HOOK_DYNAMIC","ClientHookDynamicError","isClientHookDynamicError","abortListenersBySignal","WeakMap","makeDynamicHangingPromise","signal","makeHangingPromiseWithError","makeUntrackedHangingPromise","makeRuntimeHangingPromise","workUnitStore","trackRuntimeDataAccessed","makeFallbackParamsHangingPromise","trackFallbackParamsAccessed","makeStageHangingPromise","trackRuntimeDataAccessedImpl","isFallbackParamAccess","type","runtimeDataAccessed","resolve","hintCell","shouldAttemptStaticPrefetch","isFallbackUpgradeable","current","trackIncompatibleShellContent","hasIncompatibleShellContent","makeClientHookHangingPromise","error","aborted","Promise","reject","hangingPromise","_","boundRejection","bind","currentListeners","get","push","listeners","set","addEventListener","i","length","once","catch","ignoreReject","makePromiseFromTrigger","trigger","value","promise","then","makeDevtoolsIOAwarePromise","underlying","requestStore","stage","stagedRendering","delayUntilStage","undefined","setTimeout","trackPromiseUsed","onUse","methodCache","Proxy","target","prop","receiver","patchedMethod","originalMethod","args","console","apply","RENDER_STAGES_BY_DATA_KIND","sessionData","ShellRuntime","staticLinkData","Static","runtimeLinkData","Runtime","applyOwnerStack","process","env","NODE_ENV","ownerStack","getStore","innerOwnerStack","captureOwnerStack","outerOwnerStack","stack","frames","frame","split","slice","includes","join","name","message"],"mappings":"AAAA,SACEA,WAAW,QAEN,gCAA+B;AAKtC,SAASC,oBAAoB,QAAQ,gDAA+C;AACpF,SAASC,cAAc,EAAEC,cAAc,QAAQ,4BAA2B;AAC1E,SAASC,cAAc,QAAQ,wCAAuC;AAEtE,OAAO,SAASC,+BACdC,GAAY;IAEZ,IAAI,OAAOA,QAAQ,YAAYA,QAAQ,QAAQ,CAAE,CAAA,YAAYA,GAAE,GAAI;QACjE,OAAO;IACT;IAEA,OAAOA,IAAIC,MAAM,KAAKC;AACxB;AAEA,MAAMA,4BAA4B;AAElC,MAAMC,qCAAqCC;IAGzCC,YACE,AAAgBC,KAAa,EAC7B,AAAgBC,UAAkB,CAClC;QACA,KAAK,CACH,CAAC,qBAAqB,EAAEA,WAAW,qGAAqG,EAAEA,WAAW,8KAA8K,EAAED,MAAM,EAAE,CAAC,QAJhUA,QAAAA,YACAC,aAAAA,iBAJFN,SAASC;IASzB;AACF;AAEA,MAAMM,sBAAsB;AAE5B,OAAO,MAAMC,+BAA+BL;IAG1CC,YAAYC,KAAa,EAAEC,UAAkB,CAAE;QAC7C,KAAK,CACH,CAAC,OAAO,EAAED,MAAM,kCAAkC,EAAEC,WAAW,uDAAuD,CAAC,GACrH,C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;gBACF;YACF,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAKA;gBACHyB,aAAaE;gBACb;YACF;gBACE1E;QACJ;QAEA,IAAIwE,YAAY;YACd,IAAIK,QAAQL;YAEZ,IAAIvD,MAAM4D,KAAK,EAAE;gBACf,MAAMC,SAAmB,EAAE;gBAE3B,KAAK,MAAMC,SAAS9D,MAAM4D,KAAK,CAACG,KAAK,CAAC,MAAMC,KAAK,CAAC,GAAI;oBACpD,IAAIF,MAAMG,QAAQ,CAAC,6BAA6B;wBAC9C;oBACF;oBAEAJ,OAAOnD,IAAI,CAACoD;gBACd;gBAEAF,QAAQ,OAAOC,OAAOK,IAAI,CAAC,QAAQN;YACrC;YAEA5D,MAAM4D,KAAK,GAAG5D,MAAMmE,IAAI,GAAG,OAAOnE,MAAMoE,OAAO,GAAGR;QACpD;IACF;IAEA,OAAO5D;AACT","ignoreList":[0]} |
@@ -14,3 +14,3 @@ import { loadEnvConfig } from '@next/env'; | ||
| const versionSuffix = logBundler ? ` (${bundlerName(getBundlerFromEnv())})` : ''; | ||
| Log.bootstrap(`${bold(purple(`${Log.prefixes.ready} Next.js ${"16.3.1-canary.10"}`))}${versionSuffix}`); | ||
| Log.bootstrap(`${bold(purple(`${Log.prefixes.ready} Next.js ${"16.3.1-canary.11"}`))}${versionSuffix}`); | ||
| if (appUrl) { | ||
@@ -17,0 +17,0 @@ Log.bootstrap(`- Local: ${appUrl}`); |
| import { LRUCache } from './lru-cache'; | ||
| import { createRequestResponseMocks } from './mock-request'; | ||
| import { HMR_MESSAGE_SENT_TO_BROWSER } from '../dev/hot-reloader-types'; | ||
| import { DevBundlerServiceSpan } from './trace/constants'; | ||
| import { subscribeRequestInsights } from './trace/request-insights'; | ||
| import { getTracer } from './trace/tracer'; | ||
| /** | ||
@@ -18,3 +20,5 @@ * The DevBundlerService provides an interface to perform tasks with the | ||
| // TODO: remove after ensure is pulled out of server | ||
| return await this.bundler.hotReloader.ensurePage(definition); | ||
| return await getTracer().trace(DevBundlerServiceSpan.ensurePage, { | ||
| spanName: 'compile route' | ||
| }, ()=>this.bundler.hotReloader.ensurePage(definition)); | ||
| }; | ||
@@ -21,0 +25,0 @@ this.logErrorWithOriginalStack = this.bundler.logErrorWithOriginalStack.bind(this.bundler); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/lib/dev-bundler-service.ts"],"sourcesContent":["import type { IncomingMessage } from 'http'\nimport type { DevBundler } from './router-utils/setup-dev-bundler'\nimport type { WorkerRequestHandler } from './types'\n\nimport { LRUCache } from './lru-cache'\nimport { createRequestResponseMocks } from './mock-request'\nimport {\n HMR_MESSAGE_SENT_TO_BROWSER,\n type HmrMessageSentToBrowser,\n type NextJsHotReloaderInterface,\n} from '../dev/hot-reloader-types'\nimport { subscribeRequestInsights } from './trace/request-insights'\n\n/**\n * The DevBundlerService provides an interface to perform tasks with the\n * bundler while in development.\n */\nexport class DevBundlerService {\n public appIsrManifestInner: InstanceType<typeof LRUCache<boolean>>\n public setCacheStatus: NextJsHotReloaderInterface['setCacheStatus']\n public setReactDebugChannel: NextJsHotReloaderInterface['setReactDebugChannel']\n public sendErrorsToBrowser: NextJsHotReloaderInterface['sendErrorsToBrowser']\n private unsubscribeRequestInsights?: () => void\n\n constructor(\n private readonly bundler: DevBundler,\n private readonly handler: WorkerRequestHandler,\n requestInsightsEnabled: boolean\n ) {\n this.appIsrManifestInner = new LRUCache(\n 8_000,\n\n function length() {\n return 16\n }\n )\n\n const { hotReloader } = bundler\n\n this.setCacheStatus = hotReloader.setCacheStatus.bind(hotReloader)\n this.setReactDebugChannel =\n hotReloader.setReactDebugChannel.bind(hotReloader)\n this.sendErrorsToBrowser = hotReloader.sendErrorsToBrowser.bind(hotReloader)\n\n if (requestInsightsEnabled) {\n this.unsubscribeRequestInsights = subscribeRequestInsights((insight) => {\n hotReloader.send({\n type: HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_INSIGHTS_UPDATE,\n insight,\n })\n })\n }\n }\n\n public close: NextJsHotReloaderInterface['close'] = () => {\n this.unsubscribeRequestInsights?.()\n this.bundler.hotReloader.close()\n }\n\n public ensurePage: typeof this.bundler.hotReloader.ensurePage = async (\n definition\n ) => {\n // TODO: remove after ensure is pulled out of server\n return await this.bundler.hotReloader.ensurePage(definition)\n }\n\n public getServerComponentsHmrRefreshHash(): string | undefined {\n return this.bundler.hotReloader.getServerComponentsHmrRefreshHash()\n }\n\n public logErrorWithOriginalStack =\n this.bundler.logErrorWithOriginalStack.bind(this.bundler)\n\n public async getFallbackErrorComponents(url?: string) {\n await this.bundler.hotReloader.buildFallbackError()\n // Build the error page to ensure the fallback is built too.\n // TODO: See if this can be moved into hotReloader or removed.\n await this.bundler.hotReloader.ensurePage({\n page: '/_error',\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n public async getCompilationError(page: string) {\n const errors = await this.bundler.hotReloader.getCompilationErrors(page)\n if (!errors) return\n\n // Return the very first error we found.\n return errors[0]\n }\n\n public async revalidate({\n urlPath,\n headers,\n opts: revalidateOpts,\n }: {\n urlPath: string\n headers: IncomingMessage['headers']\n opts: any\n }) {\n const mocked = createRequestResponseMocks({\n url: urlPath,\n headers,\n })\n\n await this.handler(mocked.req, mocked.res)\n await mocked.res.hasStreamed\n\n if (\n mocked.res.getHeader('x-nextjs-cache') !== 'REVALIDATED' &&\n mocked.res.statusCode !== 200 &&\n !(mocked.res.statusCode === 404 && revalidateOpts.unstable_onlyGenerated)\n ) {\n throw new Error(`Invalid response ${mocked.res.statusCode}`)\n }\n\n return {}\n }\n\n public get appIsrManifest() {\n const serializableManifest: Record<string, boolean> = {}\n\n for (const [key, value] of this.appIsrManifestInner) {\n serializableManifest[key] = value\n }\n\n return serializableManifest\n }\n\n public setIsrStatus(key: string, value: boolean | undefined) {\n if (value === undefined) {\n this.appIsrManifestInner.remove(key)\n } else {\n this.appIsrManifestInner.set(key, value)\n }\n\n // Only send the ISR manifest to legacy clients, i.e. Pages Router clients,\n // or App Router clients that have Cache Components disabled. The ISR\n // manifest is only used to inform the static indicator, which currently\n // does not provide useful information if Cache Components is enabled due to\n // its binary nature (i.e. it does not support showing info for partially\n // static pages).\n this.bundler?.hotReloader?.sendToLegacyClients({\n type: HMR_MESSAGE_SENT_TO_BROWSER.ISR_MANIFEST,\n data: this.appIsrManifest,\n })\n }\n\n public sendHmrMessage(message: HmrMessageSentToBrowser) {\n this.bundler.hotReloader.send(message)\n }\n}\n"],"names":["LRUCache","createRequestResponseMocks","HMR_MESSAGE_SENT_TO_BROWSER","subscribeRequestInsights","DevBundlerService","constructor","bundler","handler","requestInsightsEnabled","close","unsubscribeRequestInsights","hotReloader","ensurePage","definition","logErrorWithOriginalStack","bind","appIsrManifestInner","length","setCacheStatus","setReactDebugChannel","sendErrorsToBrowser","insight","send","type","REQUEST_INSIGHTS_UPDATE","getServerComponentsHmrRefreshHash","getFallbackErrorComponents","url","buildFallbackError","page","clientOnly","undefined","getCompilationError","errors","getCompilationErrors","revalidate","urlPath","headers","opts","revalidateOpts","mocked","req","res","hasStreamed","getHeader","statusCode","unstable_onlyGenerated","Error","appIsrManifest","serializableManifest","key","value","setIsrStatus","remove","set","sendToLegacyClients","ISR_MANIFEST","data","sendHmrMessage","message"],"mappings":"AAIA,SAASA,QAAQ,QAAQ,cAAa;AACtC,SAASC,0BAA0B,QAAQ,iBAAgB;AAC3D,SACEC,2BAA2B,QAGtB,4BAA2B;AAClC,SAASC,wBAAwB,QAAQ,2BAA0B;AAEnE;;;CAGC,GACD,OAAO,MAAMC;IAOXC,YACE,AAAiBC,OAAmB,EACpC,AAAiBC,OAA6B,EAC9CC,sBAA+B,CAC/B;aAHiBF,UAAAA;aACAC,UAAAA;aA4BZE,QAA6C;YAClD,IAAI,CAACC,0BAA0B,oBAA/B,IAAI,CAACA,0BAA0B,MAA/B,IAAI;YACJ,IAAI,CAACJ,OAAO,CAACK,WAAW,CAACF,KA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AgC,EAAE;QACtD,IAAI,CAACrD,OAAO,CAACK,WAAW,CAACW,IAAI,CAACqC;IAChC;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/lib/dev-bundler-service.ts"],"sourcesContent":["import type { IncomingMessage } from 'http'\nimport type { DevBundler } from './router-utils/setup-dev-bundler'\nimport type { WorkerRequestHandler } from './types'\n\nimport { LRUCache } from './lru-cache'\nimport { createRequestResponseMocks } from './mock-request'\nimport {\n HMR_MESSAGE_SENT_TO_BROWSER,\n type HmrMessageSentToBrowser,\n type NextJsHotReloaderInterface,\n} from '../dev/hot-reloader-types'\nimport { DevBundlerServiceSpan } from './trace/constants'\nimport { subscribeRequestInsights } from './trace/request-insights'\nimport { getTracer } from './trace/tracer'\n\n/**\n * The DevBundlerService provides an interface to perform tasks with the\n * bundler while in development.\n */\nexport class DevBundlerService {\n public appIsrManifestInner: InstanceType<typeof LRUCache<boolean>>\n public setCacheStatus: NextJsHotReloaderInterface['setCacheStatus']\n public setReactDebugChannel: NextJsHotReloaderInterface['setReactDebugChannel']\n public sendErrorsToBrowser: NextJsHotReloaderInterface['sendErrorsToBrowser']\n private unsubscribeRequestInsights?: () => void\n\n constructor(\n private readonly bundler: DevBundler,\n private readonly handler: WorkerRequestHandler,\n requestInsightsEnabled: boolean\n ) {\n this.appIsrManifestInner = new LRUCache(\n 8_000,\n\n function length() {\n return 16\n }\n )\n\n const { hotReloader } = bundler\n\n this.setCacheStatus = hotReloader.setCacheStatus.bind(hotReloader)\n this.setReactDebugChannel =\n hotReloader.setReactDebugChannel.bind(hotReloader)\n this.sendErrorsToBrowser = hotReloader.sendErrorsToBrowser.bind(hotReloader)\n\n if (requestInsightsEnabled) {\n this.unsubscribeRequestInsights = subscribeRequestInsights((insight) => {\n hotReloader.send({\n type: HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_INSIGHTS_UPDATE,\n insight,\n })\n })\n }\n }\n\n public close: NextJsHotReloaderInterface['close'] = () => {\n this.unsubscribeRequestInsights?.()\n this.bundler.hotReloader.close()\n }\n\n public ensurePage: typeof this.bundler.hotReloader.ensurePage = async (\n definition\n ) => {\n // TODO: remove after ensure is pulled out of server\n return await getTracer().trace(\n DevBundlerServiceSpan.ensurePage,\n { spanName: 'compile route' },\n () => this.bundler.hotReloader.ensurePage(definition)\n )\n }\n\n public getServerComponentsHmrRefreshHash(): string | undefined {\n return this.bundler.hotReloader.getServerComponentsHmrRefreshHash()\n }\n\n public logErrorWithOriginalStack =\n this.bundler.logErrorWithOriginalStack.bind(this.bundler)\n\n public async getFallbackErrorComponents(url?: string) {\n await this.bundler.hotReloader.buildFallbackError()\n // Build the error page to ensure the fallback is built too.\n // TODO: See if this can be moved into hotReloader or removed.\n await this.bundler.hotReloader.ensurePage({\n page: '/_error',\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n public async getCompilationError(page: string) {\n const errors = await this.bundler.hotReloader.getCompilationErrors(page)\n if (!errors) return\n\n // Return the very first error we found.\n return errors[0]\n }\n\n public async revalidate({\n urlPath,\n headers,\n opts: revalidateOpts,\n }: {\n urlPath: string\n headers: IncomingMessage['headers']\n opts: any\n }) {\n const mocked = createRequestResponseMocks({\n url: urlPath,\n headers,\n })\n\n await this.handler(mocked.req, mocked.res)\n await mocked.res.hasStreamed\n\n if (\n mocked.res.getHeader('x-nextjs-cache') !== 'REVALIDATED' &&\n mocked.res.statusCode !== 200 &&\n !(mocked.res.statusCode === 404 && revalidateOpts.unstable_onlyGenerated)\n ) {\n throw new Error(`Invalid response ${mocked.res.statusCode}`)\n }\n\n return {}\n }\n\n public get appIsrManifest() {\n const serializableManifest: Record<string, boolean> = {}\n\n for (const [key, value] of this.appIsrManifestInner) {\n serializableManifest[key] = value\n }\n\n return serializableManifest\n }\n\n public setIsrStatus(key: string, value: boolean | undefined) {\n if (value === undefined) {\n this.appIsrManifestInner.remove(key)\n } else {\n this.appIsrManifestInner.set(key, value)\n }\n\n // Only send the ISR manifest to legacy clients, i.e. Pages Router clients,\n // or App Router clients that have Cache Components disabled. The ISR\n // manifest is only used to inform the static indicator, which currently\n // does not provide useful information if Cache Components is enabled due to\n // its binary nature (i.e. it does not support showing info for partially\n // static pages).\n this.bundler?.hotReloader?.sendToLegacyClients({\n type: HMR_MESSAGE_SENT_TO_BROWSER.ISR_MANIFEST,\n data: this.appIsrManifest,\n })\n }\n\n public sendHmrMessage(message: HmrMessageSentToBrowser) {\n this.bundler.hotReloader.send(message)\n }\n}\n"],"names":["LRUCache","createRequestResponseMocks","HMR_MESSAGE_SENT_TO_BROWSER","DevBundlerServiceSpan","subscribeRequestInsights","getTracer","DevBundlerService","constructor","bundler","handler","requestInsightsEnabled","close","unsubscribeRequestInsights","hotReloader","ensurePage","definition","trace","spanName","logErrorWithOriginalStack","bind","appIsrManifestInner","length","setCacheStatus","setReactDebugChannel","sendErrorsToBrowser","insight","send","type","REQUEST_INSIGHTS_UPDATE","getServerComponentsHmrRefreshHash","getFallbackErrorComponents","url","buildFallbackError","page","clientOnly","undefined","getCompilationError","errors","getCompilationErrors","revalidate","urlPath","headers","opts","revalidateOpts","mocked","req","res","hasStreamed","getHeader","statusCode","unstable_onlyGenerated","Error","appIsrManifest","serializableManifest","key","value","setIsrStatus","remove","set","sendToLegacyClients","ISR_MANIFEST","data","sendHmrMessage","message"],"mappings":"AAIA,SAASA,QAAQ,QAAQ,cAAa;AACtC,SAASC,0BAA0B,QAAQ,iBAAgB;AAC3D,SACEC,2BAA2B,QAGtB,4BAA2B;AAClC,SAASC,qBAAqB,QAAQ,oBAAmB;AACzD,SAASC,wBAAwB,QAAQ,2BAA0B;AACnE,SAASC,SAAS,QAAQ,iBAAgB;AAE1C;;;CAGC,GACD,OAAO,MAAMC;IAOXC,YACE,AAAiBC,OAAmB,EACpC,AAAiBC,OAA6B,EAC9CC,sBAA+B,CAC/B;aAHiBF,UAAAA;aACAC,UAAAA;aA4BZE,QAA6C;YAClD,IAAI,CAACC,0BAA0B,oBAA/B,IAAI,CAACA,0BAA0B,MAA/B,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BAAzB,0BAA2B8C,mBAAmB,CAAC;YAC7ChC,MAAMzB,4BAA4B0D,YAAY;YAC9CC,MAAM,IAAI,CAACT,cAAc;QAC3B;IACF;IAEOU,eAAeC,OAAgC,EAAE;QACtD,IAAI,CAACvD,OAAO,CAACK,WAAW,CAACa,IAAI,CAACqC;IAChC;AACF","ignoreList":[0]} |
| import { NEXT_CACHE_IMPLICIT_TAG_ID } from '../../lib/constants'; | ||
| import { getCacheHandlerEntries } from '../use-cache/handlers'; | ||
| import { encodeCacheTag } from './encode-cache-tag'; | ||
| import { encodeHeaderSafe } from './encode-header-safe'; | ||
| import { createLazyResult } from './lazy-result'; | ||
@@ -55,3 +55,3 @@ const getDerivedTags = (pathname)=>{ | ||
| for (let tag of derivedTags){ | ||
| tag = encodeCacheTag(`${NEXT_CACHE_IMPLICIT_TAG_ID}${tag}`); | ||
| tag = encodeHeaderSafe(`${NEXT_CACHE_IMPLICIT_TAG_ID}${tag}`); | ||
| tags.add(tag); | ||
@@ -62,3 +62,3 @@ } | ||
| if (pathname && (!fallbackRouteParams || fallbackRouteParams.size === 0)) { | ||
| const tag = encodeCacheTag(`${NEXT_CACHE_IMPLICIT_TAG_ID}${pathname}`); | ||
| const tag = encodeHeaderSafe(`${NEXT_CACHE_IMPLICIT_TAG_ID}${pathname}`); | ||
| tags.add(tag); | ||
@@ -65,0 +65,0 @@ } |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/lib/implicit-tags.ts"],"sourcesContent":["import { NEXT_CACHE_IMPLICIT_TAG_ID } from '../../lib/constants'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\nimport { getCacheHandlerEntries } from '../use-cache/handlers'\nimport { encodeCacheTag } from './encode-cache-tag'\nimport { createLazyResult, type LazyResult } from './lazy-result'\n\nexport interface ImplicitTags {\n /**\n * For legacy usage, the implicit tags are passed to the incremental cache\n * handler in `get` calls.\n */\n readonly tags: string[]\n\n /**\n * Modern cache handlers don't receive implicit tags. Instead, the implicit\n * tags' expirations are stored in the work unit store, and used to compare\n * with a cache entry's timestamp.\n *\n * Note: This map contains lazy results so that we can evaluate them when the\n * first cache entry is read. It allows us to skip fetching the expiration\n * values if no caches are read at all.\n */\n readonly expirationsByCacheKind: Map<string, LazyResult<number>>\n}\n\nconst getDerivedTags = (pathname: string): string[] => {\n const derivedTags: string[] = [`/layout`]\n\n // we automatically add the current path segments as tags\n // for revalidatePath handling\n if (pathname.startsWith('/')) {\n let end = pathname.indexOf('/', 1)\n\n while (true) {\n if (end === -1) {\n end = pathname.length\n }\n\n let curPathname = pathname.slice(0, end)\n if (curPathname) {\n // all derived tags other than the page are layout tags\n if (!curPathname.endsWith('/page') && !curPathname.endsWith('/route')) {\n curPathname = `${curPathname}${\n !curPathname.endsWith('/') ? '/' : ''\n }layout`\n }\n derivedTags.push(curPathname)\n }\n\n if (end === pathname.length) {\n break\n }\n end = pathname.indexOf('/', end + 1)\n }\n }\n return derivedTags\n}\n\n/**\n * Creates a map with lazy results that fetch the expiration value for the given\n * tags and respective cache kind when they're awaited for the first time.\n */\nfunction createTagsExpirationsByCacheKind(\n tags: string[]\n): Map<string, LazyResult<number>> {\n const expirationsByCacheKind = new Map<string, LazyResult<number>>()\n const cacheHandlers = getCacheHandlerEntries()\n\n if (cacheHandlers) {\n for (const [kind, cacheHandler] of cacheHandlers) {\n if ('getExpiration' in cacheHandler) {\n expirationsByCacheKind.set(\n kind,\n createLazyResult(async () => cacheHandler.getExpiration(tags))\n )\n }\n }\n }\n\n return expirationsByCacheKind\n}\n\nexport async function getImplicitTags(\n page: string,\n pathname: string,\n fallbackRouteParams: null | OpaqueFallbackRouteParams\n): Promise<ImplicitTags> {\n const tags = new Set<string>()\n\n // Add the derived tags from the page. Encode each tag so a non-ASCII\n // pathname doesn't trip header validation when written to\n // `x-next-cache-tags`. Idempotent on already-ASCII input.\n const derivedTags = getDerivedTags(page)\n for (let tag of derivedTags) {\n tag = encodeCacheTag(`${NEXT_CACHE_IMPLICIT_TAG_ID}${tag}`)\n tags.add(tag)\n }\n\n // Add the tags from the pathname. If the route has unknown params, we don't\n // want to add the pathname as a tag, as it will be invalid.\n if (pathname && (!fallbackRouteParams || fallbackRouteParams.size === 0)) {\n const tag = encodeCacheTag(`${NEXT_CACHE_IMPLICIT_TAG_ID}${pathname}`)\n tags.add(tag)\n }\n\n if (tags.has(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)) {\n tags.add(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)\n }\n\n if (tags.has(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)) {\n tags.add(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)\n }\n\n const tagsArray = Array.from(tags)\n return {\n tags: tagsArray,\n expirationsByCacheKind: createTagsExpirationsByCacheKind(tagsArray),\n }\n}\n"],"names":["NEXT_CACHE_IMPLICIT_TAG_ID","getCacheHandlerEntries","encodeCacheTag","createLazyResult","getDerivedTags","pathname","derivedTags","startsWith","end","indexOf","length","curPathname","slice","endsWith","push","createTagsExpirationsByCacheKind","tags","expirationsByCacheKind","Map","cacheHandlers","kind","cacheHandler","set","getExpiration","getImplicitTags","page","fallbackRouteParams","Set","tag","add","size","has","tagsArray","Array","from"],"mappings":"AAAA,SAASA,0BAA0B,QAAQ,sBAAqB;AAEhE,SAASC,sBAAsB,QAAQ,wBAAuB;AAC9D,SAASC,cAAc,QAAQ,qBAAoB;AACnD,SAASC,gBAAgB,QAAyB,gBAAe;AAqBjE,MAAMC,iBAAiB,CAACC;IACtB,MAAMC,cAAwB;QAAC,CAAC,OAAO,CAAC;KAAC;IAEzC,yDAAyD;IACzD,8BAA8B;IAC9B,IAAID,SAASE,UAAU,CAAC,MAAM;QAC5B,IAAIC,MAAMH,SAASI,OAAO,CAAC,KAAK;QAEhC,MAAO,KAAM;YACX,IAAID,QAAQ,CAAC,GAAG;gBACdA,MAAMH,SAASK,MAAM;YACvB;YAEA,IAAIC,cAAcN,SAASO,KAAK,CAAC,GAAGJ;YAC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AG7B,2BAA2B,MAAM,CAAC;IAChD;IAEA,IAAIgB,KAAKe,GAAG,CAAC,GAAG/B,2BAA2B,MAAM,CAAC,GAAG;QACnDgB,KAAKa,GAAG,CAAC,GAAG7B,2BAA2B,CAAC,CAAC;IAC3C;IAEA,MAAMgC,YAAYC,MAAMC,IAAI,CAAClB;IAC7B,OAAO;QACLA,MAAMgB;QACNf,wBAAwBF,iCAAiCiB;IAC3D;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/lib/implicit-tags.ts"],"sourcesContent":["import { NEXT_CACHE_IMPLICIT_TAG_ID } from '../../lib/constants'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\nimport { getCacheHandlerEntries } from '../use-cache/handlers'\nimport { encodeHeaderSafe } from './encode-header-safe'\nimport { createLazyResult, type LazyResult } from './lazy-result'\n\nexport interface ImplicitTags {\n /**\n * For legacy usage, the implicit tags are passed to the incremental cache\n * handler in `get` calls.\n */\n readonly tags: string[]\n\n /**\n * Modern cache handlers don't receive implicit tags. Instead, the implicit\n * tags' expirations are stored in the work unit store, and used to compare\n * with a cache entry's timestamp.\n *\n * Note: This map contains lazy results so that we can evaluate them when the\n * first cache entry is read. It allows us to skip fetching the expiration\n * values if no caches are read at all.\n */\n readonly expirationsByCacheKind: Map<string, LazyResult<number>>\n}\n\nconst getDerivedTags = (pathname: string): string[] => {\n const derivedTags: string[] = [`/layout`]\n\n // we automatically add the current path segments as tags\n // for revalidatePath handling\n if (pathname.startsWith('/')) {\n let end = pathname.indexOf('/', 1)\n\n while (true) {\n if (end === -1) {\n end = pathname.length\n }\n\n let curPathname = pathname.slice(0, end)\n if (curPathname) {\n // all derived tags other than the page are layout tags\n if (!curPathname.endsWith('/page') && !curPathname.endsWith('/route')) {\n curPathname = `${curPathname}${\n !curPathname.endsWith('/') ? '/' : ''\n }layout`\n }\n derivedTags.push(curPathname)\n }\n\n if (end === pathname.length) {\n break\n }\n end = pathname.indexOf('/', end + 1)\n }\n }\n return derivedTags\n}\n\n/**\n * Creates a map with lazy results that fetch the expiration value for the given\n * tags and respective cache kind when they're awaited for the first time.\n */\nfunction createTagsExpirationsByCacheKind(\n tags: string[]\n): Map<string, LazyResult<number>> {\n const expirationsByCacheKind = new Map<string, LazyResult<number>>()\n const cacheHandlers = getCacheHandlerEntries()\n\n if (cacheHandlers) {\n for (const [kind, cacheHandler] of cacheHandlers) {\n if ('getExpiration' in cacheHandler) {\n expirationsByCacheKind.set(\n kind,\n createLazyResult(async () => cacheHandler.getExpiration(tags))\n )\n }\n }\n }\n\n return expirationsByCacheKind\n}\n\nexport async function getImplicitTags(\n page: string,\n pathname: string,\n fallbackRouteParams: null | OpaqueFallbackRouteParams\n): Promise<ImplicitTags> {\n const tags = new Set<string>()\n\n // Add the derived tags from the page. Encode each tag so a non-ASCII\n // pathname doesn't trip header validation when written to\n // `x-next-cache-tags`. Idempotent on already-ASCII input.\n const derivedTags = getDerivedTags(page)\n for (let tag of derivedTags) {\n tag = encodeHeaderSafe(`${NEXT_CACHE_IMPLICIT_TAG_ID}${tag}`)\n tags.add(tag)\n }\n\n // Add the tags from the pathname. If the route has unknown params, we don't\n // want to add the pathname as a tag, as it will be invalid.\n if (pathname && (!fallbackRouteParams || fallbackRouteParams.size === 0)) {\n const tag = encodeHeaderSafe(`${NEXT_CACHE_IMPLICIT_TAG_ID}${pathname}`)\n tags.add(tag)\n }\n\n if (tags.has(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)) {\n tags.add(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)\n }\n\n if (tags.has(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)) {\n tags.add(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)\n }\n\n const tagsArray = Array.from(tags)\n return {\n tags: tagsArray,\n expirationsByCacheKind: createTagsExpirationsByCacheKind(tagsArray),\n }\n}\n"],"names":["NEXT_CACHE_IMPLICIT_TAG_ID","getCacheHandlerEntries","encodeHeaderSafe","createLazyResult","getDerivedTags","pathname","derivedTags","startsWith","end","indexOf","length","curPathname","slice","endsWith","push","createTagsExpirationsByCacheKind","tags","expirationsByCacheKind","Map","cacheHandlers","kind","cacheHandler","set","getExpiration","getImplicitTags","page","fallbackRouteParams","Set","tag","add","size","has","tagsArray","Array","from"],"mappings":"AAAA,SAASA,0BAA0B,QAAQ,sBAAqB;AAEhE,SAASC,sBAAsB,QAAQ,wBAAuB;AAC9D,SAASC,gBAAgB,QAAQ,uBAAsB;AACvD,SAASC,gBAAgB,QAAyB,gBAAe;AAqBjE,MAAMC,iBAAiB,CAACC;IACtB,MAAMC,cAAwB;QAAC,CAAC,OAAO,CAAC;KAAC;IAEzC,yDAAyD;IACzD,8BAA8B;IAC9B,IAAID,SAASE,UAAU,CAAC,MAAM;QAC5B,IAAIC,MAAMH,SAASI,OAAO,CAAC,KAAK;QAEhC,MAAO,KAAM;YACX,IAAID,QAAQ,CAAC,GAAG;gBACdA,MAAMH,SAASK,MAAM;YACvB;YAEA,IAAIC,cAAcN,SAASO,KAAK,CAAC,GAAGJ;YACpC,IAAIG,aAAa;gBACf,uDAAuD;gBACvD,IAAI,CAACA,YAAYE,QAAQ,CAAC,YAAY,CAACF,YAAYE,QAAQ,CAAC,WAAW;oBACrEF,cAAc,GAAGA,cACf,CAACA,YAAYE,QAAQ,CAAC,OAAO,MAAM,GACpC,MAAM,CAAC;gBACV;gBACAP,YAAYQ,IAAI,CAACH;YACnB;YAEA,IAAIH,QAAQH,SAASK,MAAM,EAAE;gBAC3B;YACF;YACAF,MAAMH,SAASI,OAAO,CAAC,KAAKD,MAAM;QACpC;IACF;IACA,OAAOF;AACT;AAEA;;;CAGC,GACD,SAASS,iCACPC,IAAc;IAEd,MAAMC,yBAAyB,IAAIC;IACnC,MAAMC,gBAAgBlB;IAEtB,IAAIkB,eAAe;QACjB,KAAK,MAAM,CAACC,MAAMC,aAAa,IAAIF,cAAe;YAChD,IAAI,mBAAmBE,cAAc;gBACnCJ,uBAAuBK,GAAG,CACxBF,MACAjB,iBAAiB,UAAYkB,aAAaE,aAAa,CAACP;YAE5D;QACF;IACF;IAEA,OAAOC;AACT;AAEA,OAAO,eAAeO,gBACpBC,IAAY,EACZpB,QAAgB,EAChBqB,mBAAqD;IAErD,MAAMV,OAAO,IAAIW;IAEjB,qEAAqE;IACrE,0DAA0D;IAC1D,0DAA0D;IAC1D,MAAMrB,cAAcF,eAAeqB;IACnC,KAAK,IAAIG,OAAOtB,YAAa;QAC3BsB,MAAM1B,iBAAiB,GAAGF,6BAA6B4B,KAAK;QAC5DZ,KAAKa,GAAG,CAACD;IACX;IAEA,4EAA4E;IAC5E,4DAA4D;IAC5D,IAAIvB,YAAa,CAAA,CAACqB,uBAAuBA,oBAAoBI,IAAI,KAAK,CAAA,GAAI;QACxE,MAAMF,MAAM1B,iBAAiB,GAAGF,6BAA6BK,UAAU;QACvEW,KAAKa,GAAG,CAACD;IACX;IAEA,IAAIZ,KAAKe,GAAG,CAAC,GAAG/B,2BAA2B,CAAC,CAAC,GAAG;QAC9CgB,KAAKa,GAAG,CAAC,GAAG7B,2BAA2B,MAAM,CAAC;IAChD;IAEA,IAAIgB,KAAKe,GAAG,CAAC,GAAG/B,2BAA2B,MAAM,CAAC,GAAG;QACnDgB,KAAKa,GAAG,CAAC,GAAG7B,2BAA2B,CAAC,CAAC;IAC3C;IAEA,MAAMgC,YAAYC,MAAMC,IAAI,CAAClB;IAC7B,OAAO;QACLA,MAAMgB;QACNf,wBAAwBF,iCAAiCiB;IAC3D;AACF","ignoreList":[0]} |
@@ -1,15 +0,1 @@ | ||
| export function hasNonRootStaticParams(params, rootParams, fallbackParams) { | ||
| for(const paramName in params){ | ||
| if (!Object.hasOwn(rootParams, paramName) && isStaticParam(paramName, fallbackParams)) { | ||
| return true; | ||
| } | ||
| } | ||
| return false; | ||
| } | ||
| function isStaticParam(paramName, fallbackParams) { | ||
| // NOTE: Assume that undefined fallback params mean that all of the params are static. | ||
| if (!fallbackParams) return true; | ||
| // If the param isn't a fallback param, it must be static. | ||
| return !fallbackParams.has(paramName); | ||
| } | ||
| export function allParamsAreRootParams(underlyingParams, rootParams) { | ||
@@ -16,0 +2,0 @@ for(const paramName in underlyingParams){ |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/lib/params-utils.ts"],"sourcesContent":["import type { OpaqueFallbackRouteParams } from '../request/fallback-params'\nimport type { Params } from '../request/params'\n\nexport function hasNonRootStaticParams(\n params: Params,\n rootParams: Params,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined\n) {\n for (const paramName in params) {\n if (\n !Object.hasOwn(rootParams, paramName) &&\n isStaticParam(paramName, fallbackParams)\n ) {\n return true\n }\n }\n return false\n}\n\nfunction isStaticParam(\n paramName: string,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined\n) {\n // NOTE: Assume that undefined fallback params mean that all of the params are static.\n if (!fallbackParams) return true\n // If the param isn't a fallback param, it must be static.\n return !fallbackParams.has(paramName)\n}\n\nexport function allParamsAreRootParams(\n underlyingParams: Params,\n rootParams: Params\n) {\n for (const paramName in underlyingParams) {\n if (!Object.hasOwn(rootParams, paramName)) {\n return false\n }\n }\n return true\n}\n\nexport function isEmptyParams(params: Params): boolean {\n for (const _paramKey in params) {\n return false\n }\n return true\n}\n\nexport function hasFallbackRouteParams(\n underlyingParams: Params,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined\n): boolean {\n if (fallbackParams) {\n for (let key in underlyingParams) {\n if (fallbackParams.has(key)) {\n return true\n }\n }\n }\n return false\n}\n"],"names":["hasNonRootStaticParams","params","rootParams","fallbackParams","paramName","Object","hasOwn","isStaticParam","has","allParamsAreRootParams","underlyingParams","isEmptyParams","_paramKey","hasFallbackRouteParams","key"],"mappings":"AAGA,OAAO,SAASA,uBACdC,MAAc,EACdC,UAAkB,EAClBC,cAA4D;IAE5D,IAAK,MAAMC,aAAaH,OAAQ;QAC9B,IACE,CAACI,OAAOC,MAAM,CAACJ,YAAYE,cAC3BG,cAAcH,WAAWD,iBACzB;YACA,OAAO;QACT;IACF;IACA,OAAO;AACT;AAEA,SAASI,cACPH,SAAiB,EACjBD,cAA4D;IAE5D,sFAAsF;IACtF,IAAI,CAACA,gBAAgB,OAAO;IAC5B,0DAA0D;IAC1D,OAAO,CAACA,eAAeK,GAAG,CAACJ;AAC7B;AAEA,OAAO,SAASK,uBACdC,gBAAwB,EACxBR,UAAkB;IAElB,IAAK,MAAME,aAAaM,iBAAkB;QACxC,IAAI,CAACL,OAAOC,MAAM,CAACJ,YAAYE,YAAY;YACzC,OAAO;QACT;IACF;IACA,OAAO;AACT;AAEA,OAAO,SAASO,cAAcV,MAAc;IAC1C,IAAK,MAAMW,aAAaX,OAAQ;QAC9B,OAAO;IACT;IACA,OAAO;AACT;AAEA,OAAO,SAASY,uBACdH,gBAAwB,EACxBP,cAA4D;IAE5D,IAAIA,gBAAgB;QAClB,IAAK,IAAIW,OAAOJ,iBAAkB;YAChC,IAAIP,eAAeK,GAAG,CAACM,MAAM;gBAC3B,OAAO;YACT;QACF;IACF;IACA,OAAO;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/lib/params-utils.ts"],"sourcesContent":["import type { OpaqueFallbackRouteParams } from '../request/fallback-params'\nimport type { Params } from '../request/params'\n\nexport function allParamsAreRootParams(\n underlyingParams: Params,\n rootParams: Params\n) {\n for (const paramName in underlyingParams) {\n if (!Object.hasOwn(rootParams, paramName)) {\n return false\n }\n }\n return true\n}\n\nexport function isEmptyParams(params: Params): boolean {\n for (const _paramKey in params) {\n return false\n }\n return true\n}\n\nexport function hasFallbackRouteParams(\n underlyingParams: Params,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined\n): boolean {\n if (fallbackParams) {\n for (let key in underlyingParams) {\n if (fallbackParams.has(key)) {\n return true\n }\n }\n }\n return false\n}\n"],"names":["allParamsAreRootParams","underlyingParams","rootParams","paramName","Object","hasOwn","isEmptyParams","params","_paramKey","hasFallbackRouteParams","fallbackParams","key","has"],"mappings":"AAGA,OAAO,SAASA,uBACdC,gBAAwB,EACxBC,UAAkB;IAElB,IAAK,MAAMC,aAAaF,iBAAkB;QACxC,IAAI,CAACG,OAAOC,MAAM,CAACH,YAAYC,YAAY;YACzC,OAAO;QACT;IACF;IACA,OAAO;AACT;AAEA,OAAO,SAASG,cAAcC,MAAc;IAC1C,IAAK,MAAMC,aAAaD,OAAQ;QAC9B,OAAO;IACT;IACA,OAAO;AACT;AAEA,OAAO,SAASE,uBACdR,gBAAwB,EACxBS,cAA4D;IAE5D,IAAIA,gBAAgB;QAClB,IAAK,IAAIC,OAAOV,iBAAkB;YAChC,IAAIS,eAAeE,GAAG,CAACD,MAAM;gBAC3B,OAAO;YACT;QACF;IACF;IACA,OAAO;AACT","ignoreList":[0]} |
@@ -13,3 +13,3 @@ import { AppRenderSpan, NextNodeServerSpan } from './trace/constants'; | ||
| import { RenderStage } from '../app-render/staged-rendering'; | ||
| import { encodeCacheTag } from './encode-cache-tag'; | ||
| import { encodeHeaderSafe } from './encode-header-safe'; | ||
| const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'; | ||
@@ -93,3 +93,3 @@ /** | ||
| // validation. Length is checked on the raw input above. | ||
| validTags.push(encodeCacheTag(tag)); | ||
| validTags.push(encodeHeaderSafe(tag)); | ||
| } | ||
@@ -96,0 +96,0 @@ if (validTags.length > NEXT_CACHE_TAG_MAX_ITEMS) { |
@@ -112,3 +112,3 @@ // Start CPU profile if it wasn't already started. | ||
| let { port } = serverOptions; | ||
| process.title = `next-server (v${"16.3.1-canary.10"})`; | ||
| process.title = `next-server (v${"16.3.1-canary.11"})`; | ||
| let handlersReady = ()=>{}; | ||
@@ -115,0 +115,0 @@ let handlersError = ()=>{}; |
@@ -93,2 +93,11 @@ /** | ||
| }(AppRenderSpan || {}); | ||
| var DevRouteMatcherManagerSpan = /*#__PURE__*/ function(DevRouteMatcherManagerSpan) { | ||
| DevRouteMatcherManagerSpan["ensureRoute"] = "DevRouteMatcherManager.ensureRoute"; | ||
| DevRouteMatcherManagerSpan["reloadMatchers"] = "DevRouteMatcherManager.reloadMatchers"; | ||
| return DevRouteMatcherManagerSpan; | ||
| }(DevRouteMatcherManagerSpan || {}); | ||
| var DevBundlerServiceSpan = /*#__PURE__*/ function(DevBundlerServiceSpan) { | ||
| DevBundlerServiceSpan["ensurePage"] = "DevBundlerService.ensurePage"; | ||
| return DevBundlerServiceSpan; | ||
| }(DevBundlerServiceSpan || {}); | ||
| var RouterSpan = /*#__PURE__*/ function(RouterSpan) { | ||
@@ -141,4 +150,4 @@ RouterSpan["executeRoute"] = "Router.executeRoute"; | ||
| ]); | ||
| export { BaseServerSpan, LoadComponentsSpan, NextServerSpan, NextNodeServerSpan, StartServerSpan, RenderSpan, RouterSpan, AppRenderSpan, NodeSpan, AppRouteRouteHandlersSpan, ResolveMetadataSpan, MiddlewareSpan, }; | ||
| export { BaseServerSpan, LoadComponentsSpan, NextServerSpan, NextNodeServerSpan, StartServerSpan, RenderSpan, RouterSpan, AppRenderSpan, DevRouteMatcherManagerSpan, DevBundlerServiceSpan, NodeSpan, AppRouteRouteHandlersSpan, ResolveMetadataSpan, MiddlewareSpan, }; | ||
| //# sourceMappingURL=constants.js.map |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/server/lib/trace/constants.ts"],"sourcesContent":["/**\n * Contains predefined constants for the trace span name in next/server.\n *\n * Currently, next/server/tracer is internal implementation only for tracking\n * next.js's implementation only with known span names defined here.\n **/\n\n// eslint typescript has a bug with TS enums\n\nenum BaseServerSpan {\n handleRequest = 'BaseServer.handleRequest',\n run = 'BaseServer.run',\n pipe = 'BaseServer.pipe',\n getStaticHTML = 'BaseServer.getStaticHTML',\n render = 'BaseServer.render',\n renderToResponseWithComponents = 'BaseServer.renderToResponseWithComponents',\n renderToResponse = 'BaseServer.renderToResponse',\n renderToHTML = 'BaseServer.renderToHTML',\n renderError = 'BaseServer.renderError',\n renderErrorToResponse = 'BaseServer.renderErrorToResponse',\n renderErrorToHTML = 'BaseServer.renderErrorToHTML',\n render404 = 'BaseServer.render404',\n}\n\nenum LoadComponentsSpan {\n loadDefaultErrorComponents = 'LoadComponents.loadDefaultErrorComponents',\n loadComponents = 'LoadComponents.loadComponents',\n}\n\nenum NextServerSpan {\n getRequestHandler = 'NextServer.getRequestHandler',\n getRequestHandlerWithMetadata = 'NextServer.getRequestHandlerWithMetadata',\n getServer = 'NextServer.getServer',\n getServerRequestHandler = 'NextServer.getServerRequestHandler',\n createServer = 'createServer.createServer',\n}\n\nenum NextNodeServerSpan {\n compression = 'NextNodeServer.compression',\n getBuildId = 'NextNodeServer.getBuildId',\n createComponentTree = 'NextNodeServer.createComponentTree',\n clientComponentLoading = 'NextNodeServer.clientComponentLoading',\n getLayoutOrPageModule = 'NextNodeServer.getLayoutOrPageModule',\n generateStaticRoutes = 'NextNodeServer.generateStaticRoutes',\n generateFsStaticRoutes = 'NextNodeServer.generateFsStaticRoutes',\n generatePublicRoutes = 'NextNodeServer.generatePublicRoutes',\n generateImageRoutes = 'NextNodeServer.generateImageRoutes.route',\n sendRenderResult = 'NextNodeServer.sendRenderResult',\n proxyRequest = 'NextNodeServer.proxyRequest',\n runApi = 'NextNodeServer.runApi',\n render = 'NextNodeServer.render',\n renderHTML = 'NextNodeServer.renderHTML',\n imageOptimizer = 'NextNodeServer.imageOptimizer',\n getPagePath = 'NextNodeServer.getPagePath',\n getRoutesManifest = 'NextNodeServer.getRoutesManifest',\n findPageComponents = 'NextNodeServer.findPageComponents',\n getFontManifest = 'NextNodeServer.getFontManifest',\n getServerComponentManifest = 'NextNodeServer.getServerComponentManifest',\n getRequestHandler = 'NextNodeServer.getRequestHandler',\n renderToHTML = 'NextNodeServer.renderToHTML',\n renderError = 'NextNodeServer.renderError',\n renderErrorToHTML = 'NextNodeServer.renderErrorToHTML',\n render404 = 'NextNodeServer.render404',\n startResponse = 'NextNodeServer.startResponse',\n\n // nested inner span, does not require parent scope name\n route = 'route',\n onProxyReq = 'onProxyReq',\n apiResolver = 'apiResolver',\n internalFetch = 'internalFetch',\n}\n\nenum StartServerSpan {\n startServer = 'startServer.startServer',\n}\n\nenum RenderSpan {\n getServerSideProps = 'Render.getServerSideProps',\n getStaticProps = 'Render.getStaticProps',\n renderToString = 'Render.renderToString',\n renderDocument = 'Render.renderDocument',\n createBodyResult = 'Render.createBodyResult',\n}\n\nenum AppRenderSpan {\n renderToString = 'AppRender.renderToString',\n renderToReadableStream = 'AppRender.renderToReadableStream',\n getBodyResult = 'AppRender.getBodyResult',\n fetch = 'AppRender.fetch',\n waitShellReady = 'AppRender.waitShellReady',\n renderToNodeFizzStream = 'AppRender.renderToNodeFizzStream',\n instantInsights = 'AppRender.instantInsights',\n instantInsightsPrepareValidation = 'AppRender.instantInsights.prepareValidation',\n instantInsightsRunValidation = 'AppRender.instantInsights.runValidation',\n}\n\nenum RouterSpan {\n executeRoute = 'Router.executeRoute',\n}\n\nenum NodeSpan {\n runHandler = 'Node.runHandler',\n}\n\nenum AppRouteRouteHandlersSpan {\n runHandler = 'AppRouteRouteHandlers.runHandler',\n}\n\nenum ResolveMetadataSpan {\n generateMetadata = 'ResolveMetadata.generateMetadata',\n generateViewport = 'ResolveMetadata.generateViewport',\n}\n\nenum MiddlewareSpan {\n execute = 'Middleware.execute',\n}\n\ntype SpanTypes =\n | `${BaseServerSpan}`\n | `${LoadComponentsSpan}`\n | `${NextServerSpan}`\n | `${StartServerSpan}`\n | `${NextNodeServerSpan}`\n | `${RenderSpan}`\n | `${RouterSpan}`\n | `${AppRenderSpan}`\n | `${NodeSpan}`\n | `${AppRouteRouteHandlersSpan}`\n | `${ResolveMetadataSpan}`\n | `${MiddlewareSpan}`\n\n// This list is used to filter out spans that are not relevant to the user\nexport const NextVanillaSpanAllowlist = new Set([\n MiddlewareSpan.execute,\n BaseServerSpan.handleRequest,\n RenderSpan.getServerSideProps,\n RenderSpan.getStaticProps,\n AppRenderSpan.fetch,\n AppRenderSpan.getBodyResult,\n RenderSpan.renderDocument,\n NodeSpan.runHandler,\n AppRouteRouteHandlersSpan.runHandler,\n ResolveMetadataSpan.generateMetadata,\n ResolveMetadataSpan.generateViewport,\n NextNodeServerSpan.createComponentTree,\n NextNodeServerSpan.findPageComponents,\n NextNodeServerSpan.getLayoutOrPageModule,\n NextNodeServerSpan.startResponse,\n NextNodeServerSpan.clientComponentLoading,\n])\n\n// These Spans are allowed to be always logged\n// when the otel log prefix env is set\nexport const LogSpanAllowList = new Set([\n NextNodeServerSpan.findPageComponents,\n NextNodeServerSpan.createComponentTree,\n NextNodeServerSpan.clientComponentLoading,\n])\n\nexport {\n BaseServerSpan,\n LoadComponentsSpan,\n NextServerSpan,\n NextNodeServerSpan,\n StartServerSpan,\n RenderSpan,\n RouterSpan,\n AppRenderSpan,\n NodeSpan,\n AppRouteRouteHandlersSpan,\n ResolveMetadataSpan,\n MiddlewareSpan,\n}\n\nexport type { SpanTypes }\n"],"names":["BaseServerSpan","LoadComponentsSpan","NextServerSpan","NextNodeServerSpan","StartServerSpan","RenderSpan","AppRenderSpan","RouterSpan","NodeSpan","AppRouteRouteHandlersSpan","ResolveMetadataSpan","MiddlewareSpan","NextVanillaSpanAllowlist","Set","LogSpanAllowList"],"mappings":"AAAA;;;;;EAKE,GAEF,4CAA4C;AAE5C,IAAA,AAAKA,wCAAAA;;;;;;;;;;;;;WAAAA;EAAAA;AAeL,IAAA,AAAKC,4CAAAA;;;WAAAA;EAAAA;AAKL,IAAA,AAAKC,wCAAAA;;;;;;WAAAA;EAAAA;AAQL,IAAA,AAAKC,4CAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;IA4BH,wDAAwD;;;;;WA5BrDA;EAAAA;AAmCL,IAAA,AAAKC,yCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKC,oCAAAA;;;;;;WAAAA;EAAAA;AAQL,IAAA,AAAKC,uCAAAA;;;;;;;;;;WAAAA;EAAAA;AAYL,IAAA,AAAKC,oCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKC,kCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKC,mDAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKC,6CAAAA;;;WAAAA;EAAAA;AAKL,IAAA,AAAKC,wCAAAA;;WAAAA;EAAAA;AAkBL,0EAA0E;AAC1E,OAAO,MAAMC,2BAA2B,IAAIC,IAAI;;;;;;;;;;;;;;;;;CAiB/C,EAAC;AAEF,8CAA8C;AAC9C,sCAAsC;AACtC,OAAO,MAAMC,mBAAmB,IAAID,IAAI;;;;CAIvC,EAAC;AAEF,SACEb,cAAc,EACdC,kBAAkB,EAClBC,cAAc,EACdC,kBAAkB,EAClBC,eAAe,EACfC,UAAU,EACVE,UAAU,EACVD,aAAa,EACbE,QAAQ,EACRC,yBAAyB,EACzBC,mBAAmB,EACnBC,cAAc,KACf","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/server/lib/trace/constants.ts"],"sourcesContent":["/**\n * Contains predefined constants for the trace span name in next/server.\n *\n * Currently, next/server/tracer is internal implementation only for tracking\n * next.js's implementation only with known span names defined here.\n **/\n\n// eslint typescript has a bug with TS enums\n\nenum BaseServerSpan {\n handleRequest = 'BaseServer.handleRequest',\n run = 'BaseServer.run',\n pipe = 'BaseServer.pipe',\n getStaticHTML = 'BaseServer.getStaticHTML',\n render = 'BaseServer.render',\n renderToResponseWithComponents = 'BaseServer.renderToResponseWithComponents',\n renderToResponse = 'BaseServer.renderToResponse',\n renderToHTML = 'BaseServer.renderToHTML',\n renderError = 'BaseServer.renderError',\n renderErrorToResponse = 'BaseServer.renderErrorToResponse',\n renderErrorToHTML = 'BaseServer.renderErrorToHTML',\n render404 = 'BaseServer.render404',\n}\n\nenum LoadComponentsSpan {\n loadDefaultErrorComponents = 'LoadComponents.loadDefaultErrorComponents',\n loadComponents = 'LoadComponents.loadComponents',\n}\n\nenum NextServerSpan {\n getRequestHandler = 'NextServer.getRequestHandler',\n getRequestHandlerWithMetadata = 'NextServer.getRequestHandlerWithMetadata',\n getServer = 'NextServer.getServer',\n getServerRequestHandler = 'NextServer.getServerRequestHandler',\n createServer = 'createServer.createServer',\n}\n\nenum NextNodeServerSpan {\n compression = 'NextNodeServer.compression',\n getBuildId = 'NextNodeServer.getBuildId',\n createComponentTree = 'NextNodeServer.createComponentTree',\n clientComponentLoading = 'NextNodeServer.clientComponentLoading',\n getLayoutOrPageModule = 'NextNodeServer.getLayoutOrPageModule',\n generateStaticRoutes = 'NextNodeServer.generateStaticRoutes',\n generateFsStaticRoutes = 'NextNodeServer.generateFsStaticRoutes',\n generatePublicRoutes = 'NextNodeServer.generatePublicRoutes',\n generateImageRoutes = 'NextNodeServer.generateImageRoutes.route',\n sendRenderResult = 'NextNodeServer.sendRenderResult',\n proxyRequest = 'NextNodeServer.proxyRequest',\n runApi = 'NextNodeServer.runApi',\n render = 'NextNodeServer.render',\n renderHTML = 'NextNodeServer.renderHTML',\n imageOptimizer = 'NextNodeServer.imageOptimizer',\n getPagePath = 'NextNodeServer.getPagePath',\n getRoutesManifest = 'NextNodeServer.getRoutesManifest',\n findPageComponents = 'NextNodeServer.findPageComponents',\n getFontManifest = 'NextNodeServer.getFontManifest',\n getServerComponentManifest = 'NextNodeServer.getServerComponentManifest',\n getRequestHandler = 'NextNodeServer.getRequestHandler',\n renderToHTML = 'NextNodeServer.renderToHTML',\n renderError = 'NextNodeServer.renderError',\n renderErrorToHTML = 'NextNodeServer.renderErrorToHTML',\n render404 = 'NextNodeServer.render404',\n startResponse = 'NextNodeServer.startResponse',\n\n // nested inner span, does not require parent scope name\n route = 'route',\n onProxyReq = 'onProxyReq',\n apiResolver = 'apiResolver',\n internalFetch = 'internalFetch',\n}\n\nenum StartServerSpan {\n startServer = 'startServer.startServer',\n}\n\nenum RenderSpan {\n getServerSideProps = 'Render.getServerSideProps',\n getStaticProps = 'Render.getStaticProps',\n renderToString = 'Render.renderToString',\n renderDocument = 'Render.renderDocument',\n createBodyResult = 'Render.createBodyResult',\n}\n\nenum AppRenderSpan {\n renderToString = 'AppRender.renderToString',\n renderToReadableStream = 'AppRender.renderToReadableStream',\n getBodyResult = 'AppRender.getBodyResult',\n fetch = 'AppRender.fetch',\n waitShellReady = 'AppRender.waitShellReady',\n renderToNodeFizzStream = 'AppRender.renderToNodeFizzStream',\n instantInsights = 'AppRender.instantInsights',\n instantInsightsPrepareValidation = 'AppRender.instantInsights.prepareValidation',\n instantInsightsRunValidation = 'AppRender.instantInsights.runValidation',\n}\n\nenum DevRouteMatcherManagerSpan {\n ensureRoute = 'DevRouteMatcherManager.ensureRoute',\n reloadMatchers = 'DevRouteMatcherManager.reloadMatchers',\n}\n\nenum DevBundlerServiceSpan {\n ensurePage = 'DevBundlerService.ensurePage',\n}\n\nenum RouterSpan {\n executeRoute = 'Router.executeRoute',\n}\n\nenum NodeSpan {\n runHandler = 'Node.runHandler',\n}\n\nenum AppRouteRouteHandlersSpan {\n runHandler = 'AppRouteRouteHandlers.runHandler',\n}\n\nenum ResolveMetadataSpan {\n generateMetadata = 'ResolveMetadata.generateMetadata',\n generateViewport = 'ResolveMetadata.generateViewport',\n}\n\nenum MiddlewareSpan {\n execute = 'Middleware.execute',\n}\n\ntype SpanTypes =\n | `${BaseServerSpan}`\n | `${LoadComponentsSpan}`\n | `${NextServerSpan}`\n | `${StartServerSpan}`\n | `${NextNodeServerSpan}`\n | `${RenderSpan}`\n | `${RouterSpan}`\n | `${AppRenderSpan}`\n | `${DevRouteMatcherManagerSpan}`\n | `${DevBundlerServiceSpan}`\n | `${NodeSpan}`\n | `${AppRouteRouteHandlersSpan}`\n | `${ResolveMetadataSpan}`\n | `${MiddlewareSpan}`\n\n// This list is used to filter out spans that are not relevant to the user\nexport const NextVanillaSpanAllowlist = new Set([\n MiddlewareSpan.execute,\n BaseServerSpan.handleRequest,\n RenderSpan.getServerSideProps,\n RenderSpan.getStaticProps,\n AppRenderSpan.fetch,\n AppRenderSpan.getBodyResult,\n RenderSpan.renderDocument,\n NodeSpan.runHandler,\n AppRouteRouteHandlersSpan.runHandler,\n ResolveMetadataSpan.generateMetadata,\n ResolveMetadataSpan.generateViewport,\n NextNodeServerSpan.createComponentTree,\n NextNodeServerSpan.findPageComponents,\n NextNodeServerSpan.getLayoutOrPageModule,\n NextNodeServerSpan.startResponse,\n NextNodeServerSpan.clientComponentLoading,\n])\n\n// These Spans are allowed to be always logged\n// when the otel log prefix env is set\nexport const LogSpanAllowList = new Set([\n NextNodeServerSpan.findPageComponents,\n NextNodeServerSpan.createComponentTree,\n NextNodeServerSpan.clientComponentLoading,\n])\n\nexport {\n BaseServerSpan,\n LoadComponentsSpan,\n NextServerSpan,\n NextNodeServerSpan,\n StartServerSpan,\n RenderSpan,\n RouterSpan,\n AppRenderSpan,\n DevRouteMatcherManagerSpan,\n DevBundlerServiceSpan,\n NodeSpan,\n AppRouteRouteHandlersSpan,\n ResolveMetadataSpan,\n MiddlewareSpan,\n}\n\nexport type { SpanTypes }\n"],"names":["BaseServerSpan","LoadComponentsSpan","NextServerSpan","NextNodeServerSpan","StartServerSpan","RenderSpan","AppRenderSpan","DevRouteMatcherManagerSpan","DevBundlerServiceSpan","RouterSpan","NodeSpan","AppRouteRouteHandlersSpan","ResolveMetadataSpan","MiddlewareSpan","NextVanillaSpanAllowlist","Set","LogSpanAllowList"],"mappings":"AAAA;;;;;EAKE,GAEF,4CAA4C;AAE5C,IAAA,AAAKA,wCAAAA;;;;;;;;;;;;;WAAAA;EAAAA;AAeL,IAAA,AAAKC,4CAAAA;;;WAAAA;EAAAA;AAKL,IAAA,AAAKC,wCAAAA;;;;;;WAAAA;EAAAA;AAQL,IAAA,AAAKC,4CAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;IA4BH,wDAAwD;;;;;WA5BrDA;EAAAA;AAmCL,IAAA,AAAKC,yCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKC,oCAAAA;;;;;;WAAAA;EAAAA;AAQL,IAAA,AAAKC,uCAAAA;;;;;;;;;;WAAAA;EAAAA;AAYL,IAAA,AAAKC,oDAAAA;;;WAAAA;EAAAA;AAKL,IAAA,AAAKC,+CAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKC,oCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKC,kCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKC,mDAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKC,6CAAAA;;;WAAAA;EAAAA;AAKL,IAAA,AAAKC,wCAAAA;;WAAAA;EAAAA;AAoBL,0EAA0E;AAC1E,OAAO,MAAMC,2BAA2B,IAAIC,IAAI;;;;;;;;;;;;;;;;;CAiB/C,EAAC;AAEF,8CAA8C;AAC9C,sCAAsC;AACtC,OAAO,MAAMC,mBAAmB,IAAID,IAAI;;;;CAIvC,EAAC;AAEF,SACEf,cAAc,EACdC,kBAAkB,EAClBC,cAAc,EACdC,kBAAkB,EAClBC,eAAe,EACfC,UAAU,EACVI,UAAU,EACVH,aAAa,EACbC,0BAA0B,EAC1BC,qBAAqB,EACrBE,QAAQ,EACRC,yBAAyB,EACzBC,mBAAmB,EACnBC,cAAc,KACf","ignoreList":[0]} |
@@ -8,3 +8,3 @@ import { workAsyncStorage } from '../app-render/work-async-storage.external'; | ||
| import { describeStringPropertyAccess, wellKnownProperties } from '../../shared/lib/utils/reflect-utils'; | ||
| import { makeDevtoolsIOAwarePromise, makeFallbackParamsHangingPromise, makePromiseFromTrigger, trackFallbackParamsAccessed, RENDER_STAGES_BY_DATA_KIND } from '../dynamic-rendering-utils'; | ||
| import { makeDevtoolsIOAwarePromise, makeFallbackParamsHangingPromise, makePromiseFromTrigger, trackFallbackParamsAccessed, RENDER_STAGES_BY_DATA_KIND, trackPromiseUsed, trackIncompatibleShellContent } from '../dynamic-rendering-utils'; | ||
| import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'; | ||
@@ -409,5 +409,11 @@ import { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'; | ||
| // However, in dev we might need to recover a session shell for instant validation. | ||
| // This is indicated by `needsSessionShell`. | ||
| const staticParamsStage = workUnitStore.needsSessionShell ? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData : RENDER_STAGES_BY_DATA_KIND.staticLinkData; | ||
| return stagedRendering.delayUntilStage(staticParamsStage, 'params', userspaceParams); | ||
| // This is indicated by `needsAppShell`. | ||
| const staticParamsStage = workUnitStore.needsAppShell ? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData : RENDER_STAGES_BY_DATA_KIND.staticLinkData; | ||
| const promise = stagedRendering.delayUntilStage(staticParamsStage, 'params', userspaceParams); | ||
| if (process.env.__NEXT_DEV_SERVER) { | ||
| // If static params are accessed, we can recover a static shell or a session shell, but not both. | ||
| return trackPromiseUsed(promise, trackIncompatibleShellContent.bind(null, workUnitStore)); | ||
| } else { | ||
| return promise; | ||
| } | ||
| } | ||
@@ -414,0 +420,0 @@ return makeUntrackedParams(userspaceParams); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/request/params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { OpaqueFallbackRouteParams } from './fallback-params'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n throwToInterruptStaticGeneration,\n postponeWithTracking,\n} from '../app-render/dynamic-rendering'\n\nimport {\n workUnitAsyncStorage,\n type PrerenderStorePPR,\n type PrerenderStoreLegacy,\n type StaticPrerenderStoreModern,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type PrerenderStoreModernRuntime,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n describeStringPropertyAccess,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n makeDevtoolsIOAwarePromise,\n makeFallbackParamsHangingPromise,\n makePromiseFromTrigger,\n trackFallbackParamsAccessed,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\nimport {\n isEmptyParams,\n hasFallbackRouteParams,\n allParamsAreRootParams,\n} from '../lib/params-utils'\n\nexport type ParamValue = string | Array<string> | undefined\nexport type Params = Record<string, ParamValue>\n\nexport function createParamsFromClient(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n // Client params don't need additional vary tracking because by the\n // time they reach the client, the access would have already been\n // tracked by the server.\n const varyParamsAccumulator = null\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createParamsFromClient should not be called in cache contexts.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createParamsFromClient should not be called in a runtime prerender.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n return makeUntrackedParams(underlyingParams)\n }\n case 'request': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport type CreateServerParamsForMetadata = typeof createServerParamsForMetadata\nexport function createServerParamsForMetadata(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null\n): Promise<Params> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerParamsForServerSegment(\n underlyingParams,\n optionalCatchAllParamName,\n metadataVaryParamsAccumulator\n )\n}\n\n// routes always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerParamsForRoute(\n underlyingParams: Params,\n varyParamsAccumulator: VaryParamsAccumulator | null = null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in runtime prerenders.'\n )\n }\n case 'request':\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createServerParamsForServerSegment(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request': {\n return createRenderParamsForPage(\n workStore,\n workUnitStore,\n underlyingParams,\n optionalCatchAllParamName,\n varyParamsAccumulator\n )\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderParamsForClientSegment(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(\n 'Missing workStore in createPrerenderParamsForClientSegment'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n const fallbackParams = workUnitStore.fallbackRouteParams\n if (fallbackParams) {\n for (let key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeFallbackParamsHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`params`',\n workUnitStore\n )\n }\n }\n }\n break\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in validation contexts.'\n )\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n // We're prerendering in a mode that does not abort. We resolve the promise without\n // any tracking because we're just transporting a value from server to client where the tracking\n // will be applied.\n return Promise.resolve(underlyingParams)\n}\n\nfunction createStaticPrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n switch (prerenderStore.type) {\n case 'prerender': {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (hasFallbackRouteParams(underlyingParams, fallbackParams)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object dynamic.\n return makeHangingParams(underlyingParams, workStore, prerenderStore)\n }\n\n // All params are static.\n\n const { stagedRendering } = prerenderStore\n if (stagedRendering) {\n // Even if all params are static, we need to exclude them from the app shell\n // by delaying them to the static stage. However, root params are allowed in shells,\n // so if all the params are root params, they can be included as well.\n if (\n !allParamsAreRootParams(underlyingParams, prerenderStore.rootParams)\n ) {\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.staticLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n }\n }\n\n return makeUntrackedParams(userspaceParams)\n }\n case 'prerender-client': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeHangingParams(\n underlyingParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-ppr': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n return makeErroringParams(\n underlyingParams,\n fallbackParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRuntimePrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no staging, we're in a prospective runtime prerender.\n if (workUnitStore.isSessionShell) {\n // If we're warming up for a session shell, params should be hanging,\n // because they'll be a hanging input in the final prerender.\n return makeHangingParams(underlyingParams, workStore, workUnitStore)\n } else {\n return makeUntrackedParams(userspaceParams)\n }\n }\n\n // We don't have fallbackParams in runtime prerenders, so we don't know\n // when params are static. However, root params are static by definition,\n // so we can at least check for that.\n // Note that resolving them without a delay is valid because root params are\n // allowed in shells.\n if (allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // Semantically, we should resolve static params in the static stage.\n // But params are link data, and we need to recover a param-less session shell,\n // so we delay all params until the runtime stage instead.\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n}\n\nfunction createRenderParamsForPage(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n) {\n const { stagedRendering, asyncApiPromises, validationSamples } = workUnitStore\n\n // Distinguish the params that we expose to userspace (potentially wrapped in proxies)\n // and the underlying object containing params values. We do this because wrappers\n // like `instrumentParamsPromiseWithDevWarnings` need to be able to get the known param names\n // without triggering other wrapper proxies.\n let userspaceParams = underlyingParams\n if (validationSamples) {\n userspaceParams = createServerParamsProxyForInstantValidation(\n underlyingParams,\n workStore,\n validationSamples\n )\n }\n if (varyParamsAccumulator) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n userspaceParams,\n optionalCatchAllParamName\n )\n }\n\n if (stagedRendering && asyncApiPromises) {\n return createStagedRenderParams(\n workStore,\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(userspaceParams)\n }\n}\n\nfunction createStagedRenderParams(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n underlyingParams: Params,\n userspaceParams: Params\n) {\n const promise = createStagedRenderParamsImpl(\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n if (process.env.NODE_ENV === 'development') {\n return instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n } else {\n return promise\n }\n}\n\nfunction createStagedRenderParamsImpl(\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n /** The actual param values, without any instrumentation */\n underlyingParams: Params,\n /** The params object to return to userspace, possibly wrapped in a proxy */\n userspaceParams: Params\n) {\n // If the route has no params, they should resolve immediately.\n if (isEmptyParams(underlyingParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // If we have fallback params, then they should always resolve in the runtime link data stage.\n // We do this indirectly via the shared params parent for better debug info.\n if (hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)) {\n return createParamsPromiseFromTrigger(\n asyncApiPromises.sharedParamsParent,\n userspaceParams\n )\n }\n\n // All params are static.\n\n // If we're rendering with shells, even static params must be delayed to exclude them from the shell.\n // However, root params are allowed in shells, so if all the params are root params, they can be included as well.\n if (!allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n // For a dynamic request we generally want to recover a static shell,\n // so static params can resolve in the static stage, because session\n // shells are handled with a separate render.\n // However, in dev we might need to recover a session shell for instant validation.\n // This is indicated by `needsSessionShell`.\n const staticParamsStage = workUnitStore.needsSessionShell\n ? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n : RENDER_STAGES_BY_DATA_KIND.staticLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n }\n\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createParamsPromiseFromTrigger(\n trigger: Promise<any>,\n userspaceParams: Params\n) {\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of params in a `new Promise()`, which lets us show each\n // await a different set of values. This is important when all awaits\n // are in third party which would otherwise track all the way to the\n // internal params.\n const promise: Promise<Params> = new Promise((resolve, reject) => {\n trigger.then(() => resolve(userspaceParams), reject)\n })\n promise.catch(noop)\n // @ts-expect-error\n promise.displayName = 'params'\n return promise\n } else {\n return makePromiseFromTrigger(trigger, userspaceParams)\n }\n}\n\nfunction noop() {}\n\nfunction createServerParamsProxyForInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>\n): Params {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples.params ?? {}))\n return createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n}\n\nfunction createClientParamsInInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: ValidationStoreClient['validationSamples']\n): Promise<Params> {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples?.params ?? {}))\n const proxiedUnderlying = createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n return Promise.resolve(proxiedUnderlying)\n}\n\nfunction createRenderParamsInProd(userspaceParams: Params): Promise<Params> {\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRenderParamsInDev(\n underlyingParams: Params,\n userpaceParams: Params,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n return makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams,\n userpaceParams,\n hasFallbackRouteParams(underlyingParams, fallbackParams),\n workStore,\n requestStore\n )\n}\n\ninterface CacheLifetime {}\nconst CachedParams = new WeakMap<CacheLifetime, Promise<Params>>()\n\nconst fallbackParamsProxyHandler: ProxyHandler<Promise<Params>> = {\n get: function get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n\n return {\n [prop]: (...args: unknown[]) => {\n // Record against the store that's active at access time: the\n // hanging promise is cached by params object across prerender\n // stores, so the store that created it may not be the one that's\n // rendering when it's finally awaited.\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore !== undefined) {\n trackFallbackParamsAccessed(workUnitStore)\n }\n\n const store = dynamicAccessAsyncStorage.getStore()\n\n if (store) {\n store.abortController.abort(\n new Error(`Accessed fallback \\`params\\` during prerendering.`)\n )\n }\n\n return new Proxy(\n originalMethod.apply(target, args),\n fallbackParamsProxyHandler\n )\n },\n }[prop]\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n}\n\nfunction makeHangingParams(\n underlyingParams: Params,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = new Proxy(\n makeFallbackParamsHangingPromise<Params>(\n prerenderStore.renderSignal,\n workStore.route,\n '`params`',\n // This promise is created for every segment on a fallback route whether\n // or not it reads params, so recording the access at creation would mark\n // every render. The access is tracked in the proxy traps instead.\n null\n ),\n fallbackParamsProxyHandler\n )\n\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeErroringParams(\n underlyingParams: Params,\n fallbackParams: OpaqueFallbackRouteParams,\n workStore: WorkStore,\n prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const augmentedUnderlying = { ...underlyingParams }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = Promise.resolve(augmentedUnderlying)\n CachedParams.set(underlyingParams, promise)\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n if (fallbackParams.has(prop)) {\n Object.defineProperty(augmentedUnderlying, prop, {\n get() {\n const expression = describeStringPropertyAccess('params', prop)\n // In most dynamic APIs we also throw if `dynamic = \"error\"` however\n // for params is only dynamic when we're generating a fallback shell\n // and even when `dynamic = \"error\"` we still support generating dynamic\n // fallback shells\n // TODO remove this comment when cacheComponents is the default since there\n // will be no `dynamic = \"error\"`\n if (prerenderStore.type === 'prerender-ppr') {\n // PPR Prerender (no cacheComponents)\n postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n },\n enumerable: true,\n })\n }\n }\n })\n\n return promise\n}\n\nfunction makeUntrackedParams(underlyingParams: Params): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = Promise.resolve(underlyingParams)\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams: Params,\n userspaceParams: Params,\n hasFallbackParams: boolean,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = hasFallbackParams\n ? makeDevtoolsIOAwarePromise(\n userspaceParams,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n )\n : // We don't want to force an environment transition when this params is not part of the fallback params set\n Promise.resolve(userspaceParams)\n\n const proxiedPromise = instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n CachedParams.set(underlyingParams, proxiedPromise)\n return proxiedPromise\n}\n\nfunction instrumentParamsPromiseWithDevWarnings(\n underlyingParams: Params,\n promise: Promise<Params>,\n workStore: WorkStore\n): Promise<Params> {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (typeof prop === 'string') {\n if (\n // We are accessing a property that was proxied to the promise instance\n proxiedProperties.has(prop)\n ) {\n const expression = describeStringPropertyAccess('params', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return ReflectAdapter.set(target, prop, value, receiver)\n },\n ownKeys(target) {\n const expression = '`...params` or similar expression'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createParamsAccessError\n)\n\nfunction createParamsAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`params\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["workAsyncStorage","createVaryingParams","getMetadataVaryParamsAccumulator","ReflectAdapter","throwToInterruptStaticGeneration","postponeWithTracking","workUnitAsyncStorage","throwInvariantForMissingStore","InvariantError","describeStringPropertyAccess","wellKnownProperties","makeDevtoolsIOAwarePromise","makeFallbackParamsHangingPromise","makePromiseFromTrigger","trackFallbackParamsAccessed","RENDER_STAGES_BY_DATA_KIND","createDedupedByCallsiteServerErrorLoggerDev","dynamicAccessAsyncStorage","isEmptyParams","hasFallbackRouteParams","allParamsAreRootParams","createParamsFromClient","underlyingParams","workStore","getStore","workUnitStore","type","varyParamsAccumulator","createStaticPrerenderParams","validationSamples","createClientParamsInInstantValidation","makeUntrackedParams","process","env","NODE_ENV","fallbackParams","userspaceParams","createRenderParamsInDev","createRenderParamsInProd","createServerParamsForMetadata","optionalCatchAllParamName","metadataVaryParamsAccumulator","createServerParamsForServerSegment","createServerParamsForRoute","createRuntimePrerenderParams","createRenderParamsForPage","createPrerenderParamsForClientSegment","fallbackRouteParams","key","has","renderSignal","route","Promise","resolve","prerenderStore","makeHangingParams","stagedRendering","rootParams","staticParamsStage","staticLinkData","delayUntilStage","makeErroringParams","isSessionShell","runtimeLinkData","asyncApiPromises","createServerParamsProxyForInstantValidation","createStagedRenderParams","promise","createStagedRenderParamsImpl","instrumentParamsPromiseWithDevWarnings","createParamsPromiseFromTrigger","sharedParamsParent","needsSessionShell","trigger","reject","then","catch","noop","displayName","createExhaustiveParamsProxy","require","declaredParams","Set","Object","keys","params","proxiedUnderlying","userpaceParams","requestStore","makeDynamicallyTrackedParamsWithDevWarnings","CachedParams","WeakMap","fallbackParamsProxyHandler","get","target","prop","receiver","originalMethod","args","undefined","store","abortController","abort","Error","Proxy","apply","cachedParams","set","augmentedUnderlying","forEach","defineProperty","expression","dynamicTracking","enumerable","hasFallbackParams","proxiedPromise","proxiedProperties","add","warnForSyncAccess","value","delete","ownKeys","Reflect","createParamsAccessError","prefix"],"mappings":"AAAA,SACEA,gBAAgB,QAEX,4CAA2C;AAGlD,SACEC,mBAAmB,EACnBC,gCAAgC,QAC3B,4BAA2B;AAElC,SAASC,cAAc,QAAQ,yCAAwC;AACvE,SACEC,gCAAgC,EAChCC,oBAAoB,QACf,kCAAiC;AAExC,SACEC,oBAAoB,E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SAAQ3B,MAAM;YACZ,MAAMiB,aAAa;YACnBO,kBAAkB/F,UAAU4B,KAAK,EAAE4D;YACnC,OAAOW,QAAQD,OAAO,CAAC3B;QACzB;IACF;AACF;AAEA,MAAMwB,oBAAoBtG,4CACxB2G;AAGF,SAASA,wBACPxE,KAAyB,EACzB4D,UAAkB;IAElB,MAAMa,SAASzE,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAIoD,MACT,GAAGqB,OAAO,KAAK,EAAEb,WAAW,EAAE,CAAC,GAC7B,CAAC,iHAAiH,CAAC,GACnH,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/request/params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { OpaqueFallbackRouteParams } from './fallback-params'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n throwToInterruptStaticGeneration,\n postponeWithTracking,\n} from '../app-render/dynamic-rendering'\n\nimport {\n workUnitAsyncStorage,\n type PrerenderStorePPR,\n type PrerenderStoreLegacy,\n type StaticPrerenderStoreModern,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type PrerenderStoreModernRuntime,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n describeStringPropertyAccess,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n makeDevtoolsIOAwarePromise,\n makeFallbackParamsHangingPromise,\n makePromiseFromTrigger,\n trackFallbackParamsAccessed,\n RENDER_STAGES_BY_DATA_KIND,\n trackPromiseUsed,\n trackIncompatibleShellContent,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\nimport {\n isEmptyParams,\n hasFallbackRouteParams,\n allParamsAreRootParams,\n} from '../lib/params-utils'\n\nexport type ParamValue = string | Array<string> | undefined\nexport type Params = Record<string, ParamValue>\n\nexport function createParamsFromClient(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n // Client params don't need additional vary tracking because by the\n // time they reach the client, the access would have already been\n // tracked by the server.\n const varyParamsAccumulator = null\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createParamsFromClient should not be called in cache contexts.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createParamsFromClient should not be called in a runtime prerender.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n return makeUntrackedParams(underlyingParams)\n }\n case 'request': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport type CreateServerParamsForMetadata = typeof createServerParamsForMetadata\nexport function createServerParamsForMetadata(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null\n): Promise<Params> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerParamsForServerSegment(\n underlyingParams,\n optionalCatchAllParamName,\n metadataVaryParamsAccumulator\n )\n}\n\n// routes always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerParamsForRoute(\n underlyingParams: Params,\n varyParamsAccumulator: VaryParamsAccumulator | null = null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in runtime prerenders.'\n )\n }\n case 'request':\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createServerParamsForServerSegment(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request': {\n return createRenderParamsForPage(\n workStore,\n workUnitStore,\n underlyingParams,\n optionalCatchAllParamName,\n varyParamsAccumulator\n )\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderParamsForClientSegment(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(\n 'Missing workStore in createPrerenderParamsForClientSegment'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n const fallbackParams = workUnitStore.fallbackRouteParams\n if (fallbackParams) {\n for (let key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeFallbackParamsHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`params`',\n workUnitStore\n )\n }\n }\n }\n break\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in validation contexts.'\n )\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n // We're prerendering in a mode that does not abort. We resolve the promise without\n // any tracking because we're just transporting a value from server to client where the tracking\n // will be applied.\n return Promise.resolve(underlyingParams)\n}\n\nfunction createStaticPrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n switch (prerenderStore.type) {\n case 'prerender': {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (hasFallbackRouteParams(underlyingParams, fallbackParams)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object dynamic.\n return makeHangingParams(underlyingParams, workStore, prerenderStore)\n }\n\n // All params are static.\n\n const { stagedRendering } = prerenderStore\n if (stagedRendering) {\n // Even if all params are static, we need to exclude them from the app shell\n // by delaying them to the static stage. However, root params are allowed in shells,\n // so if all the params are root params, they can be included as well.\n if (\n !allParamsAreRootParams(underlyingParams, prerenderStore.rootParams)\n ) {\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.staticLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n }\n }\n\n return makeUntrackedParams(userspaceParams)\n }\n case 'prerender-client': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeHangingParams(\n underlyingParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-ppr': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n return makeErroringParams(\n underlyingParams,\n fallbackParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRuntimePrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no staging, we're in a prospective runtime prerender.\n if (workUnitStore.isSessionShell) {\n // If we're warming up for a session shell, params should be hanging,\n // because they'll be a hanging input in the final prerender.\n return makeHangingParams(underlyingParams, workStore, workUnitStore)\n } else {\n return makeUntrackedParams(userspaceParams)\n }\n }\n\n // We don't have fallbackParams in runtime prerenders, so we don't know\n // when params are static. However, root params are static by definition,\n // so we can at least check for that.\n // Note that resolving them without a delay is valid because root params are\n // allowed in shells.\n if (allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // Semantically, we should resolve static params in the static stage.\n // But params are link data, and we need to recover a param-less session shell,\n // so we delay all params until the runtime stage instead.\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n}\n\nfunction createRenderParamsForPage(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n) {\n const { stagedRendering, asyncApiPromises, validationSamples } = workUnitStore\n\n // Distinguish the params that we expose to userspace (potentially wrapped in proxies)\n // and the underlying object containing params values. We do this because wrappers\n // like `instrumentParamsPromiseWithDevWarnings` need to be able to get the known param names\n // without triggering other wrapper proxies.\n let userspaceParams = underlyingParams\n if (validationSamples) {\n userspaceParams = createServerParamsProxyForInstantValidation(\n underlyingParams,\n workStore,\n validationSamples\n )\n }\n if (varyParamsAccumulator) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n userspaceParams,\n optionalCatchAllParamName\n )\n }\n\n if (stagedRendering && asyncApiPromises) {\n return createStagedRenderParams(\n workStore,\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(userspaceParams)\n }\n}\n\nfunction createStagedRenderParams(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n underlyingParams: Params,\n userspaceParams: Params\n) {\n const promise = createStagedRenderParamsImpl(\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n if (process.env.NODE_ENV === 'development') {\n return instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n } else {\n return promise\n }\n}\n\nfunction createStagedRenderParamsImpl(\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n /** The actual param values, without any instrumentation */\n underlyingParams: Params,\n /** The params object to return to userspace, possibly wrapped in a proxy */\n userspaceParams: Params\n) {\n // If the route has no params, they should resolve immediately.\n if (isEmptyParams(underlyingParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // If we have fallback params, then they should always resolve in the runtime link data stage.\n // We do this indirectly via the shared params parent for better debug info.\n if (hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)) {\n return createParamsPromiseFromTrigger(\n asyncApiPromises.sharedParamsParent,\n userspaceParams\n )\n }\n\n // All params are static.\n\n // If we're rendering with shells, even static params must be delayed to exclude them from the shell.\n // However, root params are allowed in shells, so if all the params are root params, they can be included as well.\n if (!allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n // For a dynamic request we generally want to recover a static shell,\n // so static params can resolve in the static stage, because session\n // shells are handled with a separate render.\n // However, in dev we might need to recover a session shell for instant validation.\n // This is indicated by `needsAppShell`.\n const staticParamsStage = workUnitStore.needsAppShell\n ? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n : RENDER_STAGES_BY_DATA_KIND.staticLinkData\n\n const promise = stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n if (process.env.__NEXT_DEV_SERVER) {\n // If static params are accessed, we can recover a static shell or a session shell, but not both.\n return trackPromiseUsed(\n promise,\n trackIncompatibleShellContent.bind(null, workUnitStore)\n )\n } else {\n return promise\n }\n }\n\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createParamsPromiseFromTrigger(\n trigger: Promise<any>,\n userspaceParams: Params\n) {\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of params in a `new Promise()`, which lets us show each\n // await a different set of values. This is important when all awaits\n // are in third party which would otherwise track all the way to the\n // internal params.\n const promise: Promise<Params> = new Promise((resolve, reject) => {\n trigger.then(() => resolve(userspaceParams), reject)\n })\n promise.catch(noop)\n // @ts-expect-error\n promise.displayName = 'params'\n return promise\n } else {\n return makePromiseFromTrigger(trigger, userspaceParams)\n }\n}\n\nfunction noop() {}\n\nfunction createServerParamsProxyForInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>\n): Params {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples.params ?? {}))\n return createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n}\n\nfunction createClientParamsInInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: ValidationStoreClient['validationSamples']\n): Promise<Params> {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples?.params ?? {}))\n const proxiedUnderlying = createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n return Promise.resolve(proxiedUnderlying)\n}\n\nfunction createRenderParamsInProd(userspaceParams: Params): Promise<Params> {\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRenderParamsInDev(\n underlyingParams: Params,\n userpaceParams: Params,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n return makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams,\n userpaceParams,\n hasFallbackRouteParams(underlyingParams, fallbackParams),\n workStore,\n requestStore\n )\n}\n\ninterface CacheLifetime {}\nconst CachedParams = new WeakMap<CacheLifetime, Promise<Params>>()\n\nconst fallbackParamsProxyHandler: ProxyHandler<Promise<Params>> = {\n get: function get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n\n return {\n [prop]: (...args: unknown[]) => {\n // Record against the store that's active at access time: the\n // hanging promise is cached by params object across prerender\n // stores, so the store that created it may not be the one that's\n // rendering when it's finally awaited.\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore !== undefined) {\n trackFallbackParamsAccessed(workUnitStore)\n }\n\n const store = dynamicAccessAsyncStorage.getStore()\n\n if (store) {\n store.abortController.abort(\n new Error(`Accessed fallback \\`params\\` during prerendering.`)\n )\n }\n\n return new Proxy(\n originalMethod.apply(target, args),\n fallbackParamsProxyHandler\n )\n },\n }[prop]\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n}\n\nfunction makeHangingParams(\n underlyingParams: Params,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = new Proxy(\n makeFallbackParamsHangingPromise<Params>(\n prerenderStore.renderSignal,\n workStore.route,\n '`params`',\n // This promise is created for every segment on a fallback route whether\n // or not it reads params, so recording the access at creation would mark\n // every render. The access is tracked in the proxy traps instead.\n null\n ),\n fallbackParamsProxyHandler\n )\n\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeErroringParams(\n underlyingParams: Params,\n fallbackParams: OpaqueFallbackRouteParams,\n workStore: WorkStore,\n prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const augmentedUnderlying = { ...underlyingParams }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = Promise.resolve(augmentedUnderlying)\n CachedParams.set(underlyingParams, promise)\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n if (fallbackParams.has(prop)) {\n Object.defineProperty(augmentedUnderlying, prop, {\n get() {\n const expression = describeStringPropertyAccess('params', prop)\n // In most dynamic APIs we also throw if `dynamic = \"error\"` however\n // for params is only dynamic when we're generating a fallback shell\n // and even when `dynamic = \"error\"` we still support generating dynamic\n // fallback shells\n // TODO remove this comment when cacheComponents is the default since there\n // will be no `dynamic = \"error\"`\n if (prerenderStore.type === 'prerender-ppr') {\n // PPR Prerender (no cacheComponents)\n postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n },\n enumerable: true,\n })\n }\n }\n })\n\n return promise\n}\n\nfunction makeUntrackedParams(underlyingParams: Params): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = Promise.resolve(underlyingParams)\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams: Params,\n userspaceParams: Params,\n hasFallbackParams: boolean,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = hasFallbackParams\n ? makeDevtoolsIOAwarePromise(\n userspaceParams,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n )\n : // We don't want to force an environment transition when this params is not part of the fallback params set\n Promise.resolve(userspaceParams)\n\n const proxiedPromise = instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n CachedParams.set(underlyingParams, proxiedPromise)\n return proxiedPromise\n}\n\nfunction instrumentParamsPromiseWithDevWarnings(\n underlyingParams: Params,\n promise: Promise<Params>,\n workStore: WorkStore\n): Promise<Params> {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (typeof prop === 'string') {\n if (\n // We are accessing a property that was proxied to the promise instance\n proxiedProperties.has(prop)\n ) {\n const expression = describeStringPropertyAccess('params', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return ReflectAdapter.set(target, prop, value, receiver)\n },\n ownKeys(target) {\n const expression = '`...params` or similar expression'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createParamsAccessError\n)\n\nfunction createParamsAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`params\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["workAsyncStorage","createVaryingParams","getMetadataVaryParamsAccumulator","ReflectAdapter","throwToInterruptStaticGeneration","postponeWithTracking","workUnitAsyncStorage","throwInvariantForMissingStore","InvariantError","describeStringPropertyAccess","wellKnownProperties","makeDevtoolsIOAwarePromise","makeFallbackParamsHangingPromise","makePromiseFromTrigger","trackFallbackParamsAccessed","RENDER_STAGES_BY_DATA_KIND","trackPromiseUsed","trackIncompatibleShellContent","createDedupedByCallsiteServerErrorLoggerDev","dynamicAccessAsyncStorage","isEmptyParams","hasFallbackRouteParams","allParamsAreRootParams","createParamsFromClient","underlyingParams","workStore","getStore","workUnitStore","type","varyParamsAccumulator","createStaticPrerenderParams","validationSamples","createClientParamsInInstantValidation","makeUntrackedParams","process","env","NODE_ENV","fallbackParams","userspaceParams","createRenderParamsInDev","createRenderParamsInProd","createServerParamsForMetadata","optionalCatchAllParamName","metadataVaryParamsAccumulator","createServerParamsForServerSegment","createServerParamsForRoute","createRuntimePrerenderParams","createRenderParamsForPage","createPrerenderParamsForClientSegment","fallbackRouteParams","key","has","renderSignal","route","Promise","resolve","prerenderStore","makeHangingParams","stagedRendering","rootParams","staticParamsStage","staticLinkData","delayUntilStage","makeErroringParams","isSessionShell","runtimeLinkData","asyncApiPromises","createServerParamsProxyForInstantValidation","createStagedRenderParams","promise","createStagedRenderParamsImpl","instrumentParamsPromiseWithDevWarnings","createParamsPromiseFromTrigger","sharedParamsParent","needsAppShell","__NEXT_DEV_SERVER","bind","trigger","reject","then","catch","noop","displayName","createExhaustiveParamsProxy","require","declaredParams","Set","Object","keys","params","proxiedUnderlying","userpaceParams","requestStore","makeDynamicallyTrackedParamsWithDevWarnings","CachedParams","WeakMap","fallbackParamsProxyHandler","get","target","prop","receiver","originalMethod","args","undefined","store","abortController","abort","Error","Proxy","apply","cachedParams","set","augmentedUnderlying","forEach","defineProperty","expression","dynamicTracking","enumerable","hasFallbackParams","proxiedPromise","proxiedProperties","add","warnForSyncAccess","value","delete","ownKeys","Reflect","createParamsAccessError","prefix"],"mappings":"AAAA,SACEA,gBAAgB,QAEX,4CAA2C;AAGlD,SACEC,mBAAmB,EACnBC,gCAAgC,QA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,kBAAkBjG,UAAU4B,KAAK,EAAE8D;gBACrC;YACF;YACA,OAAOhH,eAAe8F,GAAG,CAACC,QAAQC,MAAMC;QAC1C;QACAW,KAAIb,MAAM,EAAEC,IAAI,EAAEwB,KAAK,EAAEvB,QAAQ;YAC/B,IAAI,OAAOD,SAAS,UAAU;gBAC5BqB,kBAAkBI,MAAM,CAACzB;YAC3B;YACA,OAAOhG,eAAe4G,GAAG,CAACb,QAAQC,MAAMwB,OAAOvB;QACjD;QACAyB,SAAQ3B,MAAM;YACZ,MAAMiB,aAAa;YACnBO,kBAAkBjG,UAAU4B,KAAK,EAAE8D;YACnC,OAAOW,QAAQD,OAAO,CAAC3B;QACzB;IACF;AACF;AAEA,MAAMwB,oBAAoBxG,4CACxB6G;AAGF,SAASA,wBACP1E,KAAyB,EACzB8D,UAAkB;IAElB,MAAMa,SAAS3E,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAIsD,MACT,GAAGqB,OAAO,KAAK,EAAEb,WAAW,EAAE,CAAC,GAC7B,CAAC,iHAAiH,CAAC,GACnH,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]} |
@@ -6,2 +6,4 @@ import { RouteKind } from '../route-kind'; | ||
| import { cyan } from '../../lib/picocolors'; | ||
| import { DevRouteMatcherManagerSpan } from '../lib/trace/constants'; | ||
| import { getTracer } from '../lib/trace/tracer'; | ||
| export class DevRouteMatcherManager extends DefaultRouteMatcherManager { | ||
@@ -35,4 +37,8 @@ constructor(production, ensurer, dir){ | ||
| // should try to ensure it and recompile the production matcher. | ||
| await this.ensurer.ensure(developmentMatch, pathname); | ||
| await this.production.reload(); | ||
| await getTracer().trace(DevRouteMatcherManagerSpan.ensureRoute, { | ||
| spanName: 'prepare route' | ||
| }, ()=>this.ensurer.ensure(developmentMatch, pathname)); | ||
| await getTracer().trace(DevRouteMatcherManagerSpan.reloadMatchers, { | ||
| spanName: 'reload route matchers' | ||
| }, ()=>this.production.reload()); | ||
| // Iterate over the production matches again, this time we should be able | ||
@@ -39,0 +45,0 @@ // to match it against the production matcher unless there's an error. |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/route-matcher-managers/dev-route-matcher-manager.ts"],"sourcesContent":["import { RouteKind } from '../route-kind'\nimport type { RouteMatch } from '../route-matches/route-match'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport { DefaultRouteMatcherManager } from './default-route-matcher-manager'\nimport type { MatchOptions, RouteMatcherManager } from './route-matcher-manager'\nimport path from '../../shared/lib/isomorphic/path'\nimport * as Log from '../../build/output/log'\nimport { cyan } from '../../lib/picocolors'\nimport type { RouteMatcher } from '../route-matchers/route-matcher'\n\nexport interface RouteEnsurer {\n ensure(match: RouteMatch, pathname: string): Promise<void>\n}\n\nexport class DevRouteMatcherManager extends DefaultRouteMatcherManager {\n constructor(\n private readonly production: RouteMatcherManager,\n private readonly ensurer: RouteEnsurer,\n private readonly dir: string\n ) {\n super()\n }\n\n public async test(pathname: string, options: MatchOptions): Promise<boolean> {\n // Try to find a match within the developer routes.\n const match = await super.match(pathname, options)\n\n // Return if the match wasn't null. Unlike the implementation of `match`\n // which uses `matchAll` here, this does not call `ensure` on the match\n // found via the development matches.\n return match !== null\n }\n\n protected validate(\n pathname: string,\n matcher: RouteMatcher,\n options: MatchOptions\n ): RouteMatch | null {\n const match = super.validate(pathname, matcher, options)\n\n // If a match was found, check to see if there were any conflicting app or\n // pages files.\n // TODO: maybe expand this to _any_ duplicated routes instead?\n if (\n match &&\n matcher.duplicated &&\n matcher.duplicated.some(\n (duplicate) =>\n duplicate.definition.kind === RouteKind.APP_PAGE ||\n duplicate.definition.kind === RouteKind.APP_ROUTE\n ) &&\n matcher.duplicated.some(\n (duplicate) =>\n duplicate.definition.kind === RouteKind.PAGES ||\n duplicate.definition.kind === RouteKind.PAGES_API\n )\n ) {\n return null\n }\n\n return match\n }\n\n public async *matchAll(\n pathname: string,\n options: MatchOptions\n ): AsyncGenerator<RouteMatch<RouteDefinition<RouteKind>>, null, undefined> {\n // Iterate over the development matches to see if one of them match the\n // request path.\n for await (const developmentMatch of super.matchAll(pathname, options)) {\n // We're here, which means that we haven't seen this match yet, so we\n // should try to ensure it and recompile the production matcher.\n await this.ensurer.ensure(developmentMatch, pathname)\n await this.production.reload()\n\n // Iterate over the production matches again, this time we should be able\n // to match it against the production matcher unless there's an error.\n for await (const productionMatch of this.production.matchAll(\n pathname,\n options\n )) {\n yield productionMatch\n }\n }\n\n // We tried direct matching against the pathname and against all the dynamic\n // paths, so there was no match.\n return null\n }\n\n public async reload(): Promise<void> {\n // Compile the production routes again.\n await this.production.reload()\n\n // Compile the development routes.\n await super.reload()\n\n // Check for and warn of any duplicates.\n for (const [pathname, matchers] of Object.entries(\n this.matchers.duplicates\n )) {\n // We only want to warn about matchers resolving to the same path if their\n // identities are different.\n const identity = matchers[0].identity\n if (matchers.slice(1).some((matcher) => matcher.identity !== identity)) {\n continue\n }\n\n Log.warn(\n `Duplicate page detected. ${matchers\n .map((matcher) =>\n cyan(path.relative(this.dir, matcher.definition.filename))\n )\n .join(' and ')} resolve to ${cyan(pathname)}`\n )\n }\n }\n}\n"],"names":["RouteKind","DefaultRouteMatcherManager","path","Log","cyan","DevRouteMatcherManager","constructor","production","ensurer","dir","test","pathname","options","match","validate","matcher","duplicated","some","duplicate","definition","kind","APP_PAGE","APP_ROUTE","PAGES","PAGES_API","matchAll","developmentMatch","ensure","reload","productionMatch","matchers","Object","entries","duplicates","identity","slice","warn","map","relative","filename","join"],"mappings":"AAAA,SAASA,SAAS,QAAQ,gBAAe;AAGzC,SAASC,0BAA0B,QAAQ,kCAAiC;AAE5E,OAAOC,UAAU,mCAAkC;AACnD,YAAYC,SAAS,yBAAwB;AAC7C,SAASC,IAAI,QAAQ,uBAAsB;AAO3C,OAAO,MAAMC,+BAA+BJ;IAC1CK,YACE,AAAiBC,UAA+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ACF;QAEA,4EAA4E;QAC5E,gCAAgC;QAChC,OAAO;IACT;IAEA,MAAaD,SAAwB;QACnC,uCAAuC;QACvC,MAAM,IAAI,CAACrB,UAAU,CAACqB,MAAM;QAE5B,kCAAkC;QAClC,MAAM,KAAK,CAACA;QAEZ,wCAAwC;QACxC,KAAK,MAAM,CAACjB,UAAUmB,SAAS,IAAIC,OAAOC,OAAO,CAC/C,IAAI,CAACF,QAAQ,CAACG,UAAU,EACvB;YACD,0EAA0E;YAC1E,4BAA4B;YAC5B,MAAMC,WAAWJ,QAAQ,CAAC,EAAE,CAACI,QAAQ;YACrC,IAAIJ,SAASK,KAAK,CAAC,GAAGlB,IAAI,CAAC,CAACF,UAAYA,QAAQmB,QAAQ,KAAKA,WAAW;gBACtE;YACF;YAEA/B,IAAIiC,IAAI,CACN,CAAC,yBAAyB,EAAEN,SACzBO,GAAG,CAAC,CAACtB,UACJX,KAAKF,KAAKoC,QAAQ,CAAC,IAAI,CAAC7B,GAAG,EAAEM,QAAQI,UAAU,CAACoB,QAAQ,IAEzDC,IAAI,CAAC,SAAS,YAAY,EAAEpC,KAAKO,WAAW;QAEnD;IACF;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/route-matcher-managers/dev-route-matcher-manager.ts"],"sourcesContent":["import { RouteKind } from '../route-kind'\nimport type { RouteMatch } from '../route-matches/route-match'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport { DefaultRouteMatcherManager } from './default-route-matcher-manager'\nimport type { MatchOptions, RouteMatcherManager } from './route-matcher-manager'\nimport path from '../../shared/lib/isomorphic/path'\nimport * as Log from '../../build/output/log'\nimport { cyan } from '../../lib/picocolors'\nimport type { RouteMatcher } from '../route-matchers/route-matcher'\nimport { DevRouteMatcherManagerSpan } from '../lib/trace/constants'\nimport { getTracer } from '../lib/trace/tracer'\n\nexport interface RouteEnsurer {\n ensure(match: RouteMatch, pathname: string): Promise<void>\n}\n\nexport class DevRouteMatcherManager extends DefaultRouteMatcherManager {\n constructor(\n private readonly production: RouteMatcherManager,\n private readonly ensurer: RouteEnsurer,\n private readonly dir: string\n ) {\n super()\n }\n\n public async test(pathname: string, options: MatchOptions): Promise<boolean> {\n // Try to find a match within the developer routes.\n const match = await super.match(pathname, options)\n\n // Return if the match wasn't null. Unlike the implementation of `match`\n // which uses `matchAll` here, this does not call `ensure` on the match\n // found via the development matches.\n return match !== null\n }\n\n protected validate(\n pathname: string,\n matcher: RouteMatcher,\n options: MatchOptions\n ): RouteMatch | null {\n const match = super.validate(pathname, matcher, options)\n\n // If a match was found, check to see if there were any conflicting app or\n // pages files.\n // TODO: maybe expand this to _any_ duplicated routes instead?\n if (\n match &&\n matcher.duplicated &&\n matcher.duplicated.some(\n (duplicate) =>\n duplicate.definition.kind === RouteKind.APP_PAGE ||\n duplicate.definition.kind === RouteKind.APP_ROUTE\n ) &&\n matcher.duplicated.some(\n (duplicate) =>\n duplicate.definition.kind === RouteKind.PAGES ||\n duplicate.definition.kind === RouteKind.PAGES_API\n )\n ) {\n return null\n }\n\n return match\n }\n\n public async *matchAll(\n pathname: string,\n options: MatchOptions\n ): AsyncGenerator<RouteMatch<RouteDefinition<RouteKind>>, null, undefined> {\n // Iterate over the development matches to see if one of them match the\n // request path.\n for await (const developmentMatch of super.matchAll(pathname, options)) {\n // We're here, which means that we haven't seen this match yet, so we\n // should try to ensure it and recompile the production matcher.\n await getTracer().trace(\n DevRouteMatcherManagerSpan.ensureRoute,\n {\n spanName: 'prepare route',\n },\n () => this.ensurer.ensure(developmentMatch, pathname)\n )\n await getTracer().trace(\n DevRouteMatcherManagerSpan.reloadMatchers,\n {\n spanName: 'reload route matchers',\n },\n () => this.production.reload()\n )\n\n // Iterate over the production matches again, this time we should be able\n // to match it against the production matcher unless there's an error.\n for await (const productionMatch of this.production.matchAll(\n pathname,\n options\n )) {\n yield productionMatch\n }\n }\n\n // We tried direct matching against the pathname and against all the dynamic\n // paths, so there was no match.\n return null\n }\n\n public async reload(): Promise<void> {\n // Compile the production routes again.\n await this.production.reload()\n\n // Compile the development routes.\n await super.reload()\n\n // Check for and warn of any duplicates.\n for (const [pathname, matchers] of Object.entries(\n this.matchers.duplicates\n )) {\n // We only want to warn about matchers resolving to the same path if their\n // identities are different.\n const identity = matchers[0].identity\n if (matchers.slice(1).some((matcher) => matcher.identity !== identity)) {\n continue\n }\n\n Log.warn(\n `Duplicate page detected. ${matchers\n .map((matcher) =>\n cyan(path.relative(this.dir, matcher.definition.filename))\n )\n .join(' and ')} resolve to ${cyan(pathname)}`\n )\n }\n }\n}\n"],"names":["RouteKind","DefaultRouteMatcherManager","path","Log","cyan","DevRouteMatcherManagerSpan","getTracer","DevRouteMatcherManager","constructor","production","ensurer","dir","test","pathname","options","match","validate","matcher","duplicated","some","duplicate","definition","kind","APP_PAGE","APP_ROUTE","PAGES","PAGES_API","matchAll","developmentMatch","trace","ensureRoute","spanName","ensure","reloadMatchers","reload","productionMatch","matchers","Object","entries","duplicates","identity","slice","warn","map","relative","filename","join"],"mappings":"AAAA,SAASA,SAAS,QAAQ,gBAAe;AAGzC,SAASC,0BAA0B,QAAQ,kCAAiC;AAE5E,OAAOC,UAAU,mCAAkC;AACnD,YAAYC,SAAS,yBAAwB;AAC7C,SAASC,IAAI,QAAQ,uBAAsB;AAE3C,SAASC,0BAA0B,QAAQ,yBAAwB;AACnE,SAASC,SAAS,QAAQ,sBAAqB;AAM/C,OAAO,MAAMC,+BAA+BN;IAC1CO,YACE,AAAiBC,UAA+B,EAChD,AAAiBC,OAAqB,EACtC,AAAiBC,GAAW,CAC5B;QACA,KAAK,SAJYF,aAAAA,iBACAC,UAAAA,cACAC,MAAAA;IAGnB;IAEA,MAAaC,KAAKC,QAAgB,EAAEC,OAAqB,EAAoB;QAC3E,mDAAmD;QACnD,MAAMC,QAAQ,MAAM,KAAK,CAACA,MAAMF,UAAUC;QAE1C,wEAAwE;QACxE,uEAAuE;QACvE,qCAAqC;QACrC,OAAOC,UAAU;IACnB;IAEUC,SACRH,QAAg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K,CAACA;QAEZ,wCAAwC;QACxC,KAAK,MAAM,CAACrB,UAAUuB,SAAS,IAAIC,OAAOC,OAAO,CAC/C,IAAI,CAACF,QAAQ,CAACG,UAAU,EACvB;YACD,0EAA0E;YAC1E,4BAA4B;YAC5B,MAAMC,WAAWJ,QAAQ,CAAC,EAAE,CAACI,QAAQ;YACrC,IAAIJ,SAASK,KAAK,CAAC,GAAGtB,IAAI,CAAC,CAACF,UAAYA,QAAQuB,QAAQ,KAAKA,WAAW;gBACtE;YACF;YAEArC,IAAIuC,IAAI,CACN,CAAC,yBAAyB,EAAEN,SACzBO,GAAG,CAAC,CAAC1B,UACJb,KAAKF,KAAK0C,QAAQ,CAAC,IAAI,CAACjC,GAAG,EAAEM,QAAQI,UAAU,CAACwB,QAAQ,IAEzDC,IAAI,CAAC,SAAS,YAAY,EAAE1C,KAAKS,WAAW;QAEnD;IACF;AACF","ignoreList":[0]} |
@@ -10,3 +10,3 @@ import { abortAndThrowOnSynchronousRequestDataAccess, postponeWithTracking } from '../../app-render/dynamic-rendering'; | ||
| import { removeTrailingSlash } from '../../../shared/lib/router/utils/remove-trailing-slash'; | ||
| import { encodeCacheTag } from '../../lib/encode-cache-tag'; | ||
| import { encodeHeaderSafe } from '../../lib/encode-header-safe'; | ||
| import { validateAndNormalizeCacheLifeProfile } from '../../use-cache/cache-life-profile'; | ||
@@ -30,3 +30,3 @@ /** | ||
| return revalidate([ | ||
| encodeCacheTag(tag) | ||
| encodeHeaderSafe(tag) | ||
| ], `revalidateTag ${tag}`, profile); | ||
@@ -52,3 +52,3 @@ } | ||
| return revalidate([ | ||
| encodeCacheTag(tag) | ||
| encodeHeaderSafe(tag) | ||
| ], `updateTag ${tag}`, undefined); | ||
@@ -85,3 +85,3 @@ } | ||
| } | ||
| let normalizedPath = `${NEXT_CACHE_IMPLICIT_TAG_ID}${encodeCacheTag(removeTrailingSlash(originalPath))}`; | ||
| let normalizedPath = `${NEXT_CACHE_IMPLICIT_TAG_ID}${encodeHeaderSafe(removeTrailingSlash(originalPath))}`; | ||
| if (type) { | ||
@@ -88,0 +88,0 @@ normalizedPath += `${normalizedPath.endsWith('/') ? '' : '/'}${type}`; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/server/web/spec-extension/revalidate.ts"],"sourcesContent":["import {\n abortAndThrowOnSynchronousRequestDataAccess,\n postponeWithTracking,\n} from '../../app-render/dynamic-rendering'\nimport { isDynamicRoute } from '../../../shared/lib/router/utils'\nimport {\n NEXT_CACHE_IMPLICIT_TAG_ID,\n NEXT_CACHE_SOFT_TAG_MAX_LENGTH,\n} from '../../../lib/constants'\nimport { workAsyncStorage } from '../../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.external'\nimport { DynamicServerError } from '../../../client/components/hooks-server-context'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport {\n ActionDidRevalidateDynamicOnly,\n ActionDidRevalidateStaticAndDynamic as ActionDidRevalidate,\n} from '../../../shared/lib/action-revalidation-kind'\nimport { removeTrailingSlash } from '../../../shared/lib/router/utils/remove-trailing-slash'\nimport { encodeCacheTag } from '../../lib/encode-cache-tag'\nimport { validateAndNormalizeCacheLifeProfile } from '../../use-cache/cache-life-profile'\n\ntype CacheLifeConfig = {\n expire?: number\n}\n\n/**\n * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.\n *\n * The second argument specifies a [`cacheLife`](https://nextjs.org/docs/app/api-reference/functions/cacheLife#reference) profile\n * (e.g. `\"max\"`), or a `{ expire }` object. For immediate expiration in Server Actions, use\n * [`updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag) instead.\n *\n * Read more: [Next.js Docs: `revalidateTag`](https://nextjs.org/docs/app/api-reference/functions/revalidateTag)\n */\nexport function revalidateTag(tag: string, profile: string | CacheLifeConfig) {\n if (!profile) {\n console.warn(\n '\"revalidateTag\" without the second argument is now deprecated, add second argument of \"max\" or use \"updateTag\". See more info here: https://nextjs.org/docs/messages/revalidate-tag-single-arg'\n )\n } else if (typeof profile === 'object') {\n profile = validateAndNormalizeCacheLifeProfile(profile, { kind: 'inline' })\n }\n return revalidate([encodeCacheTag(tag)], `revalidateTag ${tag}`, profile)\n}\n\n/**\n * This function allows you to update [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.\n * This can only be called from within a Server Action to enable read-your-own-writes semantics.\n *\n * Read more: [Next.js Docs: `updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag)\n */\nexport function updateTag(tag: string) {\n const workStore = workAsyncStorage.getStore()\n\n // TODO: change this after investigating why phase: 'action' is\n // set for route handlers\n if (!workStore || workStore.page.endsWith('/route')) {\n throw new Error(\n 'updateTag can only be called from within a Server Action. ' +\n 'To invalidate cache tags in Route Handlers or other contexts, use revalidateTag instead. ' +\n 'See more info here: https://nextjs.org/docs/app/api-reference/functions/updateTag'\n )\n }\n // updateTag uses immediate expiration (no profile) without deprecation warning\n return revalidate([encodeCacheTag(tag)], `updateTag ${tag}`, undefined)\n}\n\n/**\n * This function allows you to refresh client cache from server actions.\n * It's useful as dynamic data can be cached on the client which won't\n * be refreshed by updateTag\n */\nexport function refresh() {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (\n !workStore ||\n workStore.page.endsWith('/route') ||\n workUnitStore?.phase !== 'action'\n ) {\n throw new Error(\n 'refresh can only be called from within a Server Action. ' +\n 'See more info here: https://nextjs.org/docs/app/api-reference/functions/refresh'\n )\n }\n\n if (workStore) {\n // The Server Action version of refresh() only revalidates the dynamic data\n // on the client. It doesn't affect cached data.\n workStore.pathWasRevalidated = ActionDidRevalidateDynamicOnly\n }\n}\n\n/**\n * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific path.\n *\n * Read more: [Next.js Docs: `revalidatePath`](https://nextjs.org/docs/app/api-reference/functions/revalidatePath)\n */\nexport function revalidatePath(originalPath: string, type?: 'layout' | 'page') {\n if (originalPath.length > NEXT_CACHE_SOFT_TAG_MAX_LENGTH) {\n console.warn(\n `Warning: revalidatePath received \"${originalPath}\" which exceeded max length of ${NEXT_CACHE_SOFT_TAG_MAX_LENGTH}. See more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`\n )\n return\n }\n\n let normalizedPath = `${NEXT_CACHE_IMPLICIT_TAG_ID}${encodeCacheTag(removeTrailingSlash(originalPath))}`\n\n if (type) {\n normalizedPath += `${normalizedPath.endsWith('/') ? '' : '/'}${type}`\n } else if (isDynamicRoute(originalPath)) {\n console.warn(\n `Warning: a dynamic page path \"${originalPath}\" was passed to \"revalidatePath\", but the \"type\" parameter is missing. This has no effect by default, see more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`\n )\n }\n\n const tags = [normalizedPath]\n if (normalizedPath === `${NEXT_CACHE_IMPLICIT_TAG_ID}/`) {\n tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)\n } else if (normalizedPath === `${NEXT_CACHE_IMPLICIT_TAG_ID}/index`) {\n tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)\n }\n\n return revalidate(tags, `revalidatePath ${originalPath}`)\n}\n\nfunction revalidate(\n tags: string[],\n expression: string,\n profile?: string | CacheLifeConfig\n) {\n const store = workAsyncStorage.getStore()\n if (!store || !store.incrementalCache) {\n throw new Error(\n `Invariant: static generation store missing in ${expression}`\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n if (workUnitStore.phase === 'render') {\n throw new Error(\n `Route ${store.route} used \"${expression}\" during render which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside a \"use cache\" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'unstable-cache':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside a function cached with \"unstable_cache(...)\" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside \\`generateStaticParams\\` which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'prerender':\n case 'prerender-runtime':\n // cacheComponents Prerender\n const error = new Error(\n `Route ${store.route} used ${expression} without first calling \\`await connection()\\`.`\n )\n return abortAndThrowOnSynchronousRequestDataAccess(\n store.route,\n expression,\n error,\n workUnitStore\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n `${expression} must not be used within a client component. Next.js should be preventing ${expression} from being included in client components statically, but did not in this case.`\n )\n case 'prerender-ppr':\n return postponeWithTracking(\n store.route,\n expression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n workUnitStore.revalidate = 0\n\n const err = new DynamicServerError(\n `Route ${store.route} couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n )\n store.dynamicUsageDescription = expression\n store.dynamicUsageStack = err.stack\n\n throw err\n case 'request':\n if (process.env.NODE_ENV !== 'production') {\n // TODO: This is most likely incorrect. It would lead to the ISR\n // status being flipped when revalidating a static page with a server\n // action.\n workUnitStore.usedDynamic = true\n // TODO(restart-on-cache-miss): we should do a sync IO error here in dev\n // to match prerender behavior\n }\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (!store.pendingRevalidatedTags) {\n store.pendingRevalidatedTags = []\n }\n\n const revalidatedAt = performance.timeOrigin + performance.now()\n\n for (const tag of tags) {\n const existingIndex = store.pendingRevalidatedTags.findIndex((item) => {\n if (item.tag !== tag) return false\n // Compare profiles: both strings, both objects, or both undefined\n if (typeof item.profile === 'string' && typeof profile === 'string') {\n return item.profile === profile\n }\n if (typeof item.profile === 'object' && typeof profile === 'object') {\n return JSON.stringify(item.profile) === JSON.stringify(profile)\n }\n return item.profile === profile\n })\n if (existingIndex === -1) {\n store.pendingRevalidatedTags.push({\n tag,\n profile,\n revalidatedAt,\n })\n } else {\n // Revalidating a tag again invalidates everything produced up to now, so\n // the latest revalidation is the one that decides which entries are\n // stale.\n store.pendingRevalidatedTags[existingIndex].revalidatedAt = revalidatedAt\n }\n }\n\n // if profile is provided and this is a stale-while-revalidate\n // update we do not mark the path as revalidated so that server\n // actions don't pull their own writes\n const cacheLife =\n profile && typeof profile === 'object'\n ? profile\n : profile &&\n typeof profile === 'string' &&\n store?.cacheLifeProfiles[profile]\n ? store.cacheLifeProfiles[profile]\n : undefined\n\n if (!profile || cacheLife?.expire === 0) {\n // TODO: only revalidate if the path matches\n store.pathWasRevalidated = ActionDidRevalidate\n }\n}\n"],"names":["abortAndThrowOnSynchronousRequestDataAccess","postponeWithTracking","isDynamicRoute","NEXT_CACHE_IMPLICIT_TAG_ID","NEXT_CACHE_SOFT_TAG_MAX_LENGTH","workAsyncStorage","workUnitAsyncStorage","DynamicServerError","InvariantError","ActionDidRevalidateDynamicOnly","ActionDidRevalidateStaticAndDynamic","ActionDidRevalidate","removeTrailingSlash","encodeCacheTag","validateAndNormalizeCacheLifeProfile","revalidateTag","tag","profile","console","warn","kind","revalidate","updateTag","workStore","getStore","page","endsWith","Error","undefined","refresh","workUnitStore","phase","pathWasRevalidated","revalidatePath","originalPath","type","length","normalizedPath","tags","push","expression","store","incrementalCache","route","error","dynamicTracking","err","dynamicUsageDescription","dynamicUsageStack","stack","process","env","NODE_ENV","usedDynamic","pendingRevalidatedTags","revalidatedAt","performance","timeOrigin","now","existingIndex","findIndex","item","JSON","stringify","cacheLife","cacheLifeProfiles","exp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OAAO4C,KAAK5C,OAAO,KAAKA;QAC1B;QACA,IAAI0C,kBAAkB,CAAC,GAAG;YACxBlB,MAAMa,sBAAsB,CAACf,IAAI,CAAC;gBAChCvB;gBACAC;gBACAsC;YACF;QACF,OAAO;YACL,yEAAyE;YACzE,oEAAoE;YACpE,SAAS;YACTd,MAAMa,sBAAsB,CAACK,cAAc,CAACJ,aAAa,GAAGA;QAC9D;IACF;IAEA,8DAA8D;IAC9D,+DAA+D;IAC/D,sCAAsC;IACtC,MAAMS,YACJ/C,WAAW,OAAOA,YAAY,WAC1BA,UACAA,WACE,OAAOA,YAAY,aACnBwB,yBAAAA,MAAOwB,iBAAiB,CAAChD,QAAQ,IACjCwB,MAAMwB,iBAAiB,CAAChD,QAAQ,GAChCW;IAER,IAAI,CAACX,WAAW+C,CAAAA,6BAAAA,UAAWE,MAAM,MAAK,GAAG;QACvC,4CAA4C;QAC5CzB,MAAMT,kBAAkB,GAAGrB;IAC7B;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/server/web/spec-extension/revalidate.ts"],"sourcesContent":["import {\n abortAndThrowOnSynchronousRequestDataAccess,\n postponeWithTracking,\n} from '../../app-render/dynamic-rendering'\nimport { isDynamicRoute } from '../../../shared/lib/router/utils'\nimport {\n NEXT_CACHE_IMPLICIT_TAG_ID,\n NEXT_CACHE_SOFT_TAG_MAX_LENGTH,\n} from '../../../lib/constants'\nimport { workAsyncStorage } from '../../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.external'\nimport { DynamicServerError } from '../../../client/components/hooks-server-context'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport {\n ActionDidRevalidateDynamicOnly,\n ActionDidRevalidateStaticAndDynamic as ActionDidRevalidate,\n} from '../../../shared/lib/action-revalidation-kind'\nimport { removeTrailingSlash } from '../../../shared/lib/router/utils/remove-trailing-slash'\nimport { encodeHeaderSafe } from '../../lib/encode-header-safe'\nimport { validateAndNormalizeCacheLifeProfile } from '../../use-cache/cache-life-profile'\n\ntype CacheLifeConfig = {\n expire?: number\n}\n\n/**\n * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.\n *\n * The second argument specifies a [`cacheLife`](https://nextjs.org/docs/app/api-reference/functions/cacheLife#reference) profile\n * (e.g. `\"max\"`), or a `{ expire }` object. For immediate expiration in Server Actions, use\n * [`updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag) instead.\n *\n * Read more: [Next.js Docs: `revalidateTag`](https://nextjs.org/docs/app/api-reference/functions/revalidateTag)\n */\nexport function revalidateTag(tag: string, profile: string | CacheLifeConfig) {\n if (!profile) {\n console.warn(\n '\"revalidateTag\" without the second argument is now deprecated, add second argument of \"max\" or use \"updateTag\". See more info here: https://nextjs.org/docs/messages/revalidate-tag-single-arg'\n )\n } else if (typeof profile === 'object') {\n profile = validateAndNormalizeCacheLifeProfile(profile, { kind: 'inline' })\n }\n return revalidate([encodeHeaderSafe(tag)], `revalidateTag ${tag}`, profile)\n}\n\n/**\n * This function allows you to update [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.\n * This can only be called from within a Server Action to enable read-your-own-writes semantics.\n *\n * Read more: [Next.js Docs: `updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag)\n */\nexport function updateTag(tag: string) {\n const workStore = workAsyncStorage.getStore()\n\n // TODO: change this after investigating why phase: 'action' is\n // set for route handlers\n if (!workStore || workStore.page.endsWith('/route')) {\n throw new Error(\n 'updateTag can only be called from within a Server Action. ' +\n 'To invalidate cache tags in Route Handlers or other contexts, use revalidateTag instead. ' +\n 'See more info here: https://nextjs.org/docs/app/api-reference/functions/updateTag'\n )\n }\n // updateTag uses immediate expiration (no profile) without deprecation warning\n return revalidate([encodeHeaderSafe(tag)], `updateTag ${tag}`, undefined)\n}\n\n/**\n * This function allows you to refresh client cache from server actions.\n * It's useful as dynamic data can be cached on the client which won't\n * be refreshed by updateTag\n */\nexport function refresh() {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (\n !workStore ||\n workStore.page.endsWith('/route') ||\n workUnitStore?.phase !== 'action'\n ) {\n throw new Error(\n 'refresh can only be called from within a Server Action. ' +\n 'See more info here: https://nextjs.org/docs/app/api-reference/functions/refresh'\n )\n }\n\n if (workStore) {\n // The Server Action version of refresh() only revalidates the dynamic data\n // on the client. It doesn't affect cached data.\n workStore.pathWasRevalidated = ActionDidRevalidateDynamicOnly\n }\n}\n\n/**\n * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific path.\n *\n * Read more: [Next.js Docs: `revalidatePath`](https://nextjs.org/docs/app/api-reference/functions/revalidatePath)\n */\nexport function revalidatePath(originalPath: string, type?: 'layout' | 'page') {\n if (originalPath.length > NEXT_CACHE_SOFT_TAG_MAX_LENGTH) {\n console.warn(\n `Warning: revalidatePath received \"${originalPath}\" which exceeded max length of ${NEXT_CACHE_SOFT_TAG_MAX_LENGTH}. See more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`\n )\n return\n }\n\n let normalizedPath = `${NEXT_CACHE_IMPLICIT_TAG_ID}${encodeHeaderSafe(removeTrailingSlash(originalPath))}`\n\n if (type) {\n normalizedPath += `${normalizedPath.endsWith('/') ? '' : '/'}${type}`\n } else if (isDynamicRoute(originalPath)) {\n console.warn(\n `Warning: a dynamic page path \"${originalPath}\" was passed to \"revalidatePath\", but the \"type\" parameter is missing. This has no effect by default, see more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`\n )\n }\n\n const tags = [normalizedPath]\n if (normalizedPath === `${NEXT_CACHE_IMPLICIT_TAG_ID}/`) {\n tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)\n } else if (normalizedPath === `${NEXT_CACHE_IMPLICIT_TAG_ID}/index`) {\n tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)\n }\n\n return revalidate(tags, `revalidatePath ${originalPath}`)\n}\n\nfunction revalidate(\n tags: string[],\n expression: string,\n profile?: string | CacheLifeConfig\n) {\n const store = workAsyncStorage.getStore()\n if (!store || !store.incrementalCache) {\n throw new Error(\n `Invariant: static generation store missing in ${expression}`\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n if (workUnitStore.phase === 'render') {\n throw new Error(\n `Route ${store.route} used \"${expression}\" during render which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside a \"use cache\" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'unstable-cache':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside a function cached with \"unstable_cache(...)\" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside \\`generateStaticParams\\` which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'prerender':\n case 'prerender-runtime':\n // cacheComponents Prerender\n const error = new Error(\n `Route ${store.route} used ${expression} without first calling \\`await connection()\\`.`\n )\n return abortAndThrowOnSynchronousRequestDataAccess(\n store.route,\n expression,\n error,\n workUnitStore\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n `${expression} must not be used within a client component. Next.js should be preventing ${expression} from being included in client components statically, but did not in this case.`\n )\n case 'prerender-ppr':\n return postponeWithTracking(\n store.route,\n expression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n workUnitStore.revalidate = 0\n\n const err = new DynamicServerError(\n `Route ${store.route} couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n )\n store.dynamicUsageDescription = expression\n store.dynamicUsageStack = err.stack\n\n throw err\n case 'request':\n if (process.env.NODE_ENV !== 'production') {\n // TODO: This is most likely incorrect. It would lead to the ISR\n // status being flipped when revalidating a static page with a server\n // action.\n workUnitStore.usedDynamic = true\n // TODO(restart-on-cache-miss): we should do a sync IO error here in dev\n // to match prerender behavior\n }\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (!store.pendingRevalidatedTags) {\n store.pendingRevalidatedTags = []\n }\n\n const revalidatedAt = performance.timeOrigin + performance.now()\n\n for (const tag of tags) {\n const existingIndex = store.pendingRevalidatedTags.findIndex((item) => {\n if (item.tag !== tag) return false\n // Compare profiles: both strings, both objects, or both undefined\n if (typeof item.profile === 'string' && typeof profile === 'string') {\n return item.profile === profile\n }\n if (typeof item.profile === 'object' && typeof profile === 'object') {\n return JSON.stringify(item.profile) === JSON.stringify(profile)\n }\n return item.profile === profile\n })\n if (existingIndex === -1) {\n store.pendingRevalidatedTags.push({\n tag,\n profile,\n revalidatedAt,\n })\n } else {\n // Revalidating a tag again invalidates everything produced up to now, so\n // the latest revalidation is the one that decides which entries are\n // stale.\n store.pendingRevalidatedTags[existingIndex].revalidatedAt = revalidatedAt\n }\n }\n\n // if profile is provided and this is a stale-while-revalidate\n // update we do not mark the path as revalidated so that server\n // actions don't pull their own writes\n const cacheLife =\n profile && typeof profile === 'object'\n ? profile\n : profile &&\n typeof profile === 'string' &&\n store?.cacheLifeProfiles[profile]\n ? store.cacheLifeProfiles[profile]\n : undefined\n\n if (!profile || cacheLife?.expire === 0) {\n // TODO: only revalidate if the path matches\n store.pathWasRevalidated = ActionDidRevalidate\n }\n}\n"],"names":["abortAndThrowOnSynchronousRequestDataAccess","postponeWithTracking","isDynamicRoute","NEXT_CACHE_IMPLICIT_TAG_ID","NEXT_CACHE_SOFT_TAG_MAX_LENGTH","workAsyncStorage","workUnitAsyncStorage","DynamicServerError","InvariantError","ActionDidRevalidateDynamicOnly","ActionDidRevalidateStaticAndDynamic","ActionDidRevalidate","removeTrailingSlash","encodeHeaderSafe","validateAndNormalizeCacheLifeProfile","revalidateTag","tag","profile","console","warn","kind","revalidate","updateTag","workStore","getStore","page","endsWith","Error","undefined","refresh","workUnitStore","phase","pathWasRevalidated","revalidatePath","originalPath","type","length","normalizedPath","tags","push","expression","store","incrementalCache","route","error","dynamicTracking","err","dynamicUsageDescription","dynamicUsageStack","stack","process","env","NODE_ENV","usedDynamic","pendingRevalidatedTags","revalidatedAt","performance","timeOrigin","now","existingIndex","findIndex","item","JSON","stringify","cacheLife","cacheLifeProfiles","expire"],"mappings":"AAAA,SACEA,2CAA2C,EAC3CC,oBAAoB,QACf,qCAAoC;AAC3C,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SACEC,0BAA0B,EAC1BC,8BAA8B,QACzB,yBAAwB;AAC/B,SAASC,gBAAgB,QAAQ,+CAA8C;AAC/E,SAASC,oBAAoB,QAAQ,oDAAmD;AACxF,SAASC,kBAAkB,QAAQ,kDAAiD;AACpF,SAASC,cAAc,QAAQ,sCAAqC;AACpE,SACEC,8BAA8B,EAC9BC,uCAAuCC,mBAAmB,QACrD,+CAA8C;AACrD,SAASC,mBAAmB,QAAQ,yDAAwD;AAC5F,SAASC,gBAAgB,QAAQ,+BAA8B;AAC/D,SAASC,oCAAoC,QAAQ,qCAAoC;AAMzF;;;;;;;;CAQC,GACD,OAAO,SAASC,cAAcC,GAAW,EAAEC,OAAiC;IAC1E,IAAI,CAACA,SAAS;QACZC,QAAQC,IAAI,CACV;IAEJ,OAAO,IAAI,OAAOF,YAAY,UAAU;QACtCA,UAAUH,qCAAqCG,SAAS;YAAEG,MAAM;QAAS;IAC3E;IACA,OAAOC,WAAW;QAACR,iBAAiBG;KAAK,EAAE,CAAC,cAAc,EAAEA,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G,EAAE;IACnC;IAEA,MAAMC,gBAAgBC,YAAYC,UAAU,GAAGD,YAAYE,GAAG;IAE9D,KAAK,MAAM1C,OAAOsB,KAAM;QACtB,MAAMqB,gBAAgBlB,MAAMa,sBAAsB,CAACM,SAAS,CAAC,CAACC;YAC5D,IAAIA,KAAK7C,GAAG,KAAKA,KAAK,OAAO;YAC7B,kEAAkE;YAClE,IAAI,OAAO6C,KAAK5C,OAAO,KAAK,YAAY,OAAOA,YAAY,UAAU;gBACnE,OAAO4C,KAAK5C,OAAO,KAAKA;YAC1B;YACA,IAAI,OAAO4C,KAAK5C,OAAO,KAAK,YAAY,OAAOA,YAAY,UAAU;gBACnE,OAAO6C,KAAKC,SAAS,CAACF,KAAK5C,OAAO,MAAM6C,KAAKC,SAAS,CAAC9C;YACzD;YACA,OAAO4C,KAAK5C,OAAO,KAAKA;QAC1B;QACA,IAAI0C,kBAAkB,CAAC,GAAG;YACxBlB,MAAMa,sBAAsB,CAACf,IAAI,CAAC;gBAChCvB;gBACAC;gBACAsC;YACF;QACF,OAAO;YACL,yEAAyE;YACzE,oEAAoE;YACpE,SAAS;YACTd,MAAMa,sBAAsB,CAACK,cAAc,CAACJ,aAAa,GAAGA;QAC9D;IACF;IAEA,8DAA8D;IAC9D,+DAA+D;IAC/D,sCAAsC;IACtC,MAAMS,YACJ/C,WAAW,OAAOA,YAAY,WAC1BA,UACAA,WACE,OAAOA,YAAY,aACnBwB,yBAAAA,MAAOwB,iBAAiB,CAAChD,QAAQ,IACjCwB,MAAMwB,iBAAiB,CAAChD,QAAQ,GAChCW;IAER,IAAI,CAACX,WAAW+C,CAAAA,6BAAAA,UAAWE,MAAM,MAAK,GAAG;QACvC,4CAA4C;QAC5CzB,MAAMT,kBAAkB,GAAGrB;IAC7B;AACF","ignoreList":[0]} |
| import { CACHE_ONE_YEAR_SECONDS } from '../../../lib/constants'; | ||
| import { validateRevalidate, validateTags } from '../../lib/patch-fetch'; | ||
| import { encodeHeaderSafe } from '../../lib/encode-header-safe'; | ||
| import { workAsyncStorage } from '../../app-render/work-async-storage.external'; | ||
@@ -81,3 +82,14 @@ import { getCacheSignal, getDraftModeProviderForCacheScope, willConsumerServerCache, workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.external'; | ||
| // $urlWithPath,$sortedQueryStringKeys,$hashOfEveryThingElse | ||
| const fetchUrl = `unstable_cache ${fetchUrlPrefix} ${cb.name ? ` ${cb.name}` : cacheKey}`; | ||
| // | ||
| // A cache implementation may serialize this name into an HTTP request | ||
| // header, so it is encoded here. Both parts can carry a character above | ||
| // U+00FF: the search parameters are decoded, and a JavaScript identifier | ||
| // may hold one. The character class leaves the separating spaces and the | ||
| // URL punctuation untouched, so the shape above is preserved. | ||
| // | ||
| // `toWellFormed` replaces lone surrogates, which `cb.name` can hold and | ||
| // which `encodeURIComponent` rejects. The name identifies the call for | ||
| // debug metrics, so a replacement character is an acceptable trade for | ||
| // not failing the render. | ||
| const fetchUrl = encodeHeaderSafe(`unstable_cache ${fetchUrlPrefix} ${cb.name ? ` ${cb.name}` : cacheKey}`.toWellFormed()); | ||
| const fetchIdx = (workStore ? workStore.nextFetchId : noStoreFetchIdx) ?? 1; | ||
@@ -84,0 +96,0 @@ const implicitTags = workUnitStore == null ? void 0 : workUnitStore.implicitTags; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/server/web/spec-extension/unstable-cache.ts"],"sourcesContent":["import type { IncrementalCache } from '../../lib/incremental-cache'\n\nimport { CACHE_ONE_YEAR_SECONDS } from '../../../lib/constants'\nimport { validateRevalidate, validateTags } from '../../lib/patch-fetch'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../../app-render/work-async-storage.external'\nimport {\n getCacheSignal,\n getDraftModeProviderForCacheScope,\n willConsumerServerCache,\n workUnitAsyncStorage,\n} from '../../app-render/work-unit-async-storage.external'\nimport {\n CachedRouteKind,\n IncrementalCacheKind,\n type CachedFetchData,\n} from '../../response-cache'\nimport type {\n UnstableCacheStore,\n WorkUnitStore,\n} from '../../app-render/work-unit-async-storage.external'\n\ntype Callback = (...args: any[]) => Promise<any>\n\nlet noStoreFetchIdx = 0\n\nasync function cacheNewResult<T>(\n result: T,\n incrementalCache: IncrementalCache,\n cacheKey: string,\n tags: string[],\n revalidate: number | false | undefined,\n fetchIdx: number,\n fetchUrl: string\n): Promise<unknown> {\n await incrementalCache.set(\n cacheKey,\n {\n kind: CachedRouteKind.FETCH,\n data: {\n headers: {},\n // TODO: handle non-JSON values?\n body: JSON.stringify(result),\n status: 200,\n url: '',\n } satisfies CachedFetchData,\n revalidate:\n typeof revalidate !== 'number' ? CACHE_ONE_YEAR_SECONDS : revalidate,\n },\n { fetchCache: true, tags, fetchIdx, fetchUrl }\n )\n return\n}\n\n/**\n * This function allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests.\n *\n * Read more: [Next.js Docs: `unstable_cache`](https://nextjs.org/docs/app/api-reference/functions/unstable_cache)\n */\nexport function unstable_cache<T extends Callback>(\n cb: T,\n keyParts?: string[],\n options: {\n /**\n * The revalidation interval in seconds.\n */\n revalidate?: number | false\n tags?: string[]\n } = {}\n): T {\n if (options.revalidate === 0) {\n throw new Error(\n `Invariant revalidate: 0 can not be passed to unstable_cache(), must be \"false\" or \"> 0\" ${cb.toString()}`\n )\n }\n\n // Validate the tags provided are valid\n const tags = options.tags\n ? validateTags(options.tags, `unstable_cache ${cb.toString()}`)\n : []\n\n // Validate the revalidate option, and adopt the normalized value, which\n // maps `false` and `Infinity` to INFINITE_CACHE so that the stored value\n // survives JSON serialization.\n const revalidate = validateRevalidate(\n options.revalidate,\n `unstable_cache ${cb.name || cb.toString()}`\n )\n\n // Stash the fixed part of the key at construction time. The invocation key will combine\n // the fixed key with the arguments when actually called\n // @TODO if cb.toString() is long we should hash it\n // @TODO come up with a collision-free way to combine keyParts\n // @TODO consider validating the keyParts are all strings. TS can't provide runtime guarantees\n // and the error produced by accidentally using something that cannot be safely coerced is likely\n // hard to debug\n const fixedKey = `${cb.toString()}-${\n Array.isArray(keyParts) && keyParts.join(',')\n }`\n\n const cachedCb = async (...args: any[]) => {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // We must be able to find the incremental cache otherwise we throw\n const maybeIncrementalCache:\n | import('../../lib/incremental-cache').IncrementalCache\n | undefined =\n workStore?.incrementalCache || (globalThis as any).__incrementalCache\n\n if (!maybeIncrementalCache) {\n throw new Error(\n `Invariant: incrementalCache missing in unstable_cache ${cb.toString()}`\n )\n }\n const incrementalCache = maybeIncrementalCache\n\n const cacheSignal = workUnitStore ? getCacheSignal(workUnitStore) : null\n if (cacheSignal) {\n cacheSignal.beginRead()\n }\n try {\n // If there's no request store, we aren't in a request (or we're not in\n // app router) and if there's no static generation store, we aren't in app\n // router. Default to an empty pathname and search params when there's no\n // request store or static generation store available.\n const fetchUrlPrefix =\n workStore && workUnitStore\n ? getFetchUrlPrefix(workStore, workUnitStore)\n : ''\n\n // Construct the complete cache key for this function invocation\n // @TODO stringify is likely not safe here. We will coerce undefined to null which will make\n // the keyspace smaller than the execution space\n const invocationKey = `${fixedKey}-${JSON.stringify(args)}`\n const cacheKey =\n await incrementalCache.generateSimpleCacheKey(invocationKey)\n // $urlWithPath,$sortedQueryStringKeys,$hashOfEveryThingElse\n const fetchUrl = `unstable_cache ${fetchUrlPrefix} ${cb.name ? ` ${cb.name}` : cacheKey}`\n const fetchIdx =\n (workStore ? workStore.nextFetchId : noStoreFetchIdx) ?? 1\n\n const implicitTags = workUnitStore?.implicitTags\n\n const innerCacheStore: UnstableCacheStore = {\n type: 'unstable-cache',\n phase: 'render',\n consumerWillServerCache: true,\n implicitTags,\n draftMode:\n workUnitStore &&\n workStore &&\n getDraftModeProviderForCacheScope(workStore, workUnitStore),\n rootParams: undefined,\n }\n\n if (workStore) {\n workStore.nextFetchId = fetchIdx + 1\n\n // We are in an App Router context. We try to return the cached entry if it exists and is valid\n // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in\n // the background. If the entry is missing or invalid we generate a new entry and return it.\n\n let isNestedUnstableCache = false\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n // We update the store's revalidate property if the revalidate option is a higher precedence\n // revalidate === undefined doesn't affect timing.\n // revalidate === INFINITE_CACHE (from `false` or `Infinity`) doesn't shrink timing. it stays at the maximum.\n if (typeof revalidate === 'number') {\n if (workUnitStore.revalidate < revalidate) {\n // The store is already revalidating on a shorter time interval, leave it alone\n } else {\n workUnitStore.revalidate = revalidate\n }\n }\n\n // We need to accumulate the tags for this invocation within the store\n const collectedTags = workUnitStore.tags\n if (collectedTags === null) {\n workUnitStore.tags = tags.slice()\n } else {\n for (const tag of tags) {\n // @TODO refactor tags to be a set to avoid this O(n) lookup\n if (!collectedTags.includes(tag)) {\n collectedTags.push(tag)\n }\n }\n }\n break\n case 'unstable-cache':\n isNestedUnstableCache = true\n break\n case 'prerender-client':\n case 'validation-client':\n case 'request':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (\n // when we are nested inside of other unstable_cache's\n // we should bypass cache similar to fetches\n !isNestedUnstableCache &&\n workStore.fetchCache !== 'force-no-store' &&\n !workStore.isOnDemandRevalidate &&\n !incrementalCache.isOnDemandRevalidate &&\n !workStore.isDraftMode\n ) {\n // We attempt to get the current cache entry from the incremental cache.\n const cacheEntry = await incrementalCache.get(cacheKey, {\n kind: IncrementalCacheKind.FETCH,\n revalidate,\n tags,\n softTags: implicitTags?.tags,\n fetchIdx,\n fetchUrl,\n })\n\n if (cacheEntry && cacheEntry.value) {\n // The entry exists and has a value\n if (cacheEntry.value.kind !== CachedRouteKind.FETCH) {\n // The entry is invalid and we need a special warning\n // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced\n // so bugs can be reported\n // @TODO the invocation key can have sensitive data in it. we should not log this entire object\n console.error(\n `Invariant invalid cacheEntry returned for ${invocationKey}`\n )\n // will fall through to generating a new cache entry below\n } else {\n // We have a valid cache entry so we will be returning it. We also check to see if we need\n // to background revalidate it by checking if it is stale.\n const cachedResponse =\n cacheEntry.value.data.body !== undefined\n ? JSON.parse(cacheEntry.value.data.body)\n : undefined\n\n if (cacheEntry.isStale) {\n if (!workStore.pendingRevalidates) {\n workStore.pendingRevalidates = {}\n }\n\n // Check if there's already a pending revalidation to avoid duplicate work\n if (!workStore.pendingRevalidates[invocationKey]) {\n // Create the revalidation promise\n const revalidationPromise = workUnitAsyncStorage\n .run(innerCacheStore, cb, ...args)\n .then(async (result) => {\n await cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n return result\n })\n .catch((err) => {\n // @TODO This error handling seems wrong. We swallow the error?\n console.error(\n `revalidating cache with key: ${invocationKey}`,\n err\n )\n // Return the stale value on error for foreground revalidation\n return cachedResponse\n })\n\n // Attach the empty catch here so we don't get a \"unhandled promise\n // rejection\" warning. (Behavior is matched with patch-fetch)\n if (willConsumerServerCache(workUnitStore)) {\n revalidationPromise.catch(() => {})\n }\n\n workStore.pendingRevalidates[invocationKey] =\n revalidationPromise\n }\n\n // Check if we need to do foreground revalidation\n if (willConsumerServerCache(workUnitStore)) {\n // When the consumer will persist this result in a server\n // cache, wait for fresh data so it doesn't persist a stale\n // value. The `await` here also keeps `cacheSignal.endRead` (in\n // the outer `finally`) suspended until the recompute +\n // cacheNewResult actually complete, so a prospective\n // prerender's `cacheSignal` doesn't resolve `cacheReady`\n // prematurely.\n return await workStore.pendingRevalidates[invocationKey]\n }\n // Otherwise, we're doing background revalidation - return stale immediately\n }\n\n // We had a valid cache entry so we return it here\n return cachedResponse\n }\n }\n }\n\n // If we got this far then we had an invalid cache entry and need to generate a new one\n const result = await workUnitAsyncStorage.run(\n innerCacheStore,\n cb,\n ...args\n )\n\n if (!workStore.isDraftMode) {\n if (!workStore.pendingRevalidates) {\n workStore.pendingRevalidates = {}\n }\n\n // We need to push the cache result promise to pending\n // revalidates otherwise it won't be awaited and is just\n // dangling\n workStore.pendingRevalidates[invocationKey] = cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n }\n\n return result\n } else {\n noStoreFetchIdx += 1\n // We are in Pages Router or were called outside of a render. We don't have a store\n // so we just call the callback directly when it needs to run.\n // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in\n // the background. If the entry is missing or invalid we generate a new entry and return it.\n\n if (!incrementalCache.isOnDemandRevalidate) {\n // We aren't doing an on demand revalidation so we check use the cache if valid\n const cacheEntry = await incrementalCache.get(cacheKey, {\n kind: IncrementalCacheKind.FETCH,\n revalidate,\n tags,\n fetchIdx,\n fetchUrl,\n softTags: implicitTags?.tags,\n })\n\n if (cacheEntry && cacheEntry.value) {\n // The entry exists and has a value\n if (cacheEntry.value.kind !== CachedRouteKind.FETCH) {\n // The entry is invalid and we need a special warning\n // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced\n // so bugs can be reported\n console.error(\n `Invariant invalid cacheEntry returned for ${invocationKey}`\n )\n // will fall through to generating a new cache entry below\n } else if (!cacheEntry.isStale) {\n // We have a valid cache entry and it is fresh so we return it\n return cacheEntry.value.data.body !== undefined\n ? JSON.parse(cacheEntry.value.data.body)\n : undefined\n }\n }\n }\n\n // If we got this far then we had an invalid cache entry and need to generate a new one\n const result = await workUnitAsyncStorage.run(\n innerCacheStore,\n cb,\n ...args\n )\n\n // we need to wait setting the new cache result here as\n // we don't have pending revalidates on workStore to\n // push to and we can't have a dangling promise\n await cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n return result\n }\n } finally {\n if (cacheSignal) {\n cacheSignal.endRead()\n }\n }\n }\n // TODO: once AsyncLocalStorage.run() returns the correct types this override will no longer be necessary\n return cachedCb as unknown as T\n}\n\nfunction getFetchUrlPrefix(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): string {\n switch (workUnitStore.type) {\n case 'request':\n const pathname = workUnitStore.url.pathname\n const searchParams = new URLSearchParams(workUnitStore.url.search)\n\n const sortedSearch = [...searchParams.keys()]\n .sort((a, b) => a.localeCompare(b))\n .map((key) => `${key}=${searchParams.get(key)}`)\n .join('&')\n\n return `${pathname}${sortedSearch.length ? '?' : ''}${sortedSearch}`\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return workStore.route\n default:\n return workUnitStore satisfies never\n }\n}\n"],"names":["CACHE_ONE_YEAR_SECONDS","validateRevalidate","validateTags","workAsyncStorage","getCacheSignal","getDraftModeProviderForCacheScope","willConsumerServerCache","workUnitAsyncStorage","CachedRouteKind","IncrementalCacheKind","noStoreFetchIdx","cacheNewResult","result","incrementalCache","cacheKey","tags","revalidate","fetchIdx","fetchUrl","set","kind","FETCH","data","headers","body","JSON","stringify","status","url","fetchCache","unstable_cache","cb","keyParts","options","Error","toString","name","fixedKey","Array","isArray","join","cachedCb","args","workStore","getStore","workUnitStore","maybeIncrementalCache","globalThis","__incrementalCache","cacheSignal","beginRead","fetchUrlPrefix","getFetchUrlPrefix","invocationKey","generateSimpleCacheKey","nextFetchId","implicitTags","innerCacheStore","type","phase","consumerWillServerCache","draftMode","rootParams","undefined","isNestedUnstableCache","collectedTags","slice","tag","includes","push","isOnDemandRevalidate","isDraftMode","cacheEntry","get","softTags","value","console","error","cachedResponse","parse","isStale","pendingRevalidates","revalidationPromise","run","then","catch","err","endRead","pathname","searchParams","URLSearchParams","search","sortedSearch","keys","sort","a","b","localeCompare","map","key","length","route"],"mappings":"AAEA,SAASA,sBAAsB,QAAQ,yBAAwB;AAC/D,SAASC,kBAAkB,EAAEC,YAAY,QAAQ,wBAAuB;AACxE,SACEC,gBAAgB,QAEX,+CAA8C;AACrD,SACEC,cA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,CAACmB,WAAWQ,OAAO,EAAE;4BAC9B,8DAA8D;4BAC9D,OAAOR,WAAWG,KAAK,CAACrD,IAAI,CAACE,IAAI,KAAKuC,YAClCtC,KAAKsD,KAAK,CAACP,WAAWG,KAAK,CAACrD,IAAI,CAACE,IAAI,IACrCuC;wBACN;oBACF;gBACF;gBAEA,uFAAuF;gBACvF,MAAMnD,SAAS,MAAML,qBAAqB4E,GAAG,CAC3C1B,iBACA1B,OACGW;gBAGL,uDAAuD;gBACvD,oDAAoD;gBACpD,+CAA+C;gBAC/C,MAAM/B,eACJC,QACAC,kBACAC,UACAC,MACAC,YACAC,UACAC;gBAEF,OAAON;YACT;QACF,SAAU;YACR,IAAIqC,aAAa;gBACfA,YAAYsC,OAAO;YACrB;QACF;IACF;IACA,yGAAyG;IACzG,OAAO9C;AACT;AAEA,SAASW,kBACPT,SAAoB,EACpBE,aAA4B;IAE5B,OAAQA,cAAca,IAAI;QACxB,KAAK;YACH,MAAM8B,WAAW3C,cAAcjB,GAAG,CAAC4D,QAAQ;YAC3C,MAAMC,eAAe,IAAIC,gBAAgB7C,cAAcjB,GAAG,CAAC+D,MAAM;YAEjE,MAAMC,eAAe;mBAAIH,aAAaI,IAAI;aAAG,CAC1CC,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAEE,aAAa,CAACD,IAC/BE,GAAG,CAAC,CAACC,MAAQ,GAAGA,IAAI,CAAC,EAAEV,aAAahB,GAAG,CAAC0B,MAAM,EAC9C3D,IAAI,CAAC;YAER,OAAO,GAAGgD,WAAWI,aAAaQ,MAAM,GAAG,MAAM,KAAKR,cAAc;QACtE,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOjD,UAAU0D,KAAK;QACxB;YACE,OAAOxD;IACX;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/server/web/spec-extension/unstable-cache.ts"],"sourcesContent":["import type { IncrementalCache } from '../../lib/incremental-cache'\n\nimport { CACHE_ONE_YEAR_SECONDS } from '../../../lib/constants'\nimport { validateRevalidate, validateTags } from '../../lib/patch-fetch'\nimport { encodeHeaderSafe } from '../../lib/encode-header-safe'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../../app-render/work-async-storage.external'\nimport {\n getCacheSignal,\n getDraftModeProviderForCacheScope,\n willConsumerServerCache,\n workUnitAsyncStorage,\n} from '../../app-render/work-unit-async-storage.external'\nimport {\n CachedRouteKind,\n IncrementalCacheKind,\n type CachedFetchData,\n} from '../../response-cache'\nimport type {\n UnstableCacheStore,\n WorkUnitStore,\n} from '../../app-render/work-unit-async-storage.external'\n\ntype Callback = (...args: any[]) => Promise<any>\n\nlet noStoreFetchIdx = 0\n\nasync function cacheNewResult<T>(\n result: T,\n incrementalCache: IncrementalCache,\n cacheKey: string,\n tags: string[],\n revalidate: number | false | undefined,\n fetchIdx: number,\n fetchUrl: string\n): Promise<unknown> {\n await incrementalCache.set(\n cacheKey,\n {\n kind: CachedRouteKind.FETCH,\n data: {\n headers: {},\n // TODO: handle non-JSON values?\n body: JSON.stringify(result),\n status: 200,\n url: '',\n } satisfies CachedFetchData,\n revalidate:\n typeof revalidate !== 'number' ? CACHE_ONE_YEAR_SECONDS : revalidate,\n },\n { fetchCache: true, tags, fetchIdx, fetchUrl }\n )\n return\n}\n\n/**\n * This function allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests.\n *\n * Read more: [Next.js Docs: `unstable_cache`](https://nextjs.org/docs/app/api-reference/functions/unstable_cache)\n */\nexport function unstable_cache<T extends Callback>(\n cb: T,\n keyParts?: string[],\n options: {\n /**\n * The revalidation interval in seconds.\n */\n revalidate?: number | false\n tags?: string[]\n } = {}\n): T {\n if (options.revalidate === 0) {\n throw new Error(\n `Invariant revalidate: 0 can not be passed to unstable_cache(), must be \"false\" or \"> 0\" ${cb.toString()}`\n )\n }\n\n // Validate the tags provided are valid\n const tags = options.tags\n ? validateTags(options.tags, `unstable_cache ${cb.toString()}`)\n : []\n\n // Validate the revalidate option, and adopt the normalized value, which\n // maps `false` and `Infinity` to INFINITE_CACHE so that the stored value\n // survives JSON serialization.\n const revalidate = validateRevalidate(\n options.revalidate,\n `unstable_cache ${cb.name || cb.toString()}`\n )\n\n // Stash the fixed part of the key at construction time. The invocation key will combine\n // the fixed key with the arguments when actually called\n // @TODO if cb.toString() is long we should hash it\n // @TODO come up with a collision-free way to combine keyParts\n // @TODO consider validating the keyParts are all strings. TS can't provide runtime guarantees\n // and the error produced by accidentally using something that cannot be safely coerced is likely\n // hard to debug\n const fixedKey = `${cb.toString()}-${\n Array.isArray(keyParts) && keyParts.join(',')\n }`\n\n const cachedCb = async (...args: any[]) => {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // We must be able to find the incremental cache otherwise we throw\n const maybeIncrementalCache:\n | import('../../lib/incremental-cache').IncrementalCache\n | undefined =\n workStore?.incrementalCache || (globalThis as any).__incrementalCache\n\n if (!maybeIncrementalCache) {\n throw new Error(\n `Invariant: incrementalCache missing in unstable_cache ${cb.toString()}`\n )\n }\n const incrementalCache = maybeIncrementalCache\n\n const cacheSignal = workUnitStore ? getCacheSignal(workUnitStore) : null\n if (cacheSignal) {\n cacheSignal.beginRead()\n }\n try {\n // If there's no request store, we aren't in a request (or we're not in\n // app router) and if there's no static generation store, we aren't in app\n // router. Default to an empty pathname and search params when there's no\n // request store or static generation store available.\n const fetchUrlPrefix =\n workStore && workUnitStore\n ? getFetchUrlPrefix(workStore, workUnitStore)\n : ''\n\n // Construct the complete cache key for this function invocation\n // @TODO stringify is likely not safe here. We will coerce undefined to null which will make\n // the keyspace smaller than the execution space\n const invocationKey = `${fixedKey}-${JSON.stringify(args)}`\n const cacheKey =\n await incrementalCache.generateSimpleCacheKey(invocationKey)\n // $urlWithPath,$sortedQueryStringKeys,$hashOfEveryThingElse\n //\n // A cache implementation may serialize this name into an HTTP request\n // header, so it is encoded here. Both parts can carry a character above\n // U+00FF: the search parameters are decoded, and a JavaScript identifier\n // may hold one. The character class leaves the separating spaces and the\n // URL punctuation untouched, so the shape above is preserved.\n //\n // `toWellFormed` replaces lone surrogates, which `cb.name` can hold and\n // which `encodeURIComponent` rejects. The name identifies the call for\n // debug metrics, so a replacement character is an acceptable trade for\n // not failing the render.\n const fetchUrl = encodeHeaderSafe(\n `unstable_cache ${fetchUrlPrefix} ${cb.name ? ` ${cb.name}` : cacheKey}`.toWellFormed()\n )\n const fetchIdx =\n (workStore ? workStore.nextFetchId : noStoreFetchIdx) ?? 1\n\n const implicitTags = workUnitStore?.implicitTags\n\n const innerCacheStore: UnstableCacheStore = {\n type: 'unstable-cache',\n phase: 'render',\n consumerWillServerCache: true,\n implicitTags,\n draftMode:\n workUnitStore &&\n workStore &&\n getDraftModeProviderForCacheScope(workStore, workUnitStore),\n rootParams: undefined,\n }\n\n if (workStore) {\n workStore.nextFetchId = fetchIdx + 1\n\n // We are in an App Router context. We try to return the cached entry if it exists and is valid\n // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in\n // the background. If the entry is missing or invalid we generate a new entry and return it.\n\n let isNestedUnstableCache = false\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n // We update the store's revalidate property if the revalidate option is a higher precedence\n // revalidate === undefined doesn't affect timing.\n // revalidate === INFINITE_CACHE (from `false` or `Infinity`) doesn't shrink timing. it stays at the maximum.\n if (typeof revalidate === 'number') {\n if (workUnitStore.revalidate < revalidate) {\n // The store is already revalidating on a shorter time interval, leave it alone\n } else {\n workUnitStore.revalidate = revalidate\n }\n }\n\n // We need to accumulate the tags for this invocation within the store\n const collectedTags = workUnitStore.tags\n if (collectedTags === null) {\n workUnitStore.tags = tags.slice()\n } else {\n for (const tag of tags) {\n // @TODO refactor tags to be a set to avoid this O(n) lookup\n if (!collectedTags.includes(tag)) {\n collectedTags.push(tag)\n }\n }\n }\n break\n case 'unstable-cache':\n isNestedUnstableCache = true\n break\n case 'prerender-client':\n case 'validation-client':\n case 'request':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (\n // when we are nested inside of other unstable_cache's\n // we should bypass cache similar to fetches\n !isNestedUnstableCache &&\n workStore.fetchCache !== 'force-no-store' &&\n !workStore.isOnDemandRevalidate &&\n !incrementalCache.isOnDemandRevalidate &&\n !workStore.isDraftMode\n ) {\n // We attempt to get the current cache entry from the incremental cache.\n const cacheEntry = await incrementalCache.get(cacheKey, {\n kind: IncrementalCacheKind.FETCH,\n revalidate,\n tags,\n softTags: implicitTags?.tags,\n fetchIdx,\n fetchUrl,\n })\n\n if (cacheEntry && cacheEntry.value) {\n // The entry exists and has a value\n if (cacheEntry.value.kind !== CachedRouteKind.FETCH) {\n // The entry is invalid and we need a special warning\n // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced\n // so bugs can be reported\n // @TODO the invocation key can have sensitive data in it. we should not log this entire object\n console.error(\n `Invariant invalid cacheEntry returned for ${invocationKey}`\n )\n // will fall through to generating a new cache entry below\n } else {\n // We have a valid cache entry so we will be returning it. We also check to see if we need\n // to background revalidate it by checking if it is stale.\n const cachedResponse =\n cacheEntry.value.data.body !== undefined\n ? JSON.parse(cacheEntry.value.data.body)\n : undefined\n\n if (cacheEntry.isStale) {\n if (!workStore.pendingRevalidates) {\n workStore.pendingRevalidates = {}\n }\n\n // Check if there's already a pending revalidation to avoid duplicate work\n if (!workStore.pendingRevalidates[invocationKey]) {\n // Create the revalidation promise\n const revalidationPromise = workUnitAsyncStorage\n .run(innerCacheStore, cb, ...args)\n .then(async (result) => {\n await cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n return result\n })\n .catch((err) => {\n // @TODO This error handling seems wrong. We swallow the error?\n console.error(\n `revalidating cache with key: ${invocationKey}`,\n err\n )\n // Return the stale value on error for foreground revalidation\n return cachedResponse\n })\n\n // Attach the empty catch here so we don't get a \"unhandled promise\n // rejection\" warning. (Behavior is matched with patch-fetch)\n if (willConsumerServerCache(workUnitStore)) {\n revalidationPromise.catch(() => {})\n }\n\n workStore.pendingRevalidates[invocationKey] =\n revalidationPromise\n }\n\n // Check if we need to do foreground revalidation\n if (willConsumerServerCache(workUnitStore)) {\n // When the consumer will persist this result in a server\n // cache, wait for fresh data so it doesn't persist a stale\n // value. The `await` here also keeps `cacheSignal.endRead` (in\n // the outer `finally`) suspended until the recompute +\n // cacheNewResult actually complete, so a prospective\n // prerender's `cacheSignal` doesn't resolve `cacheReady`\n // prematurely.\n return await workStore.pendingRevalidates[invocationKey]\n }\n // Otherwise, we're doing background revalidation - return stale immediately\n }\n\n // We had a valid cache entry so we return it here\n return cachedResponse\n }\n }\n }\n\n // If we got this far then we had an invalid cache entry and need to generate a new one\n const result = await workUnitAsyncStorage.run(\n innerCacheStore,\n cb,\n ...args\n )\n\n if (!workStore.isDraftMode) {\n if (!workStore.pendingRevalidates) {\n workStore.pendingRevalidates = {}\n }\n\n // We need to push the cache result promise to pending\n // revalidates otherwise it won't be awaited and is just\n // dangling\n workStore.pendingRevalidates[invocationKey] = cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n }\n\n return result\n } else {\n noStoreFetchIdx += 1\n // We are in Pages Router or were called outside of a render. We don't have a store\n // so we just call the callback directly when it needs to run.\n // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in\n // the background. If the entry is missing or invalid we generate a new entry and return it.\n\n if (!incrementalCache.isOnDemandRevalidate) {\n // We aren't doing an on demand revalidation so we check use the cache if valid\n const cacheEntry = await incrementalCache.get(cacheKey, {\n kind: IncrementalCacheKind.FETCH,\n revalidate,\n tags,\n fetchIdx,\n fetchUrl,\n softTags: implicitTags?.tags,\n })\n\n if (cacheEntry && cacheEntry.value) {\n // The entry exists and has a value\n if (cacheEntry.value.kind !== CachedRouteKind.FETCH) {\n // The entry is invalid and we need a special warning\n // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced\n // so bugs can be reported\n console.error(\n `Invariant invalid cacheEntry returned for ${invocationKey}`\n )\n // will fall through to generating a new cache entry below\n } else if (!cacheEntry.isStale) {\n // We have a valid cache entry and it is fresh so we return it\n return cacheEntry.value.data.body !== undefined\n ? JSON.parse(cacheEntry.value.data.body)\n : undefined\n }\n }\n }\n\n // If we got this far then we had an invalid cache entry and need to generate a new one\n const result = await workUnitAsyncStorage.run(\n innerCacheStore,\n cb,\n ...args\n )\n\n // we need to wait setting the new cache result here as\n // we don't have pending revalidates on workStore to\n // push to and we can't have a dangling promise\n await cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n return result\n }\n } finally {\n if (cacheSignal) {\n cacheSignal.endRead()\n }\n }\n }\n // TODO: once AsyncLocalStorage.run() returns the correct types this override will no longer be necessary\n return cachedCb as unknown as T\n}\n\nfunction getFetchUrlPrefix(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): string {\n switch (workUnitStore.type) {\n case 'request':\n const pathname = workUnitStore.url.pathname\n const searchParams = new URLSearchParams(workUnitStore.url.search)\n\n const sortedSearch = [...searchParams.keys()]\n .sort((a, b) => a.localeCompare(b))\n .map((key) => `${key}=${searchParams.get(key)}`)\n .join('&')\n\n return `${pathname}${sortedSearch.length ? '?' : ''}${sortedSearch}`\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return workStore.route\n default:\n return workUnitStore satisfies never\n }\n}\n"],"names":["CACHE_ONE_YEAR_SECONDS","validateRevalidate","validateTags","encodeHeaderSafe","workAsyncStorage","getCacheSignal","getDraftModeProviderForCacheScope","willConsumerServerCache","workUnitAsyncStorage","CachedRouteKind","IncrementalCacheKind","noStoreFetchIdx","cacheNewResult","result","incrementalCache","cacheKey","tags","revalidate","fetchIdx","fetchUrl","set","kind","FETCH","data","headers","body","JSON","stringify","status","url","fetchCache","unstable_cache","cb","keyParts","options","Error","toString","name","fixedKey","Array","isArray","join","cachedCb","args","workStore","getStore","workUnitStore","maybeIncrementalCache","globalThis","__incrementalCache","cacheSignal","beginRead","fetchUrlPrefix","getFetchUrlPrefix","invocationKey","generateSimpleCacheKey","toWellFormed","nextFetchId","implicitTags","innerCacheStore","type","phase","consumerWillServerCache","draftMode","rootParams","undefined","isNestedUnstableCache","collectedTags","slice","tag","includes","push","isOnDemandRevalidate","isDraftMode","cacheEntry","get","softTags","value","console","error","cachedResponse","parse","isStale","pendingRevalidates","revalidationPromise","run","then","catch","err","endRead","pathname","searchParams","URLSearchParams","search","sortedSearch","keys","sort","a","b","localeCompare","map","key","length","route"],"mappings":"AAEA,SAASA,sBAAsB,QAAQ,yBAAwB;AAC/D,SAASC,kBAAkB,EAAEC,YAAY,QAAQ,wBAAuB;AACxE,SAASC,gBAAgB,QAAQ,+BAA8B;AAC/D,SACEC,gBAAgB,QAEX,+CAA8C;AACrD,SACEC,cAAc,EACdC,iCAAiC,EACjCC,uBAAuB,EACvBC,oBAAoB,QACf,oDAAmD;AAC1D,SACEC,eAAe,EACfC,oBAAoB,QAEf,uBAAsB;AAQ7B,IAAIC,kBAAkB;AAEtB,eAAeC,eACbC,MAAS,EACTC,gBAAkC,EAClCC,QAAgB,EAChBC,IAAc,EACdC,UAAsC,EACtCC,QAAgB,EAChBC,QAAgB;IAEhB,MAAML,iBAAiBM,GAAG,CACxBL,UACA;QACEM,MAAMZ,gBAAgBa,KAAK;QAC3BC,MAAM;YACJC,SAAS,CAAC;YACV,gCAAgC;YAChCC,MAAMC,KAAKC,SAAS,CAACd;YACrBe,QAAQ;YACRC,KAAK;QACP;QACAZ,YACE,OAAOA,eAAe,WAAWjB,yBAAyBiB;IAC9D,GACA;QAAEa,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gBACvD,oDAAoD;gBACpD,+CAA+C;gBAC/C,MAAM/B,eACJC,QACAC,kBACAC,UACAC,MACAC,YACAC,UACAC;gBAEF,OAAON;YACT;QACF,SAAU;YACR,IAAIqC,aAAa;gBACfA,YAAYuC,OAAO;YACrB;QACF;IACF;IACA,yGAAyG;IACzG,OAAO/C;AACT;AAEA,SAASW,kBACPT,SAAoB,EACpBE,aAA4B;IAE5B,OAAQA,cAAcc,IAAI;QACxB,KAAK;YACH,MAAM8B,WAAW5C,cAAcjB,GAAG,CAAC6D,QAAQ;YAC3C,MAAMC,eAAe,IAAIC,gBAAgB9C,cAAcjB,GAAG,CAACgE,MAAM;YAEjE,MAAMC,eAAe;mBAAIH,aAAaI,IAAI;aAAG,CAC1CC,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAEE,aAAa,CAACD,IAC/BE,GAAG,CAAC,CAACC,MAAQ,GAAGA,IAAI,CAAC,EAAEV,aAAahB,GAAG,CAAC0B,MAAM,EAC9C5D,IAAI,CAAC;YAER,OAAO,GAAGiD,WAAWI,aAAaQ,MAAM,GAAG,MAAM,KAAKR,cAAc;QACtE,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOlD,UAAU2D,KAAK;QACxB;YACE,OAAOzD;IACX;AACF","ignoreList":[0]} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/shared/lib/app-router-context.shared-runtime.ts"],"sourcesContent":["'use client'\n\nimport type {\n FocusAndScrollRef,\n PrefetchKind,\n} from '../../client/components/router-reducer/router-reducer-types'\nimport type { Params } from '../../server/request/params'\nimport type {\n FlightRouterState,\n FlightSegmentPath,\n CacheNode,\n LoadingModuleData,\n} from './app-router-types'\nimport React from 'react'\n\nexport interface NavigateOptions {\n scroll?: boolean\n /**\n * Transition types to apply when navigating. These types are passed to\n * [`React.addTransitionType`](https://react.dev/reference/react/addTransitionType)\n * inside the navigation transition, enabling\n * [`<ViewTransition>`](https://react.dev/reference/react/ViewTransition) components\n * to apply different animations based on the type of navigation.\n */\n transitionTypes?: string[]\n}\n\nexport interface PrefetchOptions {\n kind: PrefetchKind\n onInvalidate?: () => void\n}\n\nexport interface AppRouterInstance {\n /**\n * Navigate to the previous history entry.\n */\n back(): void\n /**\n * Navigate to the next history entry.\n */\n forward(): void\n /**\n * Refresh the current page.\n */\n refresh(): void\n /**\n * Refresh the current page. Use in development only.\n * @internal\n */\n hmrRefresh(): void\n /**\n * Navigate to the provided href.\n * Pushes a new history entry.\n */\n push(href: string, options?: NavigateOptions): void\n /**\n * Navigate to the provided href.\n * Replaces the current history entry.\n */\n replace(href: string, options?: NavigateOptions): void\n /**\n * Prefetch the provided href.\n */\n prefetch(href: string, options?: PrefetchOptions): void\n /**\n * Perform a gesture navigation using prefetched data.\n * Only available when experimental.gestureTransition is enabled.\n * @experimental\n */\n experimental_gesturePush?(href: string, options?: NavigateOptions): void\n /**\n * An opaque string identifier scoped to the current route segment.\n *\n * Changes when the surrounding segment is freshly created by a push or\n * replace navigation. Stays the same for back/forward navigations,\n * `router.refresh()`, and search-param/hash-only changes.\n *\n * Intended to be passed to a React `key` to opt out of state preservation\n * on fresh navigations:\n *\n * ```tsx\n * <form key={useRouter().bfcacheId}>\n * ```\n *\n * In most cases, prefer resetting state explicitly in an event handler, or\n * deriving a key from your data (e.g. a draft id from the server). Use\n * `bfcacheId` only when those patterns aren't a fit.\n */\n bfcacheId: string\n}\n\nexport const AppRouterContext = React.createContext<AppRouterInstance | null>(\n null\n)\nexport const LayoutRouterContext = React.createContext<{\n parentTree: FlightRouterState\n parentCacheNode: CacheNode\n parentSegmentPath: FlightSegmentPath | null\n parentParams: Params\n parentLoadingData: LoadingModuleData | null\n debugNameContext: string\n url: string\n isActive: boolean\n} | null>(null)\n\nexport const GlobalLayoutRouterContext = React.createContext<{\n tree: FlightRouterState\n focusAndScrollRef: FocusAndScrollRef\n nextUrl: string | null\n previousNextUrl: string | null\n}>(null as any)\n\nexport const TemplateContext = React.createContext<React.ReactNode>(null as any)\n\nif (process.env.NODE_ENV !== 'production') {\n AppRouterContext.displayName = 'AppRouterContext'\n LayoutRouterContext.displayName = 'LayoutRouterContext'\n GlobalLayoutRouterContext.displayName = 'GlobalLayoutRouterContext'\n TemplateContext.displayName = 'TemplateContext'\n}\n\nexport const MissingSlotContext = React.createContext<Set<string>>(new Set())\n"],"names":["React","AppRouterContext","createContext","LayoutRouterContext","GlobalLayoutRouterContext","TemplateContext","process","env","NODE_ENV","displayName","MissingSlotContext","Set"],"mappings":"AAAA;AAaA,OAAOA,WAAW,QAAO;AA8EzB,OAAO,MAAMC,mBAAmBD,MAAME,aAAa,CACjD,MACD;AACD,OAAO,MAAMC,sBAAsBH,MAAME,aAAa,CAS5C,MAAK;AAEf,OAAO,MAAME,4BAA4BJ,MAAME,aAAa,CAKzD,MAAY;AAEf,OAAO,MAAMG,kBAAkBL,MAAME,aAAa,CAAkB,MAAY;AAEhF,IAAII,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;IACzCP,iBAAiBQ,WAAW,GAAG;IAC/BN,oBAAoBM,WAAW,GAAG;IAClCL,0BAA0BK,WAAW,GAAG;IACxCJ,gBAAgBI,WAAW,GAAG;AAChC;AAEA,OAAO,MAAMC,qBAAqBV,MAAME,aAAa,CAAc,IAAIS,OAAM","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/shared/lib/app-router-context.shared-runtime.ts"],"sourcesContent":["'use client'\n\nimport type {\n ScrollHandlerRef,\n PrefetchKind,\n} from '../../client/components/router-reducer/router-reducer-types'\nimport type { Params } from '../../server/request/params'\nimport type {\n FlightRouterState,\n FlightSegmentPath,\n CacheNode,\n LoadingModuleData,\n} from './app-router-types'\nimport React from 'react'\n\nexport interface NavigateOptions {\n scroll?: boolean\n /**\n * Transition types to apply when navigating. These types are passed to\n * [`React.addTransitionType`](https://react.dev/reference/react/addTransitionType)\n * inside the navigation transition, enabling\n * [`<ViewTransition>`](https://react.dev/reference/react/ViewTransition) components\n * to apply different animations based on the type of navigation.\n */\n transitionTypes?: string[]\n}\n\nexport interface PrefetchOptions {\n kind: PrefetchKind\n onInvalidate?: () => void\n}\n\nexport interface AppRouterInstance {\n /**\n * Navigate to the previous history entry.\n */\n back(): void\n /**\n * Navigate to the next history entry.\n */\n forward(): void\n /**\n * Refresh the current page.\n */\n refresh(): void\n /**\n * Refresh the current page. Use in development only.\n * @internal\n */\n hmrRefresh(): void\n /**\n * Navigate to the provided href.\n * Pushes a new history entry.\n */\n push(href: string, options?: NavigateOptions): void\n /**\n * Navigate to the provided href.\n * Replaces the current history entry.\n */\n replace(href: string, options?: NavigateOptions): void\n /**\n * Prefetch the provided href.\n */\n prefetch(href: string, options?: PrefetchOptions): void\n /**\n * Perform a gesture navigation using prefetched data.\n * Only available when experimental.gestureTransition is enabled.\n * @experimental\n */\n experimental_gesturePush?(href: string, options?: NavigateOptions): void\n /**\n * An opaque string identifier scoped to the current route segment.\n *\n * Changes when the surrounding segment is freshly created by a push or\n * replace navigation. Stays the same for back/forward navigations,\n * `router.refresh()`, and search-param/hash-only changes.\n *\n * Intended to be passed to a React `key` to opt out of state preservation\n * on fresh navigations:\n *\n * ```tsx\n * <form key={useRouter().bfcacheId}>\n * ```\n *\n * In most cases, prefer resetting state explicitly in an event handler, or\n * deriving a key from your data (e.g. a draft id from the server). Use\n * `bfcacheId` only when those patterns aren't a fit.\n */\n bfcacheId: string\n}\n\nexport const AppRouterContext = React.createContext<AppRouterInstance | null>(\n null\n)\nexport const LayoutRouterContext = React.createContext<{\n parentTree: FlightRouterState\n parentCacheNode: CacheNode\n parentSegmentPath: FlightSegmentPath | null\n parentParams: Params\n parentLoadingData: LoadingModuleData | null\n debugNameContext: string\n url: string\n isActive: boolean\n} | null>(null)\n\nexport const GlobalLayoutRouterContext = React.createContext<{\n tree: FlightRouterState\n scrollRef: ScrollHandlerRef\n nextUrl: string | null\n previousNextUrl: string | null\n}>(null as any)\n\nexport const TemplateContext = React.createContext<React.ReactNode>(null as any)\n\nif (process.env.NODE_ENV !== 'production') {\n AppRouterContext.displayName = 'AppRouterContext'\n LayoutRouterContext.displayName = 'LayoutRouterContext'\n GlobalLayoutRouterContext.displayName = 'GlobalLayoutRouterContext'\n TemplateContext.displayName = 'TemplateContext'\n}\n\nexport const MissingSlotContext = React.createContext<Set<string>>(new Set())\n"],"names":["React","AppRouterContext","createContext","LayoutRouterContext","GlobalLayoutRouterContext","TemplateContext","process","env","NODE_ENV","displayName","MissingSlotContext","Set"],"mappings":"AAAA;AAaA,OAAOA,WAAW,QAAO;AA8EzB,OAAO,MAAMC,mBAAmBD,MAAME,aAAa,CACjD,MACD;AACD,OAAO,MAAMC,sBAAsBH,MAAME,aAAa,CAS5C,MAAK;AAEf,OAAO,MAAME,4BAA4BJ,MAAME,aAAa,CAKzD,MAAY;AAEf,OAAO,MAAMG,kBAAkBL,MAAME,aAAa,CAAkB,MAAY;AAEhF,IAAII,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;IACzCP,iBAAiBQ,WAAW,GAAG;IAC/BN,oBAAoBM,WAAW,GAAG;IAClCL,0BAA0BK,WAAW,GAAG;IACxCJ,gBAAgBI,WAAW,GAAG;AAChC;AAEA,OAAO,MAAMC,qBAAqBV,MAAME,aAAa,CAAc,IAAIS,OAAM","ignoreList":[0]} |
| export function isStableBuild() { | ||
| return !"16.3.1-canary.10"?.includes('canary') && !process.env.__NEXT_TEST_MODE && !process.env.NEXT_PRIVATE_LOCAL_DEV; | ||
| return !"16.3.1-canary.11"?.includes('canary') && !process.env.__NEXT_TEST_MODE && !process.env.NEXT_PRIVATE_LOCAL_DEV; | ||
| } | ||
@@ -4,0 +4,0 @@ export class CanaryOnlyConfigError extends Error { |
@@ -456,3 +456,3 @@ import { APP_PATHS_MANIFEST, BUILD_MANIFEST, CLIENT_STATIC_FILES_PATH, INTERCEPTION_ROUTE_REWRITE_MANIFEST, MIDDLEWARE_BUILD_MANIFEST, MIDDLEWARE_MANIFEST, NEXT_FONT_MANIFEST, PAGES_MANIFEST, SERVER_REFERENCE_MANIFEST, SUBRESOURCE_INTEGRITY_MANIFEST, TURBOPACK_CLIENT_BUILD_MANIFEST, TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST } from '../constants'; | ||
| // Client middleware manifest This is only used in dev though, packages/next/src/build/index.ts | ||
| // writes the mainfest again for builds. | ||
| // writes the manifest again for builds. | ||
| const matchers = middlewareManifest?.middleware['/']?.matchers || []; | ||
@@ -459,0 +459,0 @@ const clientMiddlewareManifestJs = `self.__MIDDLEWARE_MATCHERS = ${JSON.stringify(matchers, null, 2)};self.__MIDDLEWARE_MATCHERS_CB && self.__MIDDLEWARE_MATCHERS_CB()`; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/shared/lib/turbopack/manifest-loader.ts"],"sourcesContent":["import type {\n EdgeFunctionDefinition,\n MiddlewareManifest,\n} from '../../../build/webpack/plugins/middleware-plugin'\nimport type { BuildManifest } from '../../../server/get-page-files'\nimport type { PagesManifest } from '../../../build/webpack/plugins/pages-manifest-plugin'\nimport type { ActionManifest } from '../../../build/webpack/plugins/flight-client-entry-plugin'\nimport type { NextFontManifest } from '../../../build/webpack/plugins/next-font-manifest-plugin'\nimport type { REACT_LOADABLE_MANIFEST } from '../constants'\nimport {\n APP_PATHS_MANIFEST,\n BUILD_MANIFEST,\n CLIENT_STATIC_FILES_PATH,\n INTERCEPTION_ROUTE_REWRITE_MANIFEST,\n MIDDLEWARE_BUILD_MANIFEST,\n MIDDLEWARE_MANIFEST,\n NEXT_FONT_MANIFEST,\n PAGES_MANIFEST,\n SERVER_REFERENCE_MANIFEST,\n SUBRESOURCE_INTEGRITY_MANIFEST,\n TURBOPACK_CLIENT_BUILD_MANIFEST,\n TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST,\n} from '../constants'\nimport { join, posix } from 'path'\nimport { readFileSync } from 'fs'\nimport type { SetupOpts } from '../../../server/lib/router-utils/setup-dev-bundler'\nimport { deleteCache } from '../../../server/dev/require-cache'\nimport { writeFileAtomic } from '../../../lib/fs/write-atomic'\nimport getAssetPathFromRoute from '../router/utils/get-asset-path-from-route'\nimport { getEntryKey, splitEntryKey, type EntryKey } from './entry-key'\nimport type { CustomRoutes } from '../../../lib/load-custom-routes'\nimport { getSortedRoutes } from '../router/utils'\nimport { existsSync } from 'fs'\nimport {\n addMetadataIdToRoute,\n addRouteSuffix,\n removeRouteSuffix,\n} from '../../../server/dev/turbopack-utils'\nimport { tryToParsePath } from '../../../lib/try-to-parse-path'\nimport { safePathToRegexp } from '../router/utils/route-match-utils'\nimport type { Entrypoints } from '../../../build/swc/types'\nimport {\n normalizeRewritesForBuildManifest,\n type ClientBuildManifest,\n srcEmptySsgManifest,\n processRoute,\n createEdgeRuntimeManifest,\n} from '../../../build/webpack/plugins/build-manifest-plugin-utils'\nimport type { SubresourceIntegrityManifest } from '../../../build'\n\ninterface InstrumentationDefinition {\n files: string[]\n name: 'instrumentation'\n}\n\ntype TurbopackMiddlewareManifest = MiddlewareManifest & {\n instrumentation?: InstrumentationDefinition\n}\n\ntype ManifestName =\n | typeof MIDDLEWARE_MANIFEST\n | typeof BUILD_MANIFEST\n | typeof PAGES_MANIFEST\n | typeof APP_PATHS_MANIFEST\n | `${typeof SERVER_REFERENCE_MANIFEST}.json`\n | `${typeof SUBRESOURCE_INTEGRITY_MANIFEST}.json`\n | `${typeof NEXT_FONT_MANIFEST}.json`\n | typeof REACT_LOADABLE_MANIFEST\n | typeof TURBOPACK_CLIENT_BUILD_MANIFEST\n\nconst getManifestPath = (\n page: string,\n distDir: string,\n name: ManifestName,\n type: string,\n firstCall: boolean\n) => {\n let manifestPath = posix.join(\n distDir,\n `server`,\n type,\n type === 'middleware' || type === 'instrumentation'\n ? ''\n : type === 'app'\n ? page\n : getAssetPathFromRoute(page),\n name\n )\n\n if (firstCall) {\n const isSitemapRoute = /[\\\\/]sitemap(.xml)?\\/route$/.test(page)\n // Check the ambiguity of /sitemap and /sitemap.xml\n if (isSitemapRoute && !existsSync(manifestPath)) {\n manifestPath = getManifestPath(\n page.replace(/\\/sitemap\\/route$/, '/sitemap.xml/route'),\n distDir,\n name,\n type,\n false\n )\n }\n // existsSync is faster than using the async version\n if (!existsSync(manifestPath) && page.endsWith('/route')) {\n // TODO: Improve implementation of metadata routes, currently it requires this extra check for the variants of the files that can be written.\n let basePage = removeRouteSuffix(page)\n // For sitemap.xml routes with generateSitemaps, the manifest is at\n // /sitemap/[__metadata_id__]/route (without .xml), because the route\n // handler serves at /sitemap/[id] not /sitemap.xml/[id]\n if (basePage.endsWith('/sitemap.xml')) {\n basePage = basePage.slice(0, -'.xml'.length)\n }\n let metadataPage = addRouteSuffix(addMetadataIdToRoute(basePage))\n manifestPath = getManifestPath(metadataPage, distDir, name, type, false)\n }\n }\n\n return manifestPath\n}\n\nfunction readPartialManifestContent(\n distDir: string,\n name: ManifestName,\n pageName: string,\n type: 'pages' | 'app' | 'middleware' | 'instrumentation' = 'pages'\n): string {\n const page = pageName\n const manifestPath = getManifestPath(page, distDir, name, type, true)\n return readFileSync(posix.join(manifestPath), 'utf-8')\n}\n\n/// Helper class that stores a map of manifests and tracks if they have changed\n/// since the last time they were written to disk. This is used to avoid\n/// unnecessary writes to disk.\nclass ManifestsMap<K, V> {\n private rawMap = new Map<K, string>()\n private map = new Map<K, V>()\n private extraInvalidationKey: string | undefined = undefined\n private changed = true\n\n set(key: K, value: string) {\n if (this.rawMap.get(key) === value) return\n this.changed = true\n this.rawMap.set(key, value)\n this.map.set(key, JSON.parse(value))\n }\n\n delete(key: K) {\n if (this.map.has(key)) {\n this.changed = true\n this.rawMap.delete(key)\n this.map.delete(key)\n }\n }\n\n get(key: K) {\n return this.map.get(key)\n }\n\n takeChanged(extraInvalidationKey?: any) {\n let changed = this.changed\n if (extraInvalidationKey !== undefined) {\n const stringified = JSON.stringify(extraInvalidationKey)\n if (this.extraInvalidationKey !== stringified) {\n this.extraInvalidationKey = stringified\n changed = true\n }\n }\n this.changed = false\n return changed\n }\n\n values() {\n return this.map.values()\n }\n\n entries() {\n return this.map.entries()\n }\n}\n\nexport class TurbopackManifestLoader {\n private actionManifests: ManifestsMap<EntryKey, ActionManifest> =\n new ManifestsMap()\n private appPathsManifests: ManifestsMap<EntryKey, PagesManifest> =\n new ManifestsMap()\n private buildManifests: ManifestsMap<EntryKey, BuildManifest> =\n new ManifestsMap()\n private clientBuildManifests: ManifestsMap<EntryKey, ClientBuildManifest> =\n new ManifestsMap()\n private fontManifests: ManifestsMap<EntryKey, NextFontManifest> =\n new ManifestsMap()\n private middlewareManifests: ManifestsMap<\n EntryKey,\n TurbopackMiddlewareManifest\n > = new ManifestsMap()\n private pagesManifests: ManifestsMap<string, PagesManifest> =\n new ManifestsMap()\n private sriManifests: ManifestsMap<EntryKey, SubresourceIntegrityManifest> =\n new ManifestsMap()\n private encryptionKey: string\n /// interceptionRewrites that have been written to disk\n /// This is used to avoid unnecessary writes if the rewrites haven't changed\n private cachedInterceptionRewrites: string | undefined = undefined\n private pendingCacheDeletes: string[] = []\n\n private readonly distDir: string\n private readonly buildId: string\n private readonly dev: boolean\n private readonly sriEnabled: boolean\n\n constructor({\n distDir,\n buildId,\n encryptionKey,\n dev,\n sriEnabled,\n }: {\n buildId: string\n distDir: string\n encryptionKey: string\n dev: boolean\n sriEnabled: boolean\n }) {\n this.distDir = distDir\n this.buildId = buildId\n this.encryptionKey = encryptionKey\n this.dev = dev\n this.sriEnabled = sriEnabled\n }\n\n delete(key: EntryKey) {\n this.actionManifests.delete(key)\n this.appPathsManifests.delete(key)\n this.buildManifests.delete(key)\n this.clientBuildManifests.delete(key)\n this.fontManifests.delete(key)\n this.middlewareManifests.delete(key)\n this.pagesManifests.delete(key)\n }\n\n loadActionManifest(pageName: string): void {\n this.actionManifests.set(\n getEntryKey('app', 'server', pageName),\n readPartialManifestContent(\n this.distDir,\n `${SERVER_REFERENCE_MANIFEST}.json`,\n pageName,\n 'app'\n )\n )\n }\n\n private mergeActionManifests(manifests: Iterable<ActionManifest>) {\n type ActionEntries = ActionManifest['edge' | 'node']\n const manifest: ActionManifest = {\n node: {},\n edge: {},\n encryptionKey: this.encryptionKey,\n }\n\n function mergeActionIds(\n actionEntries: ActionEntries,\n other: ActionEntries\n ): void {\n for (const key in other) {\n const action = (actionEntries[key] ??= {\n workers: {},\n })\n action.filename = other[key].filename\n action.exportedName = other[key].exportedName\n Object.assign(action.workers, other[key].workers)\n }\n }\n\n for (const m of manifests) {\n mergeActionIds(manifest.node, m.node)\n mergeActionIds(manifest.edge, m.edge)\n }\n for (const key in manifest.node) {\n const entry = manifest.node[key]\n entry.workers = sortObjectByKey(entry.workers)\n }\n for (const key in manifest.edge) {\n const entry = manifest.edge[key]\n entry.workers = sortObjectByKey(entry.workers)\n }\n\n return manifest\n }\n\n private writeActionManifest(): void {\n if (!this.actionManifests.takeChanged()) {\n return\n }\n const actionManifest = this.mergeActionManifests(\n this.actionManifests.values()\n )\n const actionManifestJsonPath = join(\n this.distDir,\n 'server',\n `${SERVER_REFERENCE_MANIFEST}.json`\n )\n const actionManifestJsPath = join(\n this.distDir,\n 'server',\n `${SERVER_REFERENCE_MANIFEST}.js`\n )\n const json = JSON.stringify(actionManifest, null, 2)\n this.pendingCacheDeletes.push(actionManifestJsonPath)\n this.pendingCacheDeletes.push(actionManifestJsPath)\n writeFileAtomic(actionManifestJsonPath, json)\n writeFileAtomic(\n actionManifestJsPath,\n `self.__RSC_SERVER_MANIFEST=${JSON.stringify(json)}`\n )\n }\n\n loadAppPathsManifest(pageName: string): void {\n this.appPathsManifests.set(\n getEntryKey('app', 'server', pageName),\n readPartialManifestContent(\n this.distDir,\n APP_PATHS_MANIFEST,\n pageName,\n 'app'\n )\n )\n }\n\n private writeAppPathsManifest(): void {\n if (!this.appPathsManifests.takeChanged()) {\n return\n }\n const appPathsManifest = this.mergePagesManifests(\n this.appPathsManifests.values()\n )\n const appPathsManifestPath = join(\n this.distDir,\n 'server',\n APP_PATHS_MANIFEST\n )\n this.pendingCacheDeletes.push(appPathsManifestPath)\n writeFileAtomic(\n appPathsManifestPath,\n JSON.stringify(appPathsManifest, null, 2)\n )\n }\n\n private writeSriManifest(): void {\n if (!this.sriEnabled || !this.sriManifests.takeChanged()) {\n return\n }\n const sriManifest = this.mergeSriManifests(this.sriManifests.values())\n const pathJson = join(\n this.distDir,\n 'server',\n `${SUBRESOURCE_INTEGRITY_MANIFEST}.json`\n )\n const pathJs = join(\n this.distDir,\n 'server',\n `${SUBRESOURCE_INTEGRITY_MANIFEST}.js`\n )\n this.pendingCacheDeletes.push(pathJson)\n this.pendingCacheDeletes.push(pathJs)\n writeFileAtomic(pathJson, JSON.stringify(sriManifest, null, 2))\n writeFileAtomic(\n pathJs,\n `self.__SUBRESOURCE_INTEGRITY_MANIFEST=${JSON.stringify(\n JSON.stringify(sriManifest)\n )}`\n )\n }\n\n loadBuildManifest(pageName: string, type: 'app' | 'pages' = 'pages'): void {\n this.buildManifests.set(\n getEntryKey(type, 'server', pageName),\n readPartialManifestContent(this.distDir, BUILD_MANIFEST, pageName, type)\n )\n }\n\n loadClientBuildManifest(\n pageName: string,\n type: 'app' | 'pages' = 'pages'\n ): void {\n this.clientBuildManifests.set(\n getEntryKey(type, 'server', pageName),\n readPartialManifestContent(\n this.distDir,\n TURBOPACK_CLIENT_BUILD_MANIFEST,\n pageName,\n type\n )\n )\n }\n\n loadSriManifest(pageName: string, type: 'app' | 'pages' = 'pages'): void {\n if (!this.sriEnabled) return\n this.sriManifests.set(\n getEntryKey(type, 'client', pageName),\n readPartialManifestContent(\n this.distDir,\n `${SUBRESOURCE_INTEGRITY_MANIFEST}.json`,\n pageName,\n type\n )\n )\n }\n\n private mergeBuildManifests(\n manifests: Iterable<BuildManifest>,\n lowPriorityFiles: string[]\n ) {\n const manifest: Partial<BuildManifest> & Pick<BuildManifest, 'pages'> = {\n pages: {\n '/_app': [],\n },\n // Something in next.js depends on these to exist even for app dir rendering\n devFiles: [],\n polyfillFiles: [],\n lowPriorityFiles,\n rootMainFiles: [],\n rootMainFilesTree: {},\n pagesChunkGroupBootstrapParams: {},\n }\n for (const m of manifests) {\n Object.assign(manifest.pages, m.pages)\n if (m.rootMainFiles.length) manifest.rootMainFiles = m.rootMainFiles\n // polyfillFiles should always be the same, so we can overwrite instead of actually merging\n if (m.polyfillFiles.length) manifest.polyfillFiles = m.polyfillFiles\n if (m.rootMainFilesTree) {\n Object.assign(manifest.rootMainFilesTree!, m.rootMainFilesTree)\n }\n if (m.pagesChunkGroupBootstrapParams) {\n Object.assign(\n manifest.pagesChunkGroupBootstrapParams!,\n m.pagesChunkGroupBootstrapParams\n )\n }\n if (m.chunkLoadingGlobal)\n manifest.chunkLoadingGlobal = m.chunkLoadingGlobal\n }\n manifest.pages = sortObjectByKey(manifest.pages) as BuildManifest['pages']\n return manifest\n }\n\n private mergeClientBuildManifests(\n manifests: Iterable<ClientBuildManifest>,\n rewrites: CustomRoutes['rewrites'],\n sortedPageKeys: string[]\n ): ClientBuildManifest {\n const manifest = {\n __rewrites: rewrites as any,\n sortedPages: sortedPageKeys,\n }\n for (const m of manifests) {\n Object.assign(manifest, m)\n }\n return sortObjectByKey(manifest)\n }\n\n private writeInterceptionRouteRewriteManifest(\n devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined,\n productionRewrites: CustomRoutes['rewrites'] | undefined\n ): void {\n const rewrites = productionRewrites ?? {\n ...devRewrites,\n beforeFiles: (devRewrites?.beforeFiles ?? []).map(processRoute),\n afterFiles: (devRewrites?.afterFiles ?? []).map(processRoute),\n fallback: (devRewrites?.fallback ?? []).map(processRoute),\n }\n\n const interceptionRewrites = JSON.stringify(\n rewrites.beforeFiles.filter(\n (\n require('../../../lib/is-interception-route-rewrite') as typeof import('../../../lib/is-interception-route-rewrite')\n ).isInterceptionRouteRewrite\n )\n )\n\n if (this.cachedInterceptionRewrites === interceptionRewrites) {\n return\n }\n this.cachedInterceptionRewrites = interceptionRewrites\n\n const interceptionRewriteManifestPath = join(\n this.distDir,\n 'server',\n `${INTERCEPTION_ROUTE_REWRITE_MANIFEST}.js`\n )\n this.pendingCacheDeletes.push(interceptionRewriteManifestPath)\n\n writeFileAtomic(\n interceptionRewriteManifestPath,\n `self.__INTERCEPTION_ROUTE_REWRITE_MANIFEST=${JSON.stringify(\n interceptionRewrites\n )};`\n )\n }\n\n private writeBuildManifest(lowPriorityFiles: string[]): void {\n if (!this.buildManifests.takeChanged()) {\n return\n }\n const buildManifest = this.mergeBuildManifests(\n this.buildManifests.values(),\n lowPriorityFiles\n )\n\n const buildManifestPath = join(this.distDir, BUILD_MANIFEST)\n const middlewareBuildManifestPath = join(\n this.distDir,\n 'server',\n `${MIDDLEWARE_BUILD_MANIFEST}.js`\n )\n\n this.pendingCacheDeletes.push(buildManifestPath)\n this.pendingCacheDeletes.push(middlewareBuildManifestPath)\n writeFileAtomic(buildManifestPath, JSON.stringify(buildManifest, null, 2))\n writeFileAtomic(\n middlewareBuildManifestPath,\n createEdgeRuntimeManifest(buildManifest)\n )\n\n // Write fallback build manifest\n const fallbackBuildManifest = this.mergeBuildManifests(\n [\n this.buildManifests.get(getEntryKey('pages', 'server', '_app')),\n this.buildManifests.get(getEntryKey('pages', 'server', '_error')),\n ].filter(Boolean) as BuildManifest[],\n lowPriorityFiles\n )\n const fallbackBuildManifestPath = join(\n this.distDir,\n `fallback-${BUILD_MANIFEST}`\n )\n this.pendingCacheDeletes.push(fallbackBuildManifestPath)\n writeFileAtomic(\n fallbackBuildManifestPath,\n JSON.stringify(fallbackBuildManifest, null, 2)\n )\n }\n\n private writeClientBuildManifest(\n entrypoints: Entrypoints,\n devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined,\n productionRewrites: CustomRoutes['rewrites'] | undefined\n ): string[] {\n const rewrites = normalizeRewritesForBuildManifest(\n productionRewrites ?? {\n ...devRewrites,\n beforeFiles: (devRewrites?.beforeFiles ?? []).map(processRoute),\n afterFiles: (devRewrites?.afterFiles ?? []).map(processRoute),\n fallback: (devRewrites?.fallback ?? []).map(processRoute),\n }\n )\n\n const pagesKeys = [...entrypoints.page.keys()]\n if (entrypoints.global.app) {\n pagesKeys.push('/_app')\n }\n if (entrypoints.global.error) {\n pagesKeys.push('/_error')\n }\n\n const sortedPageKeys = getSortedRoutes(pagesKeys)\n\n let buildManifestPath = posix.join(\n CLIENT_STATIC_FILES_PATH,\n this.buildId,\n '_buildManifest.js'\n )\n let ssgManifestPath = posix.join(\n CLIENT_STATIC_FILES_PATH,\n this.buildId,\n '_ssgManifest.js'\n )\n\n if (\n this.dev &&\n !this.clientBuildManifests.takeChanged({ rewrites, sortedPageKeys })\n ) {\n return [buildManifestPath, ssgManifestPath]\n }\n\n const clientBuildManifest = this.mergeClientBuildManifests(\n this.clientBuildManifests.values(),\n rewrites,\n sortedPageKeys\n )\n\n // Expose each route's bootstrap params and the chunk-loading global to the client\n // so `route-loader` can instantiate a navigated page's entry module. The server\n // stores params as raw JSON per route.\n const pageBootstrapParams: Record<string, unknown> = {}\n let chunkLoadingGlobal: string | undefined\n for (const [key, m] of this.buildManifests.entries()) {\n // Only the pages-router `route-loader` reads `__TURBOPACK_PAGE_BOOTSTRAP`. App routes\n // navigate via flight and never use it, so skip app entries to keep `_buildManifest.js`\n // (loaded on every page) small.\n if (splitEntryKey(key).type !== 'pages') continue\n if (m.chunkLoadingGlobal) chunkLoadingGlobal = m.chunkLoadingGlobal\n for (const [route, params] of Object.entries(\n m.pagesChunkGroupBootstrapParams ?? {}\n )) {\n pageBootstrapParams[route] = params\n }\n }\n\n // Only emit the bootstrap globals when a route actually inlined its bootstrap (shared runtime\n // enabled).\n const hasBootstrapParams = Object.keys(pageBootstrapParams).length > 0\n const clientBuildManifestJs =\n `self.__BUILD_MANIFEST = ${JSON.stringify(clientBuildManifest, null, 2)};` +\n (hasBootstrapParams\n ? `self.__TURBOPACK_PAGE_BOOTSTRAP = ${JSON.stringify(pageBootstrapParams)};` +\n (chunkLoadingGlobal\n ? `self.__TURBOPACK_CHUNK_LOADING_GLOBAL = ${JSON.stringify(\n chunkLoadingGlobal\n )};`\n : '')\n : '') +\n `self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()`\n\n writeFileAtomic(\n join(this.distDir, buildManifestPath),\n clientBuildManifestJs\n )\n // This is just an empty placeholder, the actual manifest is written after prerendering in\n // packages/next/src/build/index.ts\n writeFileAtomic(join(this.distDir, ssgManifestPath), srcEmptySsgManifest)\n\n return [buildManifestPath, ssgManifestPath]\n }\n\n loadFontManifest(pageName: string, type: 'app' | 'pages' = 'pages'): void {\n this.fontManifests.set(\n getEntryKey(type, 'server', pageName),\n readPartialManifestContent(\n this.distDir,\n `${NEXT_FONT_MANIFEST}.json`,\n pageName,\n type\n )\n )\n }\n\n private mergeFontManifests(manifests: Iterable<NextFontManifest>) {\n const manifest: NextFontManifest = {\n app: {},\n appUsingSizeAdjust: false,\n pages: {},\n pagesUsingSizeAdjust: false,\n }\n for (const m of manifests) {\n Object.assign(manifest.app, m.app)\n Object.assign(manifest.pages, m.pages)\n\n manifest.appUsingSizeAdjust =\n manifest.appUsingSizeAdjust || m.appUsingSizeAdjust\n manifest.pagesUsingSizeAdjust =\n manifest.pagesUsingSizeAdjust || m.pagesUsingSizeAdjust\n }\n manifest.app = sortObjectByKey(manifest.app)\n manifest.pages = sortObjectByKey(manifest.pages)\n return manifest\n }\n\n private async writeNextFontManifest(): Promise<void> {\n if (!this.fontManifests.takeChanged()) {\n return\n }\n const fontManifest = this.mergeFontManifests(this.fontManifests.values())\n const json = JSON.stringify(fontManifest, null, 2)\n\n const fontManifestJsonPath = join(\n this.distDir,\n 'server',\n `${NEXT_FONT_MANIFEST}.json`\n )\n const fontManifestJsPath = join(\n this.distDir,\n 'server',\n `${NEXT_FONT_MANIFEST}.js`\n )\n this.pendingCacheDeletes.push(fontManifestJsonPath)\n this.pendingCacheDeletes.push(fontManifestJsPath)\n writeFileAtomic(fontManifestJsonPath, json)\n writeFileAtomic(\n fontManifestJsPath,\n `self.__NEXT_FONT_MANIFEST=${JSON.stringify(json)}`\n )\n }\n\n /**\n * @returns If the manifest was written or not\n */\n loadMiddlewareManifest(\n pageName: string,\n type: 'pages' | 'app' | 'middleware' | 'instrumentation'\n ): boolean {\n const middlewareManifestPath = getManifestPath(\n pageName,\n this.distDir,\n MIDDLEWARE_MANIFEST,\n type,\n true\n )\n\n // middlewareManifest is actually \"edge manifest\" and not all routes are edge runtime. If it is not written we skip it.\n if (!existsSync(middlewareManifestPath)) {\n return false\n }\n\n this.middlewareManifests.set(\n getEntryKey(\n type === 'middleware' || type === 'instrumentation' ? 'root' : type,\n 'server',\n pageName\n ),\n readPartialManifestContent(\n this.distDir,\n MIDDLEWARE_MANIFEST,\n pageName,\n type\n )\n )\n\n return true\n }\n\n getMiddlewareManifest(key: EntryKey) {\n return this.middlewareManifests.get(key)\n }\n\n deleteMiddlewareManifest(key: EntryKey) {\n return this.middlewareManifests.delete(key)\n }\n\n private mergeMiddlewareManifests(\n manifests: Iterable<TurbopackMiddlewareManifest>\n ): MiddlewareManifest {\n const manifest: MiddlewareManifest = {\n version: 3,\n middleware: {},\n sortedMiddleware: [],\n functions: {},\n }\n let instrumentation: InstrumentationDefinition | undefined = undefined\n for (const m of manifests) {\n Object.assign(manifest.functions, m.functions)\n Object.assign(manifest.middleware, m.middleware)\n if (m.instrumentation) {\n instrumentation = m.instrumentation\n }\n }\n manifest.functions = sortObjectByKey(manifest.functions)\n manifest.middleware = sortObjectByKey(manifest.middleware)\n const updateFunctionDefinition = (\n fun: EdgeFunctionDefinition\n ): EdgeFunctionDefinition => {\n return {\n ...fun,\n files: [...(instrumentation?.files ?? []), ...fun.files],\n }\n }\n for (const key of Object.keys(manifest.middleware)) {\n const value = manifest.middleware[key]\n manifest.middleware[key] = updateFunctionDefinition(value)\n }\n for (const key of Object.keys(manifest.functions)) {\n const value = manifest.functions[key]\n manifest.functions[key] = updateFunctionDefinition(value)\n }\n for (const fun of Object.values(manifest.functions).concat(\n Object.values(manifest.middleware)\n )) {\n for (const matcher of fun.matchers) {\n if (!matcher.regexp) {\n matcher.regexp = safePathToRegexp(matcher.originalSource, [], {\n delimiter: '/',\n sensitive: false,\n strict: true,\n }).source.replaceAll('\\\\/', '/')\n }\n }\n }\n manifest.sortedMiddleware = Object.keys(manifest.middleware)\n\n return manifest\n }\n\n private writeMiddlewareManifest(): {\n clientMiddlewareManifestPath: string\n } {\n let clientMiddlewareManifestPath = posix.join(\n CLIENT_STATIC_FILES_PATH,\n this.buildId,\n TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST\n )\n\n if (this.dev && !this.middlewareManifests.takeChanged()) {\n return {\n clientMiddlewareManifestPath,\n }\n }\n const middlewareManifest = this.mergeMiddlewareManifests(\n this.middlewareManifests.values()\n )\n\n // Server middleware manifest\n\n // Normalize regexes as it uses path-to-regexp\n for (const key in middlewareManifest.middleware) {\n middlewareManifest.middleware[key].matchers.forEach((matcher) => {\n if (!matcher.regexp.startsWith('^')) {\n const parsedPage = tryToParsePath(matcher.regexp)\n if (parsedPage.error || !parsedPage.regexStr) {\n throw new Error(`Invalid source: ${matcher.regexp}`)\n }\n matcher.regexp = parsedPage.regexStr\n }\n })\n }\n\n const middlewareManifestPath = join(\n this.distDir,\n 'server',\n MIDDLEWARE_MANIFEST\n )\n this.pendingCacheDeletes.push(middlewareManifestPath)\n writeFileAtomic(\n middlewareManifestPath,\n JSON.stringify(middlewareManifest, null, 2)\n )\n\n // Client middleware manifest This is only used in dev though, packages/next/src/build/index.ts\n // writes the mainfest again for builds.\n const matchers = middlewareManifest?.middleware['/']?.matchers || []\n\n const clientMiddlewareManifestJs = `self.__MIDDLEWARE_MATCHERS = ${JSON.stringify(\n matchers,\n null,\n 2\n )};self.__MIDDLEWARE_MATCHERS_CB && self.__MIDDLEWARE_MATCHERS_CB()`\n\n this.pendingCacheDeletes.push(clientMiddlewareManifestPath)\n writeFileAtomic(\n join(this.distDir, clientMiddlewareManifestPath),\n clientMiddlewareManifestJs\n )\n\n return {\n clientMiddlewareManifestPath,\n }\n }\n\n loadPagesManifest(pageName: string): void {\n this.pagesManifests.set(\n getEntryKey('pages', 'server', pageName),\n readPartialManifestContent(this.distDir, PAGES_MANIFEST, pageName)\n )\n }\n\n private mergePagesManifests(manifests: Iterable<PagesManifest>) {\n const manifest: PagesManifest = {}\n for (const m of manifests) {\n Object.assign(manifest, m)\n }\n return sortObjectByKey(manifest)\n }\n\n private mergeSriManifests(manifests: Iterable<SubresourceIntegrityManifest>) {\n const manifest: SubresourceIntegrityManifest = {}\n for (const m of manifests) {\n Object.assign(manifest, m)\n }\n return sortObjectByKey(manifest)\n }\n\n private writePagesManifest(): void {\n if (!this.pagesManifests.takeChanged()) {\n return\n }\n const pagesManifest = this.mergePagesManifests(this.pagesManifests.values())\n const pagesManifestPath = join(this.distDir, 'server', PAGES_MANIFEST)\n this.pendingCacheDeletes.push(pagesManifestPath)\n writeFileAtomic(pagesManifestPath, JSON.stringify(pagesManifest, null, 2))\n }\n\n writeManifests({\n devRewrites,\n productionRewrites,\n entrypoints,\n }: {\n devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined\n productionRewrites: CustomRoutes['rewrites'] | undefined\n entrypoints: Entrypoints\n }): void {\n this.writeActionManifest()\n this.writeAppPathsManifest()\n const lowPriorityFiles = this.writeClientBuildManifest(\n entrypoints,\n devRewrites,\n productionRewrites\n )\n const { clientMiddlewareManifestPath } = this.writeMiddlewareManifest()\n this.writeBuildManifest([...lowPriorityFiles, clientMiddlewareManifestPath])\n this.writeInterceptionRouteRewriteManifest(devRewrites, productionRewrites)\n this.writeNextFontManifest()\n this.writePagesManifest()\n\n this.writeSriManifest()\n\n // Flush all queued cache deletions in a single require.cache scan\n if (this.pendingCacheDeletes.length > 0) {\n deleteCache(this.pendingCacheDeletes)\n this.pendingCacheDeletes = []\n }\n }\n}\n\nfunction sortObjectByKey(obj: Record<string, any>) {\n return Object.keys(obj)\n .sort()\n .reduce(\n (acc, key) => {\n acc[key] = obj[key]\n return acc\n },\n {} as Record<string, any>\n )\n}\n"],"names":["APP_PATHS_MANIFEST","BUILD_MANIFEST","CLIENT_STATIC_FILES_PATH","INTERCEPTION_ROUTE_REWRITE_MANIFEST","MIDDLEWARE_BUILD_MANIFEST","MIDDLEWARE_MANIFEST","NEXT_FONT_MANIFEST","PAGES_MANIFEST","SERVER_REFERENCE_MANIFEST","SUBRESOURCE_INTEGRITY_MANIFEST","TURBOPACK_CLIENT_BUILD_MANIFEST","TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST","join","posix","readFileSync","deleteCache","writeFileAtomic","getAssetPathFromRoute","getEntryKey","splitEntryKey","getSortedRoutes","existsSync","addMetadataIdToRoute","addRouteSuffix","removeRouteSuffix","tryToParsePath","safePathToRegexp","normalizeRewritesForBuildManifest","srcEmptySsgManifest","processRoute","createEdgeRuntimeManifest","getManifestPath","page","distDir","name","type","firstCall","manifestPath","isSitemapRoute","test","replace","endsWith","basePage","slice","length","metadataPage","readPartialManifestContent","pageName","ManifestsMap","set","key","value","rawMap","get","changed","map","JSON","parse","delete","has","takeChanged","extraInvalidationKey","undefined","stringified","stringify","values","entries","Map","TurbopackManifestLoader","constructor","buildId","encryptionKey","dev","sriEnabled","actionManifests","appPathsManifests","buildManifests","clientBuildManifests","fontManifests","middlewareManifests","pagesManifests","sriManifests","cachedInterceptionRewrites","pendingCacheDeletes","loadActionManifest","mergeActionManifests","manifests","manifest","node","edge","mergeActionIds","actionEntries","other","action","workers","filename","exportedName","Object","assign","m","entry","sortObjectByKey","writeActionManifest","actionManifest","actionManifestJsonPath","actionManifestJsPath","json","push","loadAppPathsManifest","writeAppPathsManifest","appPathsManifest","mergePagesManifests","appPathsManifestPath","writeSriManifest","sriManifest","mergeSriManifests","pathJson","pathJs","loadBuildManifest","loadClientBuildManifest","loadSriManifest","mergeBuildManifests","lowPriorityFiles","pages","devFiles","polyfillFiles","rootMainFiles","rootMainFilesTree","pagesChunkGroupBootstrapParams","chunkLoadingGlobal","mergeClientBuildManifests","rewrites","sortedPageKeys","__rewrites","sortedPages","writeInterceptionRouteRewriteManifest","devRewrites","productionRewrites","beforeFiles","afterFiles","fallback","interceptionRewrites","filter","require","isInterceptionRouteRewrite","interceptionRewriteManifestPath","writeBuildManifest","buildManifest","buildManifestPath","middlewareBuildManifestPath","fallbackBuildManifest","Boolean","fallbackBuildManifestPath","writeClientBuildManifest","entrypoints","pagesKeys","keys","global","app","error","ssgManifestPath","clientBuildManifest","pageBootstrapParams","route","params","hasBootstrapParams","clientBuildManifestJs","loadFontManifest","mergeFontManifests","appUsingSizeAdjust","pagesUsingSizeAdjust","writeNextFontManifest","fontManifest","fontManifestJsonPath","fontManifestJsPath","loadMiddlewareManifest","middlewareManifestPath","getMiddlewareManifest","deleteMiddlewareManifest","mergeMiddlewareManifests","version","middleware","sortedMiddleware","functions","instrumentation","updateFunctionDefinition","fun","files","concat","matcher","matchers","regexp","originalSource","delimiter","sensitive","strict","source","replaceAll","writeMiddlewareManifest","clientMiddlewareManifestPath","middlewareManifest","forEach","startsWith","parsedPage","regexStr","Error","clientMiddlewareManifestJs","loadPagesManifest","writePagesManifest","pagesManifest","pagesManifestPath","writeManifests","obj","sort","reduce","acc"],"mappings":"AASA,SACEA,kBAAkB,EAClBC,cAAc,EACdC,wBAAwB,EACxBC,mCAAmC,EACnCC,yBAAyB,EACzBC,mBAAmB,EACnBC,kBAAkB,EAClBC,cAAc,EACdC,yBAAyB,EACzBC,8BAA8B,EAC9BC,+BAA+B,EAC/BC,oCAAoC,QAC/B,eAAc;AACrB,SAASC,IAAI,EAAEC,KAAK,QAAQ,OAAM;AAClC,SAASC,YAAY,QAAQ,KAAI;AAEjC,SAASC,WAAW,QAAQ,oCAAmC;AAC/D,SAASC,eAAe,QAAQ,+BAA8B;AAC9D,OAAOC,2BAA2B,4CAA2C;AAC7E,SAASC,WAAW,EAAEC,aAAa,QAAuB,cAAa;AAEvE,SAASC,eAAe,QAAQ,kBAAiB;AACjD,SAASC,UAAU,QAAQ,KAAI;AAC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AAmB,CAACwB,IAAI,CAACuG;QAC9BlM,gBAAgBkM,mBAAmB1J,KAAKQ,SAAS,CAACiJ,eAAe,MAAM;IACzE;IAEAE,eAAe,EACb3E,WAAW,EACXC,kBAAkB,EAClBiB,WAAW,EAKZ,EAAQ;QACP,IAAI,CAACpD,mBAAmB;QACxB,IAAI,CAACO,qBAAqB;QAC1B,MAAMa,mBAAmB,IAAI,CAAC+B,wBAAwB,CACpDC,aACAlB,aACAC;QAEF,MAAM,EAAE8D,4BAA4B,EAAE,GAAG,IAAI,CAACD,uBAAuB;QACrE,IAAI,CAACpD,kBAAkB,CAAC;eAAIxB;YAAkB6E;SAA6B;QAC3E,IAAI,CAAChE,qCAAqC,CAACC,aAAaC;QACxD,IAAI,CAACkC,qBAAqB;QAC1B,IAAI,CAACqC,kBAAkB;QAEvB,IAAI,CAAC/F,gBAAgB;QAErB,kEAAkE;QAClE,IAAI,IAAI,CAAC9B,mBAAmB,CAACvC,MAAM,GAAG,GAAG;YACvC7B,YAAY,IAAI,CAACoE,mBAAmB;YACpC,IAAI,CAACA,mBAAmB,GAAG,EAAE;QAC/B;IACF;AACF;AAEA,SAASkB,gBAAgB+G,GAAwB;IAC/C,OAAOnH,OAAO2D,IAAI,CAACwD,KAChBC,IAAI,GACJC,MAAM,CACL,CAACC,KAAKrK;QACJqK,GAAG,CAACrK,IAAI,GAAGkK,GAAG,CAAClK,IAAI;QACnB,OAAOqK;IACT,GACA,CAAC;AAEP","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/shared/lib/turbopack/manifest-loader.ts"],"sourcesContent":["import type {\n EdgeFunctionDefinition,\n MiddlewareManifest,\n} from '../../../build/webpack/plugins/middleware-plugin'\nimport type { BuildManifest } from '../../../server/get-page-files'\nimport type { PagesManifest } from '../../../build/webpack/plugins/pages-manifest-plugin'\nimport type { ActionManifest } from '../../../build/webpack/plugins/flight-client-entry-plugin'\nimport type { NextFontManifest } from '../../../build/webpack/plugins/next-font-manifest-plugin'\nimport type { REACT_LOADABLE_MANIFEST } from '../constants'\nimport {\n APP_PATHS_MANIFEST,\n BUILD_MANIFEST,\n CLIENT_STATIC_FILES_PATH,\n INTERCEPTION_ROUTE_REWRITE_MANIFEST,\n MIDDLEWARE_BUILD_MANIFEST,\n MIDDLEWARE_MANIFEST,\n NEXT_FONT_MANIFEST,\n PAGES_MANIFEST,\n SERVER_REFERENCE_MANIFEST,\n SUBRESOURCE_INTEGRITY_MANIFEST,\n TURBOPACK_CLIENT_BUILD_MANIFEST,\n TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST,\n} from '../constants'\nimport { join, posix } from 'path'\nimport { readFileSync } from 'fs'\nimport type { SetupOpts } from '../../../server/lib/router-utils/setup-dev-bundler'\nimport { deleteCache } from '../../../server/dev/require-cache'\nimport { writeFileAtomic } from '../../../lib/fs/write-atomic'\nimport getAssetPathFromRoute from '../router/utils/get-asset-path-from-route'\nimport { getEntryKey, splitEntryKey, type EntryKey } from './entry-key'\nimport type { CustomRoutes } from '../../../lib/load-custom-routes'\nimport { getSortedRoutes } from '../router/utils'\nimport { existsSync } from 'fs'\nimport {\n addMetadataIdToRoute,\n addRouteSuffix,\n removeRouteSuffix,\n} from '../../../server/dev/turbopack-utils'\nimport { tryToParsePath } from '../../../lib/try-to-parse-path'\nimport { safePathToRegexp } from '../router/utils/route-match-utils'\nimport type { Entrypoints } from '../../../build/swc/types'\nimport {\n normalizeRewritesForBuildManifest,\n type ClientBuildManifest,\n srcEmptySsgManifest,\n processRoute,\n createEdgeRuntimeManifest,\n} from '../../../build/webpack/plugins/build-manifest-plugin-utils'\nimport type { SubresourceIntegrityManifest } from '../../../build'\n\ninterface InstrumentationDefinition {\n files: string[]\n name: 'instrumentation'\n}\n\ntype TurbopackMiddlewareManifest = MiddlewareManifest & {\n instrumentation?: InstrumentationDefinition\n}\n\ntype ManifestName =\n | typeof MIDDLEWARE_MANIFEST\n | typeof BUILD_MANIFEST\n | typeof PAGES_MANIFEST\n | typeof APP_PATHS_MANIFEST\n | `${typeof SERVER_REFERENCE_MANIFEST}.json`\n | `${typeof SUBRESOURCE_INTEGRITY_MANIFEST}.json`\n | `${typeof NEXT_FONT_MANIFEST}.json`\n | typeof REACT_LOADABLE_MANIFEST\n | typeof TURBOPACK_CLIENT_BUILD_MANIFEST\n\nconst getManifestPath = (\n page: string,\n distDir: string,\n name: ManifestName,\n type: string,\n firstCall: boolean\n) => {\n let manifestPath = posix.join(\n distDir,\n `server`,\n type,\n type === 'middleware' || type === 'instrumentation'\n ? ''\n : type === 'app'\n ? page\n : getAssetPathFromRoute(page),\n name\n )\n\n if (firstCall) {\n const isSitemapRoute = /[\\\\/]sitemap(.xml)?\\/route$/.test(page)\n // Check the ambiguity of /sitemap and /sitemap.xml\n if (isSitemapRoute && !existsSync(manifestPath)) {\n manifestPath = getManifestPath(\n page.replace(/\\/sitemap\\/route$/, '/sitemap.xml/route'),\n distDir,\n name,\n type,\n false\n )\n }\n // existsSync is faster than using the async version\n if (!existsSync(manifestPath) && page.endsWith('/route')) {\n // TODO: Improve implementation of metadata routes, currently it requires this extra check for the variants of the files that can be written.\n let basePage = removeRouteSuffix(page)\n // For sitemap.xml routes with generateSitemaps, the manifest is at\n // /sitemap/[__metadata_id__]/route (without .xml), because the route\n // handler serves at /sitemap/[id] not /sitemap.xml/[id]\n if (basePage.endsWith('/sitemap.xml')) {\n basePage = basePage.slice(0, -'.xml'.length)\n }\n let metadataPage = addRouteSuffix(addMetadataIdToRoute(basePage))\n manifestPath = getManifestPath(metadataPage, distDir, name, type, false)\n }\n }\n\n return manifestPath\n}\n\nfunction readPartialManifestContent(\n distDir: string,\n name: ManifestName,\n pageName: string,\n type: 'pages' | 'app' | 'middleware' | 'instrumentation' = 'pages'\n): string {\n const page = pageName\n const manifestPath = getManifestPath(page, distDir, name, type, true)\n return readFileSync(posix.join(manifestPath), 'utf-8')\n}\n\n/// Helper class that stores a map of manifests and tracks if they have changed\n/// since the last time they were written to disk. This is used to avoid\n/// unnecessary writes to disk.\nclass ManifestsMap<K, V> {\n private rawMap = new Map<K, string>()\n private map = new Map<K, V>()\n private extraInvalidationKey: string | undefined = undefined\n private changed = true\n\n set(key: K, value: string) {\n if (this.rawMap.get(key) === value) return\n this.changed = true\n this.rawMap.set(key, value)\n this.map.set(key, JSON.parse(value))\n }\n\n delete(key: K) {\n if (this.map.has(key)) {\n this.changed = true\n this.rawMap.delete(key)\n this.map.delete(key)\n }\n }\n\n get(key: K) {\n return this.map.get(key)\n }\n\n takeChanged(extraInvalidationKey?: any) {\n let changed = this.changed\n if (extraInvalidationKey !== undefined) {\n const stringified = JSON.stringify(extraInvalidationKey)\n if (this.extraInvalidationKey !== stringified) {\n this.extraInvalidationKey = stringified\n changed = true\n }\n }\n this.changed = false\n return changed\n }\n\n values() {\n return this.map.values()\n }\n\n entries() {\n return this.map.entries()\n }\n}\n\nexport class TurbopackManifestLoader {\n private actionManifests: ManifestsMap<EntryKey, ActionManifest> =\n new ManifestsMap()\n private appPathsManifests: ManifestsMap<EntryKey, PagesManifest> =\n new ManifestsMap()\n private buildManifests: ManifestsMap<EntryKey, BuildManifest> =\n new ManifestsMap()\n private clientBuildManifests: ManifestsMap<EntryKey, ClientBuildManifest> =\n new ManifestsMap()\n private fontManifests: ManifestsMap<EntryKey, NextFontManifest> =\n new ManifestsMap()\n private middlewareManifests: ManifestsMap<\n EntryKey,\n TurbopackMiddlewareManifest\n > = new ManifestsMap()\n private pagesManifests: ManifestsMap<string, PagesManifest> =\n new ManifestsMap()\n private sriManifests: ManifestsMap<EntryKey, SubresourceIntegrityManifest> =\n new ManifestsMap()\n private encryptionKey: string\n /// interceptionRewrites that have been written to disk\n /// This is used to avoid unnecessary writes if the rewrites haven't changed\n private cachedInterceptionRewrites: string | undefined = undefined\n private pendingCacheDeletes: string[] = []\n\n private readonly distDir: string\n private readonly buildId: string\n private readonly dev: boolean\n private readonly sriEnabled: boolean\n\n constructor({\n distDir,\n buildId,\n encryptionKey,\n dev,\n sriEnabled,\n }: {\n buildId: string\n distDir: string\n encryptionKey: string\n dev: boolean\n sriEnabled: boolean\n }) {\n this.distDir = distDir\n this.buildId = buildId\n this.encryptionKey = encryptionKey\n this.dev = dev\n this.sriEnabled = sriEnabled\n }\n\n delete(key: EntryKey) {\n this.actionManifests.delete(key)\n this.appPathsManifests.delete(key)\n this.buildManifests.delete(key)\n this.clientBuildManifests.delete(key)\n this.fontManifests.delete(key)\n this.middlewareManifests.delete(key)\n this.pagesManifests.delete(key)\n }\n\n loadActionManifest(pageName: string): void {\n this.actionManifests.set(\n getEntryKey('app', 'server', pageName),\n readPartialManifestContent(\n this.distDir,\n `${SERVER_REFERENCE_MANIFEST}.json`,\n pageName,\n 'app'\n )\n )\n }\n\n private mergeActionManifests(manifests: Iterable<ActionManifest>) {\n type ActionEntries = ActionManifest['edge' | 'node']\n const manifest: ActionManifest = {\n node: {},\n edge: {},\n encryptionKey: this.encryptionKey,\n }\n\n function mergeActionIds(\n actionEntries: ActionEntries,\n other: ActionEntries\n ): void {\n for (const key in other) {\n const action = (actionEntries[key] ??= {\n workers: {},\n })\n action.filename = other[key].filename\n action.exportedName = other[key].exportedName\n Object.assign(action.workers, other[key].workers)\n }\n }\n\n for (const m of manifests) {\n mergeActionIds(manifest.node, m.node)\n mergeActionIds(manifest.edge, m.edge)\n }\n for (const key in manifest.node) {\n const entry = manifest.node[key]\n entry.workers = sortObjectByKey(entry.workers)\n }\n for (const key in manifest.edge) {\n const entry = manifest.edge[key]\n entry.workers = sortObjectByKey(entry.workers)\n }\n\n return manifest\n }\n\n private writeActionManifest(): void {\n if (!this.actionManifests.takeChanged()) {\n return\n }\n const actionManifest = this.mergeActionManifests(\n this.actionManifests.values()\n )\n const actionManifestJsonPath = join(\n this.distDir,\n 'server',\n `${SERVER_REFERENCE_MANIFEST}.json`\n )\n const actionManifestJsPath = join(\n this.distDir,\n 'server',\n `${SERVER_REFERENCE_MANIFEST}.js`\n )\n const json = JSON.stringify(actionManifest, null, 2)\n this.pendingCacheDeletes.push(actionManifestJsonPath)\n this.pendingCacheDeletes.push(actionManifestJsPath)\n writeFileAtomic(actionManifestJsonPath, json)\n writeFileAtomic(\n actionManifestJsPath,\n `self.__RSC_SERVER_MANIFEST=${JSON.stringify(json)}`\n )\n }\n\n loadAppPathsManifest(pageName: string): void {\n this.appPathsManifests.set(\n getEntryKey('app', 'server', pageName),\n readPartialManifestContent(\n this.distDir,\n APP_PATHS_MANIFEST,\n pageName,\n 'app'\n )\n )\n }\n\n private writeAppPathsManifest(): void {\n if (!this.appPathsManifests.takeChanged()) {\n return\n }\n const appPathsManifest = this.mergePagesManifests(\n this.appPathsManifests.values()\n )\n const appPathsManifestPath = join(\n this.distDir,\n 'server',\n APP_PATHS_MANIFEST\n )\n this.pendingCacheDeletes.push(appPathsManifestPath)\n writeFileAtomic(\n appPathsManifestPath,\n JSON.stringify(appPathsManifest, null, 2)\n )\n }\n\n private writeSriManifest(): void {\n if (!this.sriEnabled || !this.sriManifests.takeChanged()) {\n return\n }\n const sriManifest = this.mergeSriManifests(this.sriManifests.values())\n const pathJson = join(\n this.distDir,\n 'server',\n `${SUBRESOURCE_INTEGRITY_MANIFEST}.json`\n )\n const pathJs = join(\n this.distDir,\n 'server',\n `${SUBRESOURCE_INTEGRITY_MANIFEST}.js`\n )\n this.pendingCacheDeletes.push(pathJson)\n this.pendingCacheDeletes.push(pathJs)\n writeFileAtomic(pathJson, JSON.stringify(sriManifest, null, 2))\n writeFileAtomic(\n pathJs,\n `self.__SUBRESOURCE_INTEGRITY_MANIFEST=${JSON.stringify(\n JSON.stringify(sriManifest)\n )}`\n )\n }\n\n loadBuildManifest(pageName: string, type: 'app' | 'pages' = 'pages'): void {\n this.buildManifests.set(\n getEntryKey(type, 'server', pageName),\n readPartialManifestContent(this.distDir, BUILD_MANIFEST, pageName, type)\n )\n }\n\n loadClientBuildManifest(\n pageName: string,\n type: 'app' | 'pages' = 'pages'\n ): void {\n this.clientBuildManifests.set(\n getEntryKey(type, 'server', pageName),\n readPartialManifestContent(\n this.distDir,\n TURBOPACK_CLIENT_BUILD_MANIFEST,\n pageName,\n type\n )\n )\n }\n\n loadSriManifest(pageName: string, type: 'app' | 'pages' = 'pages'): void {\n if (!this.sriEnabled) return\n this.sriManifests.set(\n getEntryKey(type, 'client', pageName),\n readPartialManifestContent(\n this.distDir,\n `${SUBRESOURCE_INTEGRITY_MANIFEST}.json`,\n pageName,\n type\n )\n )\n }\n\n private mergeBuildManifests(\n manifests: Iterable<BuildManifest>,\n lowPriorityFiles: string[]\n ) {\n const manifest: Partial<BuildManifest> & Pick<BuildManifest, 'pages'> = {\n pages: {\n '/_app': [],\n },\n // Something in next.js depends on these to exist even for app dir rendering\n devFiles: [],\n polyfillFiles: [],\n lowPriorityFiles,\n rootMainFiles: [],\n rootMainFilesTree: {},\n pagesChunkGroupBootstrapParams: {},\n }\n for (const m of manifests) {\n Object.assign(manifest.pages, m.pages)\n if (m.rootMainFiles.length) manifest.rootMainFiles = m.rootMainFiles\n // polyfillFiles should always be the same, so we can overwrite instead of actually merging\n if (m.polyfillFiles.length) manifest.polyfillFiles = m.polyfillFiles\n if (m.rootMainFilesTree) {\n Object.assign(manifest.rootMainFilesTree!, m.rootMainFilesTree)\n }\n if (m.pagesChunkGroupBootstrapParams) {\n Object.assign(\n manifest.pagesChunkGroupBootstrapParams!,\n m.pagesChunkGroupBootstrapParams\n )\n }\n if (m.chunkLoadingGlobal)\n manifest.chunkLoadingGlobal = m.chunkLoadingGlobal\n }\n manifest.pages = sortObjectByKey(manifest.pages) as BuildManifest['pages']\n return manifest\n }\n\n private mergeClientBuildManifests(\n manifests: Iterable<ClientBuildManifest>,\n rewrites: CustomRoutes['rewrites'],\n sortedPageKeys: string[]\n ): ClientBuildManifest {\n const manifest = {\n __rewrites: rewrites as any,\n sortedPages: sortedPageKeys,\n }\n for (const m of manifests) {\n Object.assign(manifest, m)\n }\n return sortObjectByKey(manifest)\n }\n\n private writeInterceptionRouteRewriteManifest(\n devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined,\n productionRewrites: CustomRoutes['rewrites'] | undefined\n ): void {\n const rewrites = productionRewrites ?? {\n ...devRewrites,\n beforeFiles: (devRewrites?.beforeFiles ?? []).map(processRoute),\n afterFiles: (devRewrites?.afterFiles ?? []).map(processRoute),\n fallback: (devRewrites?.fallback ?? []).map(processRoute),\n }\n\n const interceptionRewrites = JSON.stringify(\n rewrites.beforeFiles.filter(\n (\n require('../../../lib/is-interception-route-rewrite') as typeof import('../../../lib/is-interception-route-rewrite')\n ).isInterceptionRouteRewrite\n )\n )\n\n if (this.cachedInterceptionRewrites === interceptionRewrites) {\n return\n }\n this.cachedInterceptionRewrites = interceptionRewrites\n\n const interceptionRewriteManifestPath = join(\n this.distDir,\n 'server',\n `${INTERCEPTION_ROUTE_REWRITE_MANIFEST}.js`\n )\n this.pendingCacheDeletes.push(interceptionRewriteManifestPath)\n\n writeFileAtomic(\n interceptionRewriteManifestPath,\n `self.__INTERCEPTION_ROUTE_REWRITE_MANIFEST=${JSON.stringify(\n interceptionRewrites\n )};`\n )\n }\n\n private writeBuildManifest(lowPriorityFiles: string[]): void {\n if (!this.buildManifests.takeChanged()) {\n return\n }\n const buildManifest = this.mergeBuildManifests(\n this.buildManifests.values(),\n lowPriorityFiles\n )\n\n const buildManifestPath = join(this.distDir, BUILD_MANIFEST)\n const middlewareBuildManifestPath = join(\n this.distDir,\n 'server',\n `${MIDDLEWARE_BUILD_MANIFEST}.js`\n )\n\n this.pendingCacheDeletes.push(buildManifestPath)\n this.pendingCacheDeletes.push(middlewareBuildManifestPath)\n writeFileAtomic(buildManifestPath, JSON.stringify(buildManifest, null, 2))\n writeFileAtomic(\n middlewareBuildManifestPath,\n createEdgeRuntimeManifest(buildManifest)\n )\n\n // Write fallback build manifest\n const fallbackBuildManifest = this.mergeBuildManifests(\n [\n this.buildManifests.get(getEntryKey('pages', 'server', '_app')),\n this.buildManifests.get(getEntryKey('pages', 'server', '_error')),\n ].filter(Boolean) as BuildManifest[],\n lowPriorityFiles\n )\n const fallbackBuildManifestPath = join(\n this.distDir,\n `fallback-${BUILD_MANIFEST}`\n )\n this.pendingCacheDeletes.push(fallbackBuildManifestPath)\n writeFileAtomic(\n fallbackBuildManifestPath,\n JSON.stringify(fallbackBuildManifest, null, 2)\n )\n }\n\n private writeClientBuildManifest(\n entrypoints: Entrypoints,\n devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined,\n productionRewrites: CustomRoutes['rewrites'] | undefined\n ): string[] {\n const rewrites = normalizeRewritesForBuildManifest(\n productionRewrites ?? {\n ...devRewrites,\n beforeFiles: (devRewrites?.beforeFiles ?? []).map(processRoute),\n afterFiles: (devRewrites?.afterFiles ?? []).map(processRoute),\n fallback: (devRewrites?.fallback ?? []).map(processRoute),\n }\n )\n\n const pagesKeys = [...entrypoints.page.keys()]\n if (entrypoints.global.app) {\n pagesKeys.push('/_app')\n }\n if (entrypoints.global.error) {\n pagesKeys.push('/_error')\n }\n\n const sortedPageKeys = getSortedRoutes(pagesKeys)\n\n let buildManifestPath = posix.join(\n CLIENT_STATIC_FILES_PATH,\n this.buildId,\n '_buildManifest.js'\n )\n let ssgManifestPath = posix.join(\n CLIENT_STATIC_FILES_PATH,\n this.buildId,\n '_ssgManifest.js'\n )\n\n if (\n this.dev &&\n !this.clientBuildManifests.takeChanged({ rewrites, sortedPageKeys })\n ) {\n return [buildManifestPath, ssgManifestPath]\n }\n\n const clientBuildManifest = this.mergeClientBuildManifests(\n this.clientBuildManifests.values(),\n rewrites,\n sortedPageKeys\n )\n\n // Expose each route's bootstrap params and the chunk-loading global to the client\n // so `route-loader` can instantiate a navigated page's entry module. The server\n // stores params as raw JSON per route.\n const pageBootstrapParams: Record<string, unknown> = {}\n let chunkLoadingGlobal: string | undefined\n for (const [key, m] of this.buildManifests.entries()) {\n // Only the pages-router `route-loader` reads `__TURBOPACK_PAGE_BOOTSTRAP`. App routes\n // navigate via flight and never use it, so skip app entries to keep `_buildManifest.js`\n // (loaded on every page) small.\n if (splitEntryKey(key).type !== 'pages') continue\n if (m.chunkLoadingGlobal) chunkLoadingGlobal = m.chunkLoadingGlobal\n for (const [route, params] of Object.entries(\n m.pagesChunkGroupBootstrapParams ?? {}\n )) {\n pageBootstrapParams[route] = params\n }\n }\n\n // Only emit the bootstrap globals when a route actually inlined its bootstrap (shared runtime\n // enabled).\n const hasBootstrapParams = Object.keys(pageBootstrapParams).length > 0\n const clientBuildManifestJs =\n `self.__BUILD_MANIFEST = ${JSON.stringify(clientBuildManifest, null, 2)};` +\n (hasBootstrapParams\n ? `self.__TURBOPACK_PAGE_BOOTSTRAP = ${JSON.stringify(pageBootstrapParams)};` +\n (chunkLoadingGlobal\n ? `self.__TURBOPACK_CHUNK_LOADING_GLOBAL = ${JSON.stringify(\n chunkLoadingGlobal\n )};`\n : '')\n : '') +\n `self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()`\n\n writeFileAtomic(\n join(this.distDir, buildManifestPath),\n clientBuildManifestJs\n )\n // This is just an empty placeholder, the actual manifest is written after prerendering in\n // packages/next/src/build/index.ts\n writeFileAtomic(join(this.distDir, ssgManifestPath), srcEmptySsgManifest)\n\n return [buildManifestPath, ssgManifestPath]\n }\n\n loadFontManifest(pageName: string, type: 'app' | 'pages' = 'pages'): void {\n this.fontManifests.set(\n getEntryKey(type, 'server', pageName),\n readPartialManifestContent(\n this.distDir,\n `${NEXT_FONT_MANIFEST}.json`,\n pageName,\n type\n )\n )\n }\n\n private mergeFontManifests(manifests: Iterable<NextFontManifest>) {\n const manifest: NextFontManifest = {\n app: {},\n appUsingSizeAdjust: false,\n pages: {},\n pagesUsingSizeAdjust: false,\n }\n for (const m of manifests) {\n Object.assign(manifest.app, m.app)\n Object.assign(manifest.pages, m.pages)\n\n manifest.appUsingSizeAdjust =\n manifest.appUsingSizeAdjust || m.appUsingSizeAdjust\n manifest.pagesUsingSizeAdjust =\n manifest.pagesUsingSizeAdjust || m.pagesUsingSizeAdjust\n }\n manifest.app = sortObjectByKey(manifest.app)\n manifest.pages = sortObjectByKey(manifest.pages)\n return manifest\n }\n\n private async writeNextFontManifest(): Promise<void> {\n if (!this.fontManifests.takeChanged()) {\n return\n }\n const fontManifest = this.mergeFontManifests(this.fontManifests.values())\n const json = JSON.stringify(fontManifest, null, 2)\n\n const fontManifestJsonPath = join(\n this.distDir,\n 'server',\n `${NEXT_FONT_MANIFEST}.json`\n )\n const fontManifestJsPath = join(\n this.distDir,\n 'server',\n `${NEXT_FONT_MANIFEST}.js`\n )\n this.pendingCacheDeletes.push(fontManifestJsonPath)\n this.pendingCacheDeletes.push(fontManifestJsPath)\n writeFileAtomic(fontManifestJsonPath, json)\n writeFileAtomic(\n fontManifestJsPath,\n `self.__NEXT_FONT_MANIFEST=${JSON.stringify(json)}`\n )\n }\n\n /**\n * @returns If the manifest was written or not\n */\n loadMiddlewareManifest(\n pageName: string,\n type: 'pages' | 'app' | 'middleware' | 'instrumentation'\n ): boolean {\n const middlewareManifestPath = getManifestPath(\n pageName,\n this.distDir,\n MIDDLEWARE_MANIFEST,\n type,\n true\n )\n\n // middlewareManifest is actually \"edge manifest\" and not all routes are edge runtime. If it is not written we skip it.\n if (!existsSync(middlewareManifestPath)) {\n return false\n }\n\n this.middlewareManifests.set(\n getEntryKey(\n type === 'middleware' || type === 'instrumentation' ? 'root' : type,\n 'server',\n pageName\n ),\n readPartialManifestContent(\n this.distDir,\n MIDDLEWARE_MANIFEST,\n pageName,\n type\n )\n )\n\n return true\n }\n\n getMiddlewareManifest(key: EntryKey) {\n return this.middlewareManifests.get(key)\n }\n\n deleteMiddlewareManifest(key: EntryKey) {\n return this.middlewareManifests.delete(key)\n }\n\n private mergeMiddlewareManifests(\n manifests: Iterable<TurbopackMiddlewareManifest>\n ): MiddlewareManifest {\n const manifest: MiddlewareManifest = {\n version: 3,\n middleware: {},\n sortedMiddleware: [],\n functions: {},\n }\n let instrumentation: InstrumentationDefinition | undefined = undefined\n for (const m of manifests) {\n Object.assign(manifest.functions, m.functions)\n Object.assign(manifest.middleware, m.middleware)\n if (m.instrumentation) {\n instrumentation = m.instrumentation\n }\n }\n manifest.functions = sortObjectByKey(manifest.functions)\n manifest.middleware = sortObjectByKey(manifest.middleware)\n const updateFunctionDefinition = (\n fun: EdgeFunctionDefinition\n ): EdgeFunctionDefinition => {\n return {\n ...fun,\n files: [...(instrumentation?.files ?? []), ...fun.files],\n }\n }\n for (const key of Object.keys(manifest.middleware)) {\n const value = manifest.middleware[key]\n manifest.middleware[key] = updateFunctionDefinition(value)\n }\n for (const key of Object.keys(manifest.functions)) {\n const value = manifest.functions[key]\n manifest.functions[key] = updateFunctionDefinition(value)\n }\n for (const fun of Object.values(manifest.functions).concat(\n Object.values(manifest.middleware)\n )) {\n for (const matcher of fun.matchers) {\n if (!matcher.regexp) {\n matcher.regexp = safePathToRegexp(matcher.originalSource, [], {\n delimiter: '/',\n sensitive: false,\n strict: true,\n }).source.replaceAll('\\\\/', '/')\n }\n }\n }\n manifest.sortedMiddleware = Object.keys(manifest.middleware)\n\n return manifest\n }\n\n private writeMiddlewareManifest(): {\n clientMiddlewareManifestPath: string\n } {\n let clientMiddlewareManifestPath = posix.join(\n CLIENT_STATIC_FILES_PATH,\n this.buildId,\n TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST\n )\n\n if (this.dev && !this.middlewareManifests.takeChanged()) {\n return {\n clientMiddlewareManifestPath,\n }\n }\n const middlewareManifest = this.mergeMiddlewareManifests(\n this.middlewareManifests.values()\n )\n\n // Server middleware manifest\n\n // Normalize regexes as it uses path-to-regexp\n for (const key in middlewareManifest.middleware) {\n middlewareManifest.middleware[key].matchers.forEach((matcher) => {\n if (!matcher.regexp.startsWith('^')) {\n const parsedPage = tryToParsePath(matcher.regexp)\n if (parsedPage.error || !parsedPage.regexStr) {\n throw new Error(`Invalid source: ${matcher.regexp}`)\n }\n matcher.regexp = parsedPage.regexStr\n }\n })\n }\n\n const middlewareManifestPath = join(\n this.distDir,\n 'server',\n MIDDLEWARE_MANIFEST\n )\n this.pendingCacheDeletes.push(middlewareManifestPath)\n writeFileAtomic(\n middlewareManifestPath,\n JSON.stringify(middlewareManifest, null, 2)\n )\n\n // Client middleware manifest This is only used in dev though, packages/next/src/build/index.ts\n // writes the manifest again for builds.\n const matchers = middlewareManifest?.middleware['/']?.matchers || []\n\n const clientMiddlewareManifestJs = `self.__MIDDLEWARE_MATCHERS = ${JSON.stringify(\n matchers,\n null,\n 2\n )};self.__MIDDLEWARE_MATCHERS_CB && self.__MIDDLEWARE_MATCHERS_CB()`\n\n this.pendingCacheDeletes.push(clientMiddlewareManifestPath)\n writeFileAtomic(\n join(this.distDir, clientMiddlewareManifestPath),\n clientMiddlewareManifestJs\n )\n\n return {\n clientMiddlewareManifestPath,\n }\n }\n\n loadPagesManifest(pageName: string): void {\n this.pagesManifests.set(\n getEntryKey('pages', 'server', pageName),\n readPartialManifestContent(this.distDir, PAGES_MANIFEST, pageName)\n )\n }\n\n private mergePagesManifests(manifests: Iterable<PagesManifest>) {\n const manifest: PagesManifest = {}\n for (const m of manifests) {\n Object.assign(manifest, m)\n }\n return sortObjectByKey(manifest)\n }\n\n private mergeSriManifests(manifests: Iterable<SubresourceIntegrityManifest>) {\n const manifest: SubresourceIntegrityManifest = {}\n for (const m of manifests) {\n Object.assign(manifest, m)\n }\n return sortObjectByKey(manifest)\n }\n\n private writePagesManifest(): void {\n if (!this.pagesManifests.takeChanged()) {\n return\n }\n const pagesManifest = this.mergePagesManifests(this.pagesManifests.values())\n const pagesManifestPath = join(this.distDir, 'server', PAGES_MANIFEST)\n this.pendingCacheDeletes.push(pagesManifestPath)\n writeFileAtomic(pagesManifestPath, JSON.stringify(pagesManifest, null, 2))\n }\n\n writeManifests({\n devRewrites,\n productionRewrites,\n entrypoints,\n }: {\n devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined\n productionRewrites: CustomRoutes['rewrites'] | undefined\n entrypoints: Entrypoints\n }): void {\n this.writeActionManifest()\n this.writeAppPathsManifest()\n const lowPriorityFiles = this.writeClientBuildManifest(\n entrypoints,\n devRewrites,\n productionRewrites\n )\n const { clientMiddlewareManifestPath } = this.writeMiddlewareManifest()\n this.writeBuildManifest([...lowPriorityFiles, clientMiddlewareManifestPath])\n this.writeInterceptionRouteRewriteManifest(devRewrites, productionRewrites)\n this.writeNextFontManifest()\n this.writePagesManifest()\n\n this.writeSriManifest()\n\n // Flush all queued cache deletions in a single require.cache scan\n if (this.pendingCacheDeletes.length > 0) {\n deleteCache(this.pendingCacheDeletes)\n this.pendingCacheDeletes = []\n }\n }\n}\n\nfunction sortObjectByKey(obj: Record<string, any>) {\n return Object.keys(obj)\n .sort()\n .reduce(\n (acc, key) => {\n acc[key] = obj[key]\n return acc\n },\n {} as Record<string, any>\n )\n}\n"],"names":["APP_PATHS_MANIFEST","BUILD_MANIFEST","CLIENT_STATIC_FILES_PATH","INTERCEPTION_ROUTE_REWRITE_MANIFEST","MIDDLEWARE_BUILD_MANIFEST","MIDDLEWARE_MANIFEST","NEXT_FONT_MANIFEST","PAGES_MANIFEST","SERVER_REFERENCE_MANIFEST","SUBRESOURCE_INTEGRITY_MANIFEST","TURBOPACK_CLIENT_BUILD_MANIFEST","TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST","join","posix","readFileSync","deleteCache","writeFileAtomic","getAssetPathFromRoute","getEntryKey","splitEntryKey","getSortedRoutes","existsSync","addMetadataIdToRoute","addRouteSuffix","removeRouteSuffix","tryToParsePath","safePathToRegexp","normalizeRewritesForBuildManifest","srcEmptySsgManifest","processRoute","createEdgeRuntimeManifest","getManifestPath","page","distDir","name","type","firstCall","manifestPath","isSitemapRoute","test","replace","endsWith","basePage","slice","length","metadataPage","readPartialManifestContent","pageName","ManifestsMap","set","key","value","rawMap","get","changed","map","JSON","parse","delete","has","takeChanged","extraInvalidationKey","undefined","stringified","stringify","values","entries","Map","TurbopackManifestLoader","constructor","buildId","encryptionKey","dev","sriEnabled","actionManifests","appPathsManifests","buildManifests","clientBuildManifests","fontManifests","middlewareManifests","pagesManifests","sriManifests","cachedInterceptionRewrites","pendingCacheDeletes","loadActionManifest","mergeActionManifests","manifests","manifest","node","edge","mergeActionIds","actionEntries","other","action","workers","filename","exportedName","Object","assign","m","entry","sortObjectByKey","writeActionManifest","actionManifest","actionManifestJsonPath","actionManifestJsPath","json","push","loadAppPathsManifest","writeAppPathsManifest","appPathsManifest","mergePagesManifests","appPathsManifestPath","writeSriManifest","sriManifest","mergeSriManifests","pathJson","pathJs","loadBuildManifest","loadClientBuildManifest","loadSriManifest","mergeBuildManifests","lowPriorityFiles","pages","devFiles","polyfillFiles","rootMainFiles","rootMainFilesTree","pagesChunkGroupBootstrapParams","chunkLoadingGlobal","mergeClientBuildManifests","rewrites","sortedPageKeys","__rewrites","sortedPages","writeInterceptionRouteRewriteManifest","devRewrites","productionRewrites","beforeFiles","afterFiles","fallback","interceptionRewrites","filter","require","isInterceptionRouteRewrite","interceptionRewriteManifestPath","writeBuildManifest","buildManifest","buildManifestPath","middlewareBuildManifestPath","fallbackBuildManifest","Boolean","fallbackBuildManifestPath","writeClientBuildManifest","entrypoints","pagesKeys","keys","global","app","error","ssgManifestPath","clientBuildManifest","pageBootstrapParams","route","params","hasBootstrapParams","clientBuildManifestJs","loadFontManifest","mergeFontManifests","appUsingSizeAdjust","pagesUsingSizeAdjust","writeNextFontManifest","fontManifest","fontManifestJsonPath","fontManifestJsPath","loadMiddlewareManifest","middlewareManifestPath","getMiddlewareManifest","deleteMiddlewareManifest","mergeMiddlewareManifests","version","middleware","sortedMiddleware","functions","instrumentation","updateFunctionDefinition","fun","files","concat","matcher","matchers","regexp","originalSource","delimiter","sensitive","strict","source","replaceAll","writeMiddlewareManifest","clientMiddlewareManifestPath","middlewareManifest","forEach","startsWith","parsedPage","regexStr","Error","clientMiddlewareManifestJs","loadPagesManifest","writePagesManifest","pagesManifest","pagesManifestPath","writeManifests","obj","sort","reduce","acc"],"mappings":"AASA,SACEA,kBAAkB,EAClBC,cAAc,EACdC,wBAAwB,EACxBC,mCAAmC,EACn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,KAAKrK;QACJqK,GAAG,CAACrK,IAAI,GAAGkK,GAAG,CAAClK,IAAI;QACnB,OAAOqK;IACT,GACA,CAAC;AAEP","ignoreList":[0]} |
@@ -417,3 +417,2 @@ "use strict"; | ||
| images: nextConfig.images, | ||
| htmlLimitedBots: nextConfig.htmlLimitedBots.source, | ||
| experimental: { | ||
@@ -420,0 +419,0 @@ clientTraceMetadata: nextConfig.experimental.clientTraceMetadata, |
@@ -75,3 +75,3 @@ "use strict"; | ||
| const data = await res.json(); | ||
| const versionData = data.versions["16.3.1-canary.10"]; | ||
| const versionData = data.versions["16.3.1-canary.11"]; | ||
| return { | ||
@@ -104,3 +104,3 @@ os: versionData.os, | ||
| lockfileParsed.dependencies[pkg] = { | ||
| version: "16.3.1-canary.10", | ||
| version: "16.3.1-canary.11", | ||
| resolved: pkgData.tarball, | ||
@@ -113,3 +113,3 @@ integrity: pkgData.integrity, | ||
| lockfileParsed.packages[pkg] = { | ||
| version: "16.3.1-canary.10", | ||
| version: "16.3.1-canary.11", | ||
| resolved: pkgData.tarball, | ||
@@ -116,0 +116,0 @@ integrity: pkgData.integrity, |
@@ -65,3 +65,2 @@ import type { LoadComponentsReturnType } from '../load-components'; | ||
| isPrefetch?: boolean; | ||
| htmlLimitedBots: string | undefined; | ||
| experimental: { | ||
@@ -68,0 +67,0 @@ /** |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/app-render/types.ts"],"sourcesContent":["import type { LoadComponentsReturnType } from '../load-components'\nimport type { ServerRuntime, SizeLimit } from '../../types'\nimport type {\n ExperimentalConfig,\n NextConfigComplete,\n PrefetchInliningConfig,\n ValidationLevel,\n} from '../../server/config-shared'\nimport type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { AppPageModule } from '../route-modules/app-page/module'\nimport type { DeepReadonly } from '../../shared/lib/deep-readonly'\nimport type { ImageConfigComplete } from '../../shared/lib/image-config'\nimport type { __ApiPreviewProps } from '../api-utils'\n\nimport s from 'next/dist/compiled/superstruct'\nimport type { RequestLifecycleOpts } from '../base-server'\nimport type { InstrumentationOnRequestError } from '../instrumentation/types'\nimport type { NextRequestHint } from '../web/adapter'\nimport type { BaseNextRequest } from '../base-http'\nimport type { IncomingMessage } from 'http'\nimport type { RenderResumeDataCache } from '../resume-data-cache/resume-data-cache'\nimport type { ServerCacheStatus } from '../../next-devtools/dev-overlay/cache-indicator'\nimport type { PrefetchHints } from '../../shared/lib/app-router-types'\nimport type { AnyStream } from './stream-ops'\n\nconst dynamicParamTypesSchema = s.enums([\n 'c',\n 'ci(..)(..)',\n 'ci(.)',\n 'ci(..)',\n 'ci(...)',\n 'oc',\n 'd',\n 'di(..)(..)',\n 'di(.)',\n 'di(..)',\n 'di(...)',\n])\n\nconst segmentSchema = s.union([\n s.string(),\n\n s.tuple([\n // Param name\n s.string(),\n // Param cache key (almost the same as the value, but arrays are\n // concatenated into strings)\n // TODO: We should change this to just be the value. Currently we convert\n // it back to a value when passing to useParams. It only needs to be\n // a string when converted to a a cache key, but that doesn't mean we\n // need to store it as that representation.\n s.string(),\n // Dynamic param type\n dynamicParamTypesSchema,\n // Static siblings at the same URL level. Used by the client router to\n // determine if a prefetch can be reused when navigating to a static\n // sibling of a dynamic route. null means siblings are unknown.\n s.nullable(s.array(s.string())),\n ]),\n])\n\n// unfortunately the tuple is not understood well by Describe so we have to\n// use any here. This does not have any impact on the runtime type since the validation\n// does work correctly.\nexport const flightRouterStateSchema: s.Describe<any> = s.tuple([\n segmentSchema,\n s.record(\n s.string(),\n s.lazy(() => flightRouterStateSchema)\n ),\n s.optional(s.nullable(s.tuple([s.string(), s.string()]))),\n s.optional(\n s.nullable(\n s.union([\n s.literal('refetch'),\n s.literal('inside-shared-layout'),\n s.literal('metadata-only'),\n ])\n )\n ),\n s.optional(s.number()),\n])\n\nexport type ServerOnInstrumentationRequestError = (\n error: unknown,\n // The request could be middleware, node server or web server request,\n // we normalized them into an aligned format to `onRequestError` API later.\n request: NextRequestHint | BaseNextRequest | IncomingMessage,\n errorContext: Parameters<InstrumentationOnRequestError>[2],\n silenceLog: boolean\n) => void | Promise<void>\n\nexport interface RenderOptsPartial {\n dir?: string\n previewProps: __ApiPreviewProps | undefined\n err?: Error | null\n basePath: string\n cacheComponents: boolean\n partialPrefetching?: NextConfigComplete['partialPrefetching']\n validationLevel: ValidationLevel\n trailingSlash: boolean\n images: ImageConfigComplete\n supportsDynamicResponse: boolean\n runtime?: ServerRuntime\n serverComponents?: boolean\n enableTainting?: boolean\n assetPrefix?: string\n crossOrigin?: '' | 'anonymous' | 'use-credentials' | undefined\n nextFontManifest?: DeepReadonly<NextFontManifest>\n botType?: 'dom' | 'html' | undefined\n serveStreamingMetadata?: boolean\n incrementalCache?: import('../lib/incremental-cache').IncrementalCache\n cacheLifeProfiles: import('../config-shared').ResolvedCacheLifeProfiles\n staticPageGenerationTimeout: number\n isOnDemandRevalidate?: boolean\n isPossibleServerAction?: boolean\n setCacheStatus?: (status: ServerCacheStatus, htmlRequestId: string) => void\n setIsrStatus?: (key: string, value: boolean | undefined) => void\n setReactDebugChannel?: (\n debugChannel: { readable: AnyStream },\n htmlRequestId: string,\n requestId: string\n ) => void\n sendErrorsToBrowser?: (\n errorsRscStream: AnyStream,\n htmlRequestId: string\n ) => void\n isBuildTimePrerendering?: boolean\n nextConfigOutput?: 'standalone' | 'export'\n onInstrumentationRequestError?: ServerOnInstrumentationRequestError\n isDraftMode?: boolean\n onUpdateCookies?: (cookies: string[]) => void\n loadConfig?: (\n phase: string,\n dir: string,\n customConfig?: object | null,\n rawConfig?: boolean,\n silent?: boolean\n ) => Promise<NextConfigComplete>\n serverActions?: {\n bodySizeLimit?: SizeLimit\n allowedOrigins?: string[]\n }\n logServerFunctions?: boolean\n params?: ParsedUrlQuery\n isPrefetch?: boolean\n htmlLimitedBots: string | undefined\n experimental: {\n /**\n * When true, it indicates that the current page supports partial\n * prerendering.\n */\n isRoutePPREnabled?: boolean\n expireTime: number | undefined\n staleTimes: ExperimentalConfig['staleTimes'] | undefined\n clientTraceMetadata: string[] | undefined\n\n /**\n * The origins that are allowed to write the rewritten headers when\n * performing a non-relative rewrite. When undefined, no non-relative\n * rewrites will get the rewrite headers.\n */\n clientParamParsingOrigins: string[] | undefined\n dynamicOnHover: boolean\n optimisticRouting: boolean\n inlineCss: boolean\n prefetchInlining: PrefetchInliningConfig\n authInterrupts: boolean\n serverComponentsHmrCancellation?: boolean\n useCacheTimeout: number\n cachedNavigations: boolean\n\n /**\n * The maximum size (in bytes) of the postponed state body for PPR resume\n * requests. Used to calculate decompression limits (5x this value).\n */\n maxPostponedStateSizeBytes: number | undefined\n\n /**\n * Whether the Instant Navigation Testing API is exposed (dev mode or the\n * `exposeTestingApiInProductionBuild` flag). When true, the prerendered\n * shell and dynamic renders embed a cookie-guarded bootstrap script that\n * drives instant navigation tests.\n */\n exposeTestingApi: boolean\n }\n postponed?: string\n\n /**\n * A prefilled resume data cache. This was either generated for this page\n * during dev warmup, or when a page with defined params was previously\n * prerendered, and now its matching optional fallback shell is prerendered.\n */\n renderResumeDataCache?: RenderResumeDataCache\n\n /**\n * When true, the page will be rendered using the static rendering to detect\n * any dynamic API's that would have stopped the page from being fully\n * statically generated.\n */\n isDebugDynamicAccesses?: boolean\n\n /**\n /**\n * The maximum length of the headers that are emitted by React and added to\n * the response.\n */\n reactMaxHeadersLength: number | undefined\n\n /**\n * Per-route prefetch hints from prefetch-hints.json.\n * Loaded at server startup from the build output.\n */\n prefetchHints?: Record<string, PrefetchHints>\n\n /**\n * When true, the page is prerendered as a fallback shell, while allowing any\n * dynamic accesses to result in an empty shell. This is the case when there\n * are also routes prerendered with a more complete set of params.\n * Prerendering those routes would catch any invalid dynamic accesses.\n */\n allowEmptyStaticShell?: boolean\n\n /**\n * When true, attempt to run build-time instant validation for this prerender.\n * Only the first prerender per page sets this, since validation uses\n * instant.unstable_samples and is independent of actual route params.\n */\n runInstantValidation?: boolean\n\n /**\n * When true, a fallback shell produced for this render could later be\n * upgraded to a concrete version (at least one of its fallback params is a\n * candidate enumerated by `generateStaticParams`). Only such shells are\n * flagged `isUpgradeableISRFallback` so the client retries the prefetch; a route that\n * can never upgrade (no `generateStaticParams`) is left unflagged.\n */\n isFallbackUpgradeable?: boolean\n}\n\nexport type RenderOpts = LoadComponentsReturnType<AppPageModule> &\n RenderOptsPartial &\n RequestLifecycleOpts\n\nexport type PreloadCallbacks = (() => void)[]\n"],"names":["flightRouterStateSchema","dynamicParamTypesSchema","s","enums","segmentSchema","union","string","tuple","nullable","array","record","lazy","optional","literal","number"],"mappings":";;;;+BAiEaA;;;eAAAA;;;oEAlDC;;;;;;AAWd,MAAMC,0BAA0BC,oBAAC,CAACC,KAAK,CAAC;IACtC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,MAAMC,gBAAgBF,oBAAC,CAACG,KAAK,CAAC;IAC5BH,oBAAC,CAACI,MAAM;IAERJ,oBAAC,CAACK,KAAK,CAAC;QACN,aAAa;QACbL,oBAAC,CAACI,MAAM;QACR,gEAAgE;QAChE,6BAA6B;QAC7B,yEAAyE;QACzE,oEAAoE;QACpE,qEAAqE;QACrE,2CAA2C;QAC3CJ,oBAAC,CAACI,MAAM;QACR,qBAAqB;QACrBL;QACA,sEAAsE;QACtE,oEAAoE;QACpE,+DAA+D;QAC/DC,oBAAC,CAACM,QAAQ,CAACN,oBAAC,CAACO,KAAK,CAACP,oBAAC,CAACI,MAAM;KAC5B;CACF;AAKM,MAAMN,0BAA2CE,oBAAC,CAACK,KAAK,CAAC;IAC9DH;IACAF,oBAAC,CAACQ,MAAM,CACNR,oBAAC,CAACI,MAAM,IACRJ,oBAAC,CAACS,IAAI,CAAC,IAAMX;IAEfE,oBAAC,CAACU,QAAQ,CAACV,oBAAC,CAACM,QAAQ,CAACN,oBAAC,CAACK,KAAK,CAAC;QAACL,oBAAC,CAACI,MAAM;QAAIJ,oBAAC,CAACI,MAAM;KAAG;IACtDJ,oBAAC,CAACU,QAAQ,CACRV,oBAAC,CAACM,QAAQ,CACRN,oBAAC,CAACG,KAAK,CAAC;QACNH,oBAAC,CAACW,OAAO,CAAC;QACVX,oBAAC,CAACW,OAAO,CAAC;QACVX,oBAAC,CAACW,OAAO,CAAC;KACX;IAGLX,oBAAC,CAACU,QAAQ,CAACV,oBAAC,CAACY,MAAM;CACpB","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/app-render/types.ts"],"sourcesContent":["import type { LoadComponentsReturnType } from '../load-components'\nimport type { ServerRuntime, SizeLimit } from '../../types'\nimport type {\n ExperimentalConfig,\n NextConfigComplete,\n PrefetchInliningConfig,\n ValidationLevel,\n} from '../../server/config-shared'\nimport type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { AppPageModule } from '../route-modules/app-page/module'\nimport type { DeepReadonly } from '../../shared/lib/deep-readonly'\nimport type { ImageConfigComplete } from '../../shared/lib/image-config'\nimport type { __ApiPreviewProps } from '../api-utils'\n\nimport s from 'next/dist/compiled/superstruct'\nimport type { RequestLifecycleOpts } from '../base-server'\nimport type { InstrumentationOnRequestError } from '../instrumentation/types'\nimport type { NextRequestHint } from '../web/adapter'\nimport type { BaseNextRequest } from '../base-http'\nimport type { IncomingMessage } from 'http'\nimport type { RenderResumeDataCache } from '../resume-data-cache/resume-data-cache'\nimport type { ServerCacheStatus } from '../../next-devtools/dev-overlay/cache-indicator'\nimport type { PrefetchHints } from '../../shared/lib/app-router-types'\nimport type { AnyStream } from './stream-ops'\n\nconst dynamicParamTypesSchema = s.enums([\n 'c',\n 'ci(..)(..)',\n 'ci(.)',\n 'ci(..)',\n 'ci(...)',\n 'oc',\n 'd',\n 'di(..)(..)',\n 'di(.)',\n 'di(..)',\n 'di(...)',\n])\n\nconst segmentSchema = s.union([\n s.string(),\n\n s.tuple([\n // Param name\n s.string(),\n // Param cache key (almost the same as the value, but arrays are\n // concatenated into strings)\n // TODO: We should change this to just be the value. Currently we convert\n // it back to a value when passing to useParams. It only needs to be\n // a string when converted to a a cache key, but that doesn't mean we\n // need to store it as that representation.\n s.string(),\n // Dynamic param type\n dynamicParamTypesSchema,\n // Static siblings at the same URL level. Used by the client router to\n // determine if a prefetch can be reused when navigating to a static\n // sibling of a dynamic route. null means siblings are unknown.\n s.nullable(s.array(s.string())),\n ]),\n])\n\n// unfortunately the tuple is not understood well by Describe so we have to\n// use any here. This does not have any impact on the runtime type since the validation\n// does work correctly.\nexport const flightRouterStateSchema: s.Describe<any> = s.tuple([\n segmentSchema,\n s.record(\n s.string(),\n s.lazy(() => flightRouterStateSchema)\n ),\n s.optional(s.nullable(s.tuple([s.string(), s.string()]))),\n s.optional(\n s.nullable(\n s.union([\n s.literal('refetch'),\n s.literal('inside-shared-layout'),\n s.literal('metadata-only'),\n ])\n )\n ),\n s.optional(s.number()),\n])\n\nexport type ServerOnInstrumentationRequestError = (\n error: unknown,\n // The request could be middleware, node server or web server request,\n // we normalized them into an aligned format to `onRequestError` API later.\n request: NextRequestHint | BaseNextRequest | IncomingMessage,\n errorContext: Parameters<InstrumentationOnRequestError>[2],\n silenceLog: boolean\n) => void | Promise<void>\n\nexport interface RenderOptsPartial {\n dir?: string\n previewProps: __ApiPreviewProps | undefined\n err?: Error | null\n basePath: string\n cacheComponents: boolean\n partialPrefetching?: NextConfigComplete['partialPrefetching']\n validationLevel: ValidationLevel\n trailingSlash: boolean\n images: ImageConfigComplete\n supportsDynamicResponse: boolean\n runtime?: ServerRuntime\n serverComponents?: boolean\n enableTainting?: boolean\n assetPrefix?: string\n crossOrigin?: '' | 'anonymous' | 'use-credentials' | undefined\n nextFontManifest?: DeepReadonly<NextFontManifest>\n botType?: 'dom' | 'html' | undefined\n serveStreamingMetadata?: boolean\n incrementalCache?: import('../lib/incremental-cache').IncrementalCache\n cacheLifeProfiles: import('../config-shared').ResolvedCacheLifeProfiles\n staticPageGenerationTimeout: number\n isOnDemandRevalidate?: boolean\n isPossibleServerAction?: boolean\n setCacheStatus?: (status: ServerCacheStatus, htmlRequestId: string) => void\n setIsrStatus?: (key: string, value: boolean | undefined) => void\n setReactDebugChannel?: (\n debugChannel: { readable: AnyStream },\n htmlRequestId: string,\n requestId: string\n ) => void\n sendErrorsToBrowser?: (\n errorsRscStream: AnyStream,\n htmlRequestId: string\n ) => void\n isBuildTimePrerendering?: boolean\n nextConfigOutput?: 'standalone' | 'export'\n onInstrumentationRequestError?: ServerOnInstrumentationRequestError\n isDraftMode?: boolean\n onUpdateCookies?: (cookies: string[]) => void\n loadConfig?: (\n phase: string,\n dir: string,\n customConfig?: object | null,\n rawConfig?: boolean,\n silent?: boolean\n ) => Promise<NextConfigComplete>\n serverActions?: {\n bodySizeLimit?: SizeLimit\n allowedOrigins?: string[]\n }\n logServerFunctions?: boolean\n params?: ParsedUrlQuery\n isPrefetch?: boolean\n experimental: {\n /**\n * When true, it indicates that the current page supports partial\n * prerendering.\n */\n isRoutePPREnabled?: boolean\n expireTime: number | undefined\n staleTimes: ExperimentalConfig['staleTimes'] | undefined\n clientTraceMetadata: string[] | undefined\n\n /**\n * The origins that are allowed to write the rewritten headers when\n * performing a non-relative rewrite. When undefined, no non-relative\n * rewrites will get the rewrite headers.\n */\n clientParamParsingOrigins: string[] | undefined\n dynamicOnHover: boolean\n optimisticRouting: boolean\n inlineCss: boolean\n prefetchInlining: PrefetchInliningConfig\n authInterrupts: boolean\n serverComponentsHmrCancellation?: boolean\n useCacheTimeout: number\n cachedNavigations: boolean\n\n /**\n * The maximum size (in bytes) of the postponed state body for PPR resume\n * requests. Used to calculate decompression limits (5x this value).\n */\n maxPostponedStateSizeBytes: number | undefined\n\n /**\n * Whether the Instant Navigation Testing API is exposed (dev mode or the\n * `exposeTestingApiInProductionBuild` flag). When true, the prerendered\n * shell and dynamic renders embed a cookie-guarded bootstrap script that\n * drives instant navigation tests.\n */\n exposeTestingApi: boolean\n }\n postponed?: string\n\n /**\n * A prefilled resume data cache. This was either generated for this page\n * during dev warmup, or when a page with defined params was previously\n * prerendered, and now its matching optional fallback shell is prerendered.\n */\n renderResumeDataCache?: RenderResumeDataCache\n\n /**\n * When true, the page will be rendered using the static rendering to detect\n * any dynamic API's that would have stopped the page from being fully\n * statically generated.\n */\n isDebugDynamicAccesses?: boolean\n\n /**\n /**\n * The maximum length of the headers that are emitted by React and added to\n * the response.\n */\n reactMaxHeadersLength: number | undefined\n\n /**\n * Per-route prefetch hints from prefetch-hints.json.\n * Loaded at server startup from the build output.\n */\n prefetchHints?: Record<string, PrefetchHints>\n\n /**\n * When true, the page is prerendered as a fallback shell, while allowing any\n * dynamic accesses to result in an empty shell. This is the case when there\n * are also routes prerendered with a more complete set of params.\n * Prerendering those routes would catch any invalid dynamic accesses.\n */\n allowEmptyStaticShell?: boolean\n\n /**\n * When true, attempt to run build-time instant validation for this prerender.\n * Only the first prerender per page sets this, since validation uses\n * instant.unstable_samples and is independent of actual route params.\n */\n runInstantValidation?: boolean\n\n /**\n * When true, a fallback shell produced for this render could later be\n * upgraded to a concrete version (at least one of its fallback params is a\n * candidate enumerated by `generateStaticParams`). Only such shells are\n * flagged `isUpgradeableISRFallback` so the client retries the prefetch; a route that\n * can never upgrade (no `generateStaticParams`) is left unflagged.\n */\n isFallbackUpgradeable?: boolean\n}\n\nexport type RenderOpts = LoadComponentsReturnType<AppPageModule> &\n RenderOptsPartial &\n RequestLifecycleOpts\n\nexport type PreloadCallbacks = (() => void)[]\n"],"names":["flightRouterStateSchema","dynamicParamTypesSchema","s","enums","segmentSchema","union","string","tuple","nullable","array","record","lazy","optional","literal","number"],"mappings":";;;;+BAiEaA;;;eAAAA;;;oEAlDC;;;;;;AAWd,MAAMC,0BAA0BC,oBAAC,CAACC,KAAK,CAAC;IACtC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,MAAMC,gBAAgBF,oBAAC,CAACG,KAAK,CAAC;IAC5BH,oBAAC,CAACI,MAAM;IAERJ,oBAAC,CAACK,KAAK,CAAC;QACN,aAAa;QACbL,oBAAC,CAACI,MAAM;QACR,gEAAgE;QAChE,6BAA6B;QAC7B,yEAAyE;QACzE,oEAAoE;QACpE,qEAAqE;QACrE,2CAA2C;QAC3CJ,oBAAC,CAACI,MAAM;QACR,qBAAqB;QACrBL;QACA,sEAAsE;QACtE,oEAAoE;QACpE,+DAA+D;QAC/DC,oBAAC,CAACM,QAAQ,CAACN,oBAAC,CAACO,KAAK,CAACP,oBAAC,CAACI,MAAM;KAC5B;CACF;AAKM,MAAMN,0BAA2CE,oBAAC,CAACK,KAAK,CAAC;IAC9DH;IACAF,oBAAC,CAACQ,MAAM,CACNR,oBAAC,CAACI,MAAM,IACRJ,oBAAC,CAACS,IAAI,CAAC,IAAMX;IAEfE,oBAAC,CAACU,QAAQ,CAACV,oBAAC,CAACM,QAAQ,CAACN,oBAAC,CAACK,KAAK,CAAC;QAACL,oBAAC,CAACI,MAAM;QAAIJ,oBAAC,CAACI,MAAM;KAAG;IACtDJ,oBAAC,CAACU,QAAQ,CACRV,oBAAC,CAACM,QAAQ,CACRN,oBAAC,CAACG,KAAK,CAAC;QACNH,oBAAC,CAACW,OAAO,CAAC;QACVX,oBAAC,CAACW,OAAO,CAAC;QACVX,oBAAC,CAACW,OAAO,CAAC;KACX;IAGLX,oBAAC,CAACU,QAAQ,CAACV,oBAAC,CAACY,MAAM;CACpB","ignoreList":[0]} |
@@ -61,3 +61,16 @@ import type { AsyncLocalStorage } from 'async_hooks'; | ||
| asyncApiPromises?: AsyncApiPromises; | ||
| needsSessionShell?: boolean; | ||
| /** | ||
| * DEV-only. | ||
| * Certain APIs have different behavior in static and runtime prerenders. | ||
| * - if `false`, they will follow static semantics | ||
| * - if `true`, they will follow runtime semantics | ||
| * */ | ||
| needsAppShell?: boolean; | ||
| /** | ||
| * DEV-only, mutable. | ||
| * Whether any APIs that resolve in different stages in static and | ||
| * runtime prerenders (i.e. whose behavior varies on `needsAppShell`) | ||
| * were used during this render. | ||
| * */ | ||
| hasIncompatibleShellContent?: boolean; | ||
| cacheSignal?: CacheSignal | null; | ||
@@ -64,0 +77,0 @@ fallbackParams?: OpaqueFallbackRouteParams | null; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/app-render/work-unit-async-storage.external.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport type { DraftModeProvider } from '../async-storage/draft-mode-provider'\nimport type { ResponseCookies } from '../web/spec-extension/cookies'\nimport type { ReadonlyHeaders } from '../web/spec-extension/adapters/headers'\nimport type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'\nimport type { CacheSignal } from './cache-signal'\nimport type { ResponseVaryParamsAccumulator } from './vary-params'\nimport type { DynamicTrackingState } from './dynamic-rendering'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\n\n// Share the instance module in the next-shared layer\nimport { workUnitAsyncStorageInstance } from './work-unit-async-storage-instance' with { 'turbopack-transition': 'next-shared' }\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport type {\n PrerenderResumeDataCache,\n ResumeDataCache,\n} from '../resume-data-cache/resume-data-cache'\nimport type { Params } from '../request/params'\nimport type { ImplicitTags } from '../lib/implicit-tags'\nimport type { WorkStore } from './work-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport type { StagedRenderingController } from './staged-rendering'\nimport type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'\nimport type { InstantValidationSampleTracking } from './instant-validation/instant-samples'\n\nexport type WorkUnitPhase = 'action' | 'render' | 'after'\n\nexport interface CommonWorkUnitStore {\n /** NOTE: Will be mutated as phases change */\n phase: WorkUnitPhase\n readonly implicitTags: ImplicitTags\n}\n\nexport interface RequestStore extends CommonWorkUnitStore {\n readonly type: 'request'\n\n /**\n * The URL of the request. This only specifies the pathname and the search\n * part of the URL.\n */\n readonly url: {\n /**\n * The pathname of the requested URL.\n */\n readonly pathname: string\n\n /**\n * The search part of the requested URL. If the request did not provide a\n * search part, this will be an empty string.\n */\n readonly search: string\n }\n\n readonly headers: ReadonlyHeaders\n // This is mutable because we need to reassign it when transitioning from the action phase to the render phase.\n // The cookie object itself is deliberately read only and thus can't be updated.\n cookies: ReadonlyRequestCookies\n readonly mutableCookies: ResponseCookies\n readonly userspaceMutableCookies: ResponseCookies\n readonly draftMode: DraftModeProvider\n readonly isHmrRefresh?: boolean\n readonly serverComponentsHmrCache?: ServerComponentsHmrCache\n readonly hmrRefreshHash?: string\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this request. Either a mutable\n * `PrerenderResumeDataCache` (e.g. during a dev warmup that fills caches) or\n * an immutable `RenderResumeDataCache` (e.g. when resuming from a postponed\n * state). Narrow via `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n stale?: number\n\n stagedRendering?: StagedRenderingController | null\n asyncApiPromises?: AsyncApiPromises\n needsSessionShell?: boolean // DEV-only\n cacheSignal?: CacheSignal | null\n fallbackParams?: OpaqueFallbackRouteParams | null\n varyParamsAccumulator?: ResponseVaryParamsAccumulator | null\n\n // Only in build-time instant-validation or when rendering\n // a secondary stream for static shell validation\n // We mirror the controller/renderSignal from prerender stores to allow aborting the render\n controller?: AbortController\n renderSignal?: AbortSignal\n\n // Only in build-time instant-validation\n validationSamples?: InstantValidationSamples\n validationSampleTracking?: InstantValidationSampleTracking | null\n\n // DEV-only\n usedDynamic?: boolean\n}\n\nexport type InstantValidationSamples = {\n params: Params | undefined\n searchParams: Record<string, string | string[] | null> | undefined\n}\n\nexport type AsyncApiPromises = {\n cookies: Promise<ReadonlyRequestCookies>\n mutableCookies: Promise<ReadonlyRequestCookies>\n headers: Promise<ReadonlyHeaders>\n sharedParamsParent: Promise<string>\n sharedSearchParamsParent: Promise<string>\n connection: Promise<undefined>\n io: Promise<undefined>\n}\n\n/**\n * The Prerender store is for tracking information related to prerenders.\n *\n * It can be used for both RSC and SSR prerendering and should be scoped as close\n * to the individual `renderTo...` API call as possible. To keep the type simple\n * we don't distinguish between RSC and SSR prerendering explicitly but instead\n * use conditional object properties to infer which mode we are in. For instance cache tracking\n * only needs to happen during the RSC prerender when we are prospectively prerendering\n * to fill all caches.\n */\nexport type PrerenderStoreModern =\n | PrerenderStoreModernClient\n | PrerenderStoreModernServer\n | PrerenderStoreModernRuntime\n | ValidationStoreClient\n\n/** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStoreModern = Exclude<\n PrerenderStoreModern,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface PrerenderStoreModernClient\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender-client'\n}\n\nexport interface ValidationStoreClient extends PrerenderStoreModernCommon {\n readonly type: 'validation-client'\n readonly boundaryState: ValidationBoundaryTracking | null\n validationSamples: InstantValidationSamples | null\n validationSampleTracking: InstantValidationSampleTracking | null\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStoreModernServer\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender'\n\n readonly stagedRendering: StagedRenderingController | null\n\n /**\n * When not null, records whether the render has accessed a data source\n * that hangs during a static prerender but would resolve during a runtime\n * prerender — cookies, headers, fallback params, searchParams, and cache\n * entries excluded only from static prerenders. Call sites go through\n * `trackRuntimeDataAccessed`, which resolves the promise `true` on the\n * first access; it's resolved `false` when the prerender completes without\n * one. Promise resolution is idempotent, so the flag is monotonic with no\n * extra state.\n *\n * The promise is embedded in the RSC payload (`InitialRSCPayload['u']`)\n * so the fulfillment row's stream position records the stage the access\n * happened in; the per-segment prefetch encoding (`collectSegmentData`)\n * extracts it from the page data to tell the client whether a runtime\n * prefetch request could be skipped. Tracking is page-global: an access\n * anywhere in the page poisons all segments (per-segment granularity is\n * recovered downstream for segments whose content is provably complete).\n * Shared between the payload prerender store and the render store because\n * request-data props are created during payload construction, before the\n * render store exists. Null for warmup, route-handler, and error prerender\n * stores.\n */\n readonly runtimeDataAccessed: PromiseWithResolvers<boolean> | null\n\n /**\n * Mutable single-boolean companion to `runtimeDataAccessed`, holding this\n * prerender's `PrefetchHint.ShouldAttemptStaticPrefetch` measurement\n * directly — the value that becomes the route's build-constant hint:\n * starts `true`, and a disqualifying runtime-data access flips it to\n * `false`. Not every access that resolves the promise disqualifies —\n * fallback-param accesses on a fallback-upgradeable route are transient\n * and leave the hint intact (see `trackRuntimeDataAccessed`, which applies\n * the rule at access time using `isFallbackUpgradeable` below). A plain\n * boolean suffices because the hint needs no stream positioning: unlike\n * `runtimeDataAccessed`, whose fulfillment position encodes which stage\n * the access happened in, this is read once after the prerender settles.\n * Held in a cell so it can be shared. Same sharing and null rules as\n * `runtimeDataAccessed`.\n */\n readonly shouldAttemptStaticPrefetch: { current: boolean } | null\n\n /**\n * Whether a fallback shell produced by this prerender could later be\n * upgraded to a concrete prerender (`renderOpts.isFallbackUpgradeable`:\n * at least one fallback param is a `generateStaticParams` candidate).\n * Consulted by `trackRuntimeDataAccessed` to decide whether a\n * fallback-param access disqualifies the static-prefetch hint.\n */\n readonly isFallbackUpgradeable: boolean\n}\n\nexport interface PrerenderStoreModernRuntime\n extends PrerenderStoreModernCommon {\n readonly type: 'prerender-runtime'\n\n /**\n * The staged rendering controller for this prerender. Models stage\n * transitions (Before → Static → Runtime → Dynamic). Null for prospective\n * renders where all stages run without sequencing.\n */\n readonly stagedRendering: StagedRenderingController | null\n readonly isSessionShell: boolean\n\n readonly headers: RequestStore['headers']\n readonly cookies: RequestStore['cookies']\n readonly draftMode: RequestStore['draftMode']\n}\n\nexport interface RevalidateStore {\n // Collected revalidate times and tags for this document during the prerender.\n revalidate: number // in seconds. 0 means dynamic. INFINITE_CACHE and higher means never revalidate.\n expire: number // server expiration time\n stale: number // client expiration time\n tags: null | string[]\n}\n\ninterface PrerenderStoreModernCommon\n extends CommonWorkUnitStore,\n RevalidateStore {\n /**\n * The render signal is aborted after React's `prerender` function is aborted\n * (using a separate signal), which happens in two cases:\n *\n * 1. When all caches are filled during the prospective prerender.\n * 2. When the final prerender is aborted immediately after the prerender was\n * started.\n *\n * It can be used to reject any pending I/O, including hanging promises. This\n * allows React to properly track the async I/O in dev mode, which yields\n * better owner stacks for dynamic validation errors.\n */\n readonly renderSignal: AbortSignal\n\n /**\n * This is the AbortController which represents the boundary between Prerender\n * and dynamic. In some renders it is the same as the controller for React,\n * but in others it is a separate controller. It should be aborted whenever we\n * are no longer in the prerender phase of rendering. Typically this is after\n * one task, or when you call a sync API which requires the prerender to end\n * immediately.\n */\n readonly controller: AbortController\n\n /**\n * When not null, this signal is used to track cache reads during prerendering\n * and to await all cache reads completing, before aborting the prerender.\n */\n readonly cacheSignal: null | CacheSignal\n\n /**\n * During some prerenders we want to track dynamic access.\n */\n readonly dynamicTracking: null | DynamicTrackingState\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this prerender. Either a mutable\n * `PrerenderResumeDataCache` that fills as this prerender runs, or an\n * immutable `RenderResumeDataCache` provided by an earlier phase when the\n * prerender is supposed to read from prefilled caches only (e.g. when\n * prerendering an optional fallback shell). Narrow via\n * `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n /**\n * The HMR refresh hash is only provided in dev mode. It is needed for the dev\n * warmup render to ensure that the cache keys will be identical for the\n * subsequent dynamic render.\n */\n readonly hmrRefreshHash: string | undefined\n\n /**\n * A mutable accumulator for per-segment vary params during prerender. Tracks\n * which route params each segment actually accesses, allowing the client\n * cache to re-key entries for better sharing across different param values.\n */\n readonly varyParamsAccumulator: ResponseVaryParamsAccumulator | null\n}\n\ninterface StaticPrerenderStoreCommon {\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStorePPR\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-ppr'\n readonly rootParams: Params\n readonly dynamicTracking: null | DynamicTrackingState\n\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n\n /**\n * The resume data cache for this prerender. Always mutable in PPR mode.\n */\n resumeDataCache: PrerenderResumeDataCache\n}\n\nexport interface PrerenderStoreLegacy\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-legacy'\n readonly rootParams: Params\n}\n\nexport type PrerenderStore =\n | PrerenderStoreLegacy\n | PrerenderStorePPR\n | PrerenderStoreModern\n\n// /** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStore = Exclude<\n PrerenderStore,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface CommonCacheStore\n extends Omit<CommonWorkUnitStore, 'implicitTags'> {\n /**\n * Whether this work unit will persist the results it consumes in a server\n * cache. This only describes the immediate consumer; it is not inherited\n * from outer scopes.\n */\n readonly consumerWillServerCache: boolean\n /**\n * A cache work unit store might not always have an outer work unit store,\n * from which implicit tags could be inherited.\n */\n readonly implicitTags: ImplicitTags | undefined\n /**\n * Draft mode is only available if the outer work unit store is a request\n * store and draft mode is enabled.\n */\n readonly draftMode: DraftModeProvider | undefined\n}\n\nexport interface CommonUseCacheStore extends CommonCacheStore, RevalidateStore {\n explicitRevalidate: undefined | number // explicit revalidate time from cacheLife() calls\n explicitExpire: undefined | number // server expiration time\n explicitStale: undefined | number // client expiration time\n readonly hmrRefreshHash: string | undefined\n readonly isHmrRefresh: boolean\n readonly serverComponentsHmrCache: ServerComponentsHmrCache | undefined\n readonly forceRevalidate: boolean\n readonly outerOwnerStack: string | undefined\n}\n\nexport interface PublicUseCacheStore extends CommonUseCacheStore {\n readonly type: 'cache'\n\n /**\n * The root params for the current route. `undefined` when nested inside\n * `unstable_cache`, which doesn't carry root params. Currently, `\"use cache\"`\n * inside `unstable_cache` is allowed, so this case must be handled. The error\n * message in `getRootParam` assumes this is the only scenario where\n * `rootParams` is `undefined`.\n */\n readonly rootParams: Params | undefined\n /**\n * Tracks which root param names were read during this cache invocation.\n */\n readonly readRootParamNames: Set<string>\n /**\n * The first nested public `'use cache'` invocation with a dynamic cache life\n * (`revalidate === 0` or `expire < MIN_PRERENDERABLE_EXPIRE`) that propagated\n * up to this store. Used as `cause` for the nested-dynamic cache error so the\n * redbox can point at the inner invocation site, not just the outer one.\n */\n dynamicNestedCacheError: Error | undefined\n}\n\nexport interface PrivateUseCacheStore extends CommonUseCacheStore {\n readonly type: 'private-cache'\n\n readonly headers: ReadonlyHeaders\n readonly cookies: ReadonlyRequestCookies\n\n readonly rootParams: Params\n\n /**\n * DEV-only: Tracks which root param names were read during this cache\n * invocation. In development, private caches are persisted (keyed by the\n * request's cookies and headers), so reads of different root param values\n * must produce different entries.\n */\n readonly readRootParamNames: Set<string> | undefined\n}\n\nexport type UseCacheStore = PublicUseCacheStore | PrivateUseCacheStore\n\nexport interface UnstableCacheStore extends CommonCacheStore {\n readonly type: 'unstable-cache'\n /**\n * Always `undefined` for `unstable_cache` — root params are not available in\n * this context. If a `\"use cache\"` function nested inside `unstable_cache`\n * tries to access root params, it will encounter `undefined` here and throw.\n */\n readonly rootParams: undefined\n}\n\n/**\n * The Cache store is for tracking information inside a \"use cache\" or\n * unstable_cache context. A cache store shadows an outer request store (if\n * present) as a work unit, so that we never accidentally expose any request or\n * page specific information to cache functions, unless it's explicitly desired.\n * For those exceptions, the data is copied over from the request store to the\n * cache store, instead of generally making the request store available to cache\n * functions.\n */\nexport type CacheStore = UseCacheStore | UnstableCacheStore\n\nexport interface GenerateStaticParamsStore extends CommonWorkUnitStore {\n readonly type: 'generate-static-params'\n readonly rootParams: Params\n}\n\nexport type WorkUnitStore =\n | RequestStore\n | CacheStore\n | PrerenderStore\n | GenerateStaticParamsStore\n\nexport function willConsumerServerCache(\n workUnitStore: WorkUnitStore | undefined\n): boolean {\n if (!workUnitStore) {\n return false\n }\n\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n return workUnitStore.consumerWillServerCache\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return true\n case 'request':\n case 'prerender-runtime':\n case 'validation-client':\n case 'generate-static-params':\n return false\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport type WorkUnitAsyncStorage = AsyncLocalStorage<WorkUnitStore>\n\nexport { workUnitAsyncStorageInstance as workUnitAsyncStorage }\n\nexport function throwForMissingRequestStore(callingExpression: string): never {\n throw new Error(\n `\\`${callingExpression}\\` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n}\n\nexport function throwInvariantForMissingStore(): never {\n throw new InvariantError('Expected workUnitAsyncStorage to have a store.')\n}\n\n/**\n * Returns the resume data cache for the given work unit store, regardless of\n * whether it is mutable (`PrerenderResumeDataCache`) or read-only\n * (`RenderResumeDataCache`). Use `resumeDataCache.mutable` to narrow.\n */\nexport function getResumeDataCache(\n workUnitStore: WorkUnitStore\n): ResumeDataCache | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n return workUnitStore.resumeDataCache\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-legacy':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getHmrRefreshHash(\n workUnitStore: WorkUnitStore\n): string | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.hmrRefreshHash\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function isHmrRefresh(workUnitStore: WorkUnitStore): boolean {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.isHmrRefresh ?? false\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return false\n}\n\nexport function getServerComponentsHmrCache(\n workUnitStore: WorkUnitStore\n): ServerComponentsHmrCache | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.serverComponentsHmrCache\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\n/**\n * Returns a draft mode provider only if draft mode is enabled.\n */\nexport function getDraftModeProviderForCacheScope(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): DraftModeProvider | undefined {\n if (workStore.isDraftMode) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.draftMode\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function getStagedRenderingController(\n workUnitStore: WorkUnitStore\n): StagedRenderingController | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender-runtime':\n case 'prerender':\n return workUnitStore.stagedRendering ?? null\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getCacheSignal(\n workUnitStore: WorkUnitStore\n): CacheSignal | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n return workUnitStore.cacheSignal\n case 'request': {\n // In dev, we might fill caches even during a dynamic request.\n if (workUnitStore.cacheSignal) {\n return workUnitStore.cacheSignal\n }\n // fallthrough\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getVaryParamsAccumulator(\n workUnitStore: WorkUnitStore\n): ResponseVaryParamsAccumulator | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime':\n case 'request': {\n return workUnitStore.varyParamsAccumulator ?? null\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'prerender-client':\n case 'validation-client':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n workUnitStore satisfies never\n return null\n }\n}\n"],"names":["getCacheSignal","getDraftModeProviderForCacheScope","getHmrRefreshHash","getResumeDataCache","getServerComponentsHmrCache","getStagedRenderingController","getVaryParamsAccumulator","isHmrRefresh","throwForMissingRequestStore","throwInvariantForMissingStore","willConsumerServerCache","workUnitAsyncStorage","workUnitAsyncStorageInstance","workUnitStore","type","consumerWillServerCache","callingExpression","Error","InvariantError","resumeDataCache","process","env","__NEXT_DEV_SERVER","hmrRefreshHash","undefined","serverComponentsHmrCache","workStore","isDraftMode","draftMode","stagedRendering","cacheSignal","varyParamsAccumulator"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;IAmoBgBA,cAAc;eAAdA;;IAjDAC,iCAAiC;eAAjCA;;IA/EAC,iBAAiB;eAAjBA;;IAtBAC,kBAAkB;eAAlBA;;IAwEAC,2BAA2B;eAA3BA;;IAwDAC,4BAA4B;eAA5BA;;IAkDAC,wBAAwB;eAAxBA;;IAlIAC,YAAY;eAAZA;;IA/DAC,2BAA2B;eAA3BA;;IAMA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AAK;YAAW;gBACd,8DAA8D;gBAC9D,IAAIjB,cAAciB,WAAW,EAAE;oBAC7B,OAAOjB,cAAciB,WAAW;gBAClC;YACA,cAAc;YAChB;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAOjB;IACX;AACF;AAEO,SAASP,yBACdO,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;YAAW;gBACd,OAAOD,cAAckB,qBAAqB,IAAI;YAChD;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACElB;YACA,OAAO;IACX;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/app-render/work-unit-async-storage.external.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport type { DraftModeProvider } from '../async-storage/draft-mode-provider'\nimport type { ResponseCookies } from '../web/spec-extension/cookies'\nimport type { ReadonlyHeaders } from '../web/spec-extension/adapters/headers'\nimport type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'\nimport type { CacheSignal } from './cache-signal'\nimport type { ResponseVaryParamsAccumulator } from './vary-params'\nimport type { DynamicTrackingState } from './dynamic-rendering'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\n\n// Share the instance module in the next-shared layer\nimport { workUnitAsyncStorageInstance } from './work-unit-async-storage-instance' with { 'turbopack-transition': 'next-shared' }\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport type {\n PrerenderResumeDataCache,\n ResumeDataCache,\n} from '../resume-data-cache/resume-data-cache'\nimport type { Params } from '../request/params'\nimport type { ImplicitTags } from '../lib/implicit-tags'\nimport type { WorkStore } from './work-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport type { StagedRenderingController } from './staged-rendering'\nimport type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'\nimport type { InstantValidationSampleTracking } from './instant-validation/instant-samples'\n\nexport type WorkUnitPhase = 'action' | 'render' | 'after'\n\nexport interface CommonWorkUnitStore {\n /** NOTE: Will be mutated as phases change */\n phase: WorkUnitPhase\n readonly implicitTags: ImplicitTags\n}\n\nexport interface RequestStore extends CommonWorkUnitStore {\n readonly type: 'request'\n\n /**\n * The URL of the request. This only specifies the pathname and the search\n * part of the URL.\n */\n readonly url: {\n /**\n * The pathname of the requested URL.\n */\n readonly pathname: string\n\n /**\n * The search part of the requested URL. If the request did not provide a\n * search part, this will be an empty string.\n */\n readonly search: string\n }\n\n readonly headers: ReadonlyHeaders\n // This is mutable because we need to reassign it when transitioning from the action phase to the render phase.\n // The cookie object itself is deliberately read only and thus can't be updated.\n cookies: ReadonlyRequestCookies\n readonly mutableCookies: ResponseCookies\n readonly userspaceMutableCookies: ResponseCookies\n readonly draftMode: DraftModeProvider\n readonly isHmrRefresh?: boolean\n readonly serverComponentsHmrCache?: ServerComponentsHmrCache\n readonly hmrRefreshHash?: string\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this request. Either a mutable\n * `PrerenderResumeDataCache` (e.g. during a dev warmup that fills caches) or\n * an immutable `RenderResumeDataCache` (e.g. when resuming from a postponed\n * state). Narrow via `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n stale?: number\n\n stagedRendering?: StagedRenderingController | null\n asyncApiPromises?: AsyncApiPromises\n\n /**\n * DEV-only.\n * Certain APIs have different behavior in static and runtime prerenders.\n * - if `false`, they will follow static semantics\n * - if `true`, they will follow runtime semantics\n * */\n needsAppShell?: boolean // DEV-only\n /**\n * DEV-only, mutable.\n * Whether any APIs that resolve in different stages in static and\n * runtime prerenders (i.e. whose behavior varies on `needsAppShell`)\n * were used during this render.\n * */\n hasIncompatibleShellContent?: boolean\n\n cacheSignal?: CacheSignal | null\n fallbackParams?: OpaqueFallbackRouteParams | null\n varyParamsAccumulator?: ResponseVaryParamsAccumulator | null\n\n // Only in build-time instant-validation or when rendering\n // a secondary stream for static shell validation\n // We mirror the controller/renderSignal from prerender stores to allow aborting the render\n controller?: AbortController\n renderSignal?: AbortSignal\n\n // Only in build-time instant-validation\n validationSamples?: InstantValidationSamples\n validationSampleTracking?: InstantValidationSampleTracking | null\n\n // DEV-only\n usedDynamic?: boolean\n}\n\nexport type InstantValidationSamples = {\n params: Params | undefined\n searchParams: Record<string, string | string[] | null> | undefined\n}\n\nexport type AsyncApiPromises = {\n cookies: Promise<ReadonlyRequestCookies>\n mutableCookies: Promise<ReadonlyRequestCookies>\n headers: Promise<ReadonlyHeaders>\n sharedParamsParent: Promise<string>\n sharedSearchParamsParent: Promise<string>\n connection: Promise<undefined>\n io: Promise<undefined>\n}\n\n/**\n * The Prerender store is for tracking information related to prerenders.\n *\n * It can be used for both RSC and SSR prerendering and should be scoped as close\n * to the individual `renderTo...` API call as possible. To keep the type simple\n * we don't distinguish between RSC and SSR prerendering explicitly but instead\n * use conditional object properties to infer which mode we are in. For instance cache tracking\n * only needs to happen during the RSC prerender when we are prospectively prerendering\n * to fill all caches.\n */\nexport type PrerenderStoreModern =\n | PrerenderStoreModernClient\n | PrerenderStoreModernServer\n | PrerenderStoreModernRuntime\n | ValidationStoreClient\n\n/** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStoreModern = Exclude<\n PrerenderStoreModern,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface PrerenderStoreModernClient\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender-client'\n}\n\nexport interface ValidationStoreClient extends PrerenderStoreModernCommon {\n readonly type: 'validation-client'\n readonly boundaryState: ValidationBoundaryTracking | null\n validationSamples: InstantValidationSamples | null\n validationSampleTracking: InstantValidationSampleTracking | null\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStoreModernServer\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender'\n\n readonly stagedRendering: StagedRenderingController | null\n\n /**\n * When not null, records whether the render has accessed a data source\n * that hangs during a static prerender but would resolve during a runtime\n * prerender — cookies, headers, fallback params, searchParams, and cache\n * entries excluded only from static prerenders. Call sites go through\n * `trackRuntimeDataAccessed`, which resolves the promise `true` on the\n * first access; it's resolved `false` when the prerender completes without\n * one. Promise resolution is idempotent, so the flag is monotonic with no\n * extra state.\n *\n * The promise is embedded in the RSC payload (`InitialRSCPayload['u']`)\n * so the fulfillment row's stream position records the stage the access\n * happened in; the per-segment prefetch encoding (`collectSegmentData`)\n * extracts it from the page data to tell the client whether a runtime\n * prefetch request could be skipped. Tracking is page-global: an access\n * anywhere in the page poisons all segments (per-segment granularity is\n * recovered downstream for segments whose content is provably complete).\n * Shared between the payload prerender store and the render store because\n * request-data props are created during payload construction, before the\n * render store exists. Null for warmup, route-handler, and error prerender\n * stores.\n */\n readonly runtimeDataAccessed: PromiseWithResolvers<boolean> | null\n\n /**\n * Mutable single-boolean companion to `runtimeDataAccessed`, holding this\n * prerender's `PrefetchHint.ShouldAttemptStaticPrefetch` measurement\n * directly — the value that becomes the route's build-constant hint:\n * starts `true`, and a disqualifying runtime-data access flips it to\n * `false`. Not every access that resolves the promise disqualifies —\n * fallback-param accesses on a fallback-upgradeable route are transient\n * and leave the hint intact (see `trackRuntimeDataAccessed`, which applies\n * the rule at access time using `isFallbackUpgradeable` below). A plain\n * boolean suffices because the hint needs no stream positioning: unlike\n * `runtimeDataAccessed`, whose fulfillment position encodes which stage\n * the access happened in, this is read once after the prerender settles.\n * Held in a cell so it can be shared. Same sharing and null rules as\n * `runtimeDataAccessed`.\n */\n readonly shouldAttemptStaticPrefetch: { current: boolean } | null\n\n /**\n * Whether a fallback shell produced by this prerender could later be\n * upgraded to a concrete prerender (`renderOpts.isFallbackUpgradeable`:\n * at least one fallback param is a `generateStaticParams` candidate).\n * Consulted by `trackRuntimeDataAccessed` to decide whether a\n * fallback-param access disqualifies the static-prefetch hint.\n */\n readonly isFallbackUpgradeable: boolean\n}\n\nexport interface PrerenderStoreModernRuntime\n extends PrerenderStoreModernCommon {\n readonly type: 'prerender-runtime'\n\n /**\n * The staged rendering controller for this prerender. Models stage\n * transitions (Before → Static → Runtime → Dynamic). Null for prospective\n * renders where all stages run without sequencing.\n */\n readonly stagedRendering: StagedRenderingController | null\n readonly isSessionShell: boolean\n\n readonly headers: RequestStore['headers']\n readonly cookies: RequestStore['cookies']\n readonly draftMode: RequestStore['draftMode']\n}\n\nexport interface RevalidateStore {\n // Collected revalidate times and tags for this document during the prerender.\n revalidate: number // in seconds. 0 means dynamic. INFINITE_CACHE and higher means never revalidate.\n expire: number // server expiration time\n stale: number // client expiration time\n tags: null | string[]\n}\n\ninterface PrerenderStoreModernCommon\n extends CommonWorkUnitStore,\n RevalidateStore {\n /**\n * The render signal is aborted after React's `prerender` function is aborted\n * (using a separate signal), which happens in two cases:\n *\n * 1. When all caches are filled during the prospective prerender.\n * 2. When the final prerender is aborted immediately after the prerender was\n * started.\n *\n * It can be used to reject any pending I/O, including hanging promises. This\n * allows React to properly track the async I/O in dev mode, which yields\n * better owner stacks for dynamic validation errors.\n */\n readonly renderSignal: AbortSignal\n\n /**\n * This is the AbortController which represents the boundary between Prerender\n * and dynamic. In some renders it is the same as the controller for React,\n * but in others it is a separate controller. It should be aborted whenever we\n * are no longer in the prerender phase of rendering. Typically this is after\n * one task, or when you call a sync API which requires the prerender to end\n * immediately.\n */\n readonly controller: AbortController\n\n /**\n * When not null, this signal is used to track cache reads during prerendering\n * and to await all cache reads completing, before aborting the prerender.\n */\n readonly cacheSignal: null | CacheSignal\n\n /**\n * During some prerenders we want to track dynamic access.\n */\n readonly dynamicTracking: null | DynamicTrackingState\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this prerender. Either a mutable\n * `PrerenderResumeDataCache` that fills as this prerender runs, or an\n * immutable `RenderResumeDataCache` provided by an earlier phase when the\n * prerender is supposed to read from prefilled caches only (e.g. when\n * prerendering an optional fallback shell). Narrow via\n * `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n /**\n * The HMR refresh hash is only provided in dev mode. It is needed for the dev\n * warmup render to ensure that the cache keys will be identical for the\n * subsequent dynamic render.\n */\n readonly hmrRefreshHash: string | undefined\n\n /**\n * A mutable accumulator for per-segment vary params during prerender. Tracks\n * which route params each segment actually accesses, allowing the client\n * cache to re-key entries for better sharing across different param values.\n */\n readonly varyParamsAccumulator: ResponseVaryParamsAccumulator | null\n}\n\ninterface StaticPrerenderStoreCommon {\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStorePPR\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-ppr'\n readonly rootParams: Params\n readonly dynamicTracking: null | DynamicTrackingState\n\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n\n /**\n * The resume data cache for this prerender. Always mutable in PPR mode.\n */\n resumeDataCache: PrerenderResumeDataCache\n}\n\nexport interface PrerenderStoreLegacy\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-legacy'\n readonly rootParams: Params\n}\n\nexport type PrerenderStore =\n | PrerenderStoreLegacy\n | PrerenderStorePPR\n | PrerenderStoreModern\n\n// /** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStore = Exclude<\n PrerenderStore,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface CommonCacheStore\n extends Omit<CommonWorkUnitStore, 'implicitTags'> {\n /**\n * Whether this work unit will persist the results it consumes in a server\n * cache. This only describes the immediate consumer; it is not inherited\n * from outer scopes.\n */\n readonly consumerWillServerCache: boolean\n /**\n * A cache work unit store might not always have an outer work unit store,\n * from which implicit tags could be inherited.\n */\n readonly implicitTags: ImplicitTags | undefined\n /**\n * Draft mode is only available if the outer work unit store is a request\n * store and draft mode is enabled.\n */\n readonly draftMode: DraftModeProvider | undefined\n}\n\nexport interface CommonUseCacheStore extends CommonCacheStore, RevalidateStore {\n explicitRevalidate: undefined | number // explicit revalidate time from cacheLife() calls\n explicitExpire: undefined | number // server expiration time\n explicitStale: undefined | number // client expiration time\n readonly hmrRefreshHash: string | undefined\n readonly isHmrRefresh: boolean\n readonly serverComponentsHmrCache: ServerComponentsHmrCache | undefined\n readonly forceRevalidate: boolean\n readonly outerOwnerStack: string | undefined\n}\n\nexport interface PublicUseCacheStore extends CommonUseCacheStore {\n readonly type: 'cache'\n\n /**\n * The root params for the current route. `undefined` when nested inside\n * `unstable_cache`, which doesn't carry root params. Currently, `\"use cache\"`\n * inside `unstable_cache` is allowed, so this case must be handled. The error\n * message in `getRootParam` assumes this is the only scenario where\n * `rootParams` is `undefined`.\n */\n readonly rootParams: Params | undefined\n /**\n * Tracks which root param names were read during this cache invocation.\n */\n readonly readRootParamNames: Set<string>\n /**\n * The first nested public `'use cache'` invocation with a dynamic cache life\n * (`revalidate === 0` or `expire < MIN_PRERENDERABLE_EXPIRE`) that propagated\n * up to this store. Used as `cause` for the nested-dynamic cache error so the\n * redbox can point at the inner invocation site, not just the outer one.\n */\n dynamicNestedCacheError: Error | undefined\n}\n\nexport interface PrivateUseCacheStore extends CommonUseCacheStore {\n readonly type: 'private-cache'\n\n readonly headers: ReadonlyHeaders\n readonly cookies: ReadonlyRequestCookies\n\n readonly rootParams: Params\n\n /**\n * DEV-only: Tracks which root param names were read during this cache\n * invocation. In development, private caches are persisted (keyed by the\n * request's cookies and headers), so reads of different root param values\n * must produce different entries.\n */\n readonly readRootParamNames: Set<string> | undefined\n}\n\nexport type UseCacheStore = PublicUseCacheStore | PrivateUseCacheStore\n\nexport interface UnstableCacheStore extends CommonCacheStore {\n readonly type: 'unstable-cache'\n /**\n * Always `undefined` for `unstable_cache` — root params are not available in\n * this context. If a `\"use cache\"` function nested inside `unstable_cache`\n * tries to access root params, it will encounter `undefined` here and throw.\n */\n readonly rootParams: undefined\n}\n\n/**\n * The Cache store is for tracking information inside a \"use cache\" or\n * unstable_cache context. A cache store shadows an outer request store (if\n * present) as a work unit, so that we never accidentally expose any request or\n * page specific information to cache functions, unless it's explicitly desired.\n * For those exceptions, the data is copied over from the request store to the\n * cache store, instead of generally making the request store available to cache\n * functions.\n */\nexport type CacheStore = UseCacheStore | UnstableCacheStore\n\nexport interface GenerateStaticParamsStore extends CommonWorkUnitStore {\n readonly type: 'generate-static-params'\n readonly rootParams: Params\n}\n\nexport type WorkUnitStore =\n | RequestStore\n | CacheStore\n | PrerenderStore\n | GenerateStaticParamsStore\n\nexport function willConsumerServerCache(\n workUnitStore: WorkUnitStore | undefined\n): boolean {\n if (!workUnitStore) {\n return false\n }\n\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n return workUnitStore.consumerWillServerCache\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return true\n case 'request':\n case 'prerender-runtime':\n case 'validation-client':\n case 'generate-static-params':\n return false\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport type WorkUnitAsyncStorage = AsyncLocalStorage<WorkUnitStore>\n\nexport { workUnitAsyncStorageInstance as workUnitAsyncStorage }\n\nexport function throwForMissingRequestStore(callingExpression: string): never {\n throw new Error(\n `\\`${callingExpression}\\` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n}\n\nexport function throwInvariantForMissingStore(): never {\n throw new InvariantError('Expected workUnitAsyncStorage to have a store.')\n}\n\n/**\n * Returns the resume data cache for the given work unit store, regardless of\n * whether it is mutable (`PrerenderResumeDataCache`) or read-only\n * (`RenderResumeDataCache`). Use `resumeDataCache.mutable` to narrow.\n */\nexport function getResumeDataCache(\n workUnitStore: WorkUnitStore\n): ResumeDataCache | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n return workUnitStore.resumeDataCache\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-legacy':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getHmrRefreshHash(\n workUnitStore: WorkUnitStore\n): string | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.hmrRefreshHash\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function isHmrRefresh(workUnitStore: WorkUnitStore): boolean {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.isHmrRefresh ?? false\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return false\n}\n\nexport function getServerComponentsHmrCache(\n workUnitStore: WorkUnitStore\n): ServerComponentsHmrCache | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.serverComponentsHmrCache\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\n/**\n * Returns a draft mode provider only if draft mode is enabled.\n */\nexport function getDraftModeProviderForCacheScope(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): DraftModeProvider | undefined {\n if (workStore.isDraftMode) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.draftMode\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function getStagedRenderingController(\n workUnitStore: WorkUnitStore\n): StagedRenderingController | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender-runtime':\n case 'prerender':\n return workUnitStore.stagedRendering ?? null\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getCacheSignal(\n workUnitStore: WorkUnitStore\n): CacheSignal | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n return workUnitStore.cacheSignal\n case 'request': {\n // In dev, we might fill caches even during a dynamic request.\n if (workUnitStore.cacheSignal) {\n return workUnitStore.cacheSignal\n }\n // fallthrough\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getVaryParamsAccumulator(\n workUnitStore: WorkUnitStore\n): ResponseVaryParamsAccumulator | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime':\n case 'request': {\n return workUnitStore.varyParamsAccumulator ?? null\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'prerender-client':\n case 'validation-client':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n workUnitStore satisfies never\n return null\n }\n}\n"],"names":["getCacheSignal","getDraftModeProviderForCacheScope","getHmrRefreshHash","getResumeDataCache","getServerComponentsHmrCache","getStagedRenderingController","getVaryParamsAccumulator","isHmrRefresh","throwForMissingRequestStore","throwInvariantForMissingStore","willConsumerServerCache","workUnitAsyncStorage","workUnitAsyncStorageInstance","workUnitStore","type","consumerWillServerCache","callingExpression","Error","InvariantError","resumeDataCache","process","env","__NEXT_DEV_SERVER","hmrRefreshHash","undefined","serverComponentsHmrCache","workStore","isDraftMode","draftMode","stagedRendering","cacheSignal","varyParamsAccumulator"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;IAkpBgBA,cAAc;eAAdA;;IAjDAC,iCAAiC;eAAjCA;;IA/EAC,iBAAiB;eAAjBA;;IAtBAC,kBAAkB;eAAlBA;;IAwEAC,2BAA2B;eAA3BA;;IAwDAC,4BAA4B;eAA5BA;;IAkDAC,wBAAwB;eAAxBA;;IAlIAC,YAAY;eAAZA;;IA/DAC,2BAA2B;eAA3BA;;IAMAC,6BAA6B;eAA7BA;;IArCAC,uBAAuB;eAAvBA;;IA6ByBC,oBAAoB;eAApDC,0DAA4B;;;8CAheQ;gCASd;AA0bxB,SAASF,wBACdG,aAAwC;IAExC,IAAI,CAACA,eAAe;QAClB,OAAO;IACT;IAEA,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOD,cAAcE,uBAAuB;QAC9C,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAOF;IACX;AACF;AAMO,SAASL,4BAA4BQ,iBAAyB;IACnE,MAAM,qBAEL,CAFK,IAAIC,MACR,CAAC,EAAE,EAAED,kBAAkB,iHAAiH,CAAC,GADrI,qBAAA;eAAA;oBAAA;sBAAA;IAEN;AACF;AAEO,SAASP;IACd,MAAM,qBAAoE,CAApE,IAAIS,8BAAc,CAAC,mDAAnB,qBAAA;eAAA;oBAAA;sBAAA;IAAmE;AA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AcC,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH,OAAOD,cAAce,SAAS;YAChC,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH;YACF;gBACEf;QACJ;IACF;IAEA,OAAOW;AACT;AAEO,SAASnB,6BACdQ,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOD,cAAcgB,eAAe,IAAI;QAC1C,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAOhB;IACX;AACF;AAEO,SAASb,eACda,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOD,cAAciB,WAAW;QAClC,KAAK;YAAW;gBACd,8DAA8D;gBAC9D,IAAIjB,cAAciB,WAAW,EAAE;oBAC7B,OAAOjB,cAAciB,WAAW;gBAClC;YACA,cAAc;YAChB;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAOjB;IACX;AACF;AAEO,SAASP,yBACdO,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;YAAW;gBACd,OAAOD,cAAckB,qBAAqB,IAAI;YAChD;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACElB;YACA,OAAO;IACX;AACF","ignoreList":[0]} |
@@ -7,4 +7,5 @@ import type { AppPageModule } from './route-modules/app-page/module'; | ||
| clientComponentLoadStart: number; | ||
| clientComponentLoadEnd: number; | ||
| clientComponentLoadTimes: number; | ||
| clientComponentLoadCount: number; | ||
| } | undefined; |
@@ -25,2 +25,3 @@ "use strict"; | ||
| let clientComponentLoadStart = 0; | ||
| let clientComponentLoadEnd = 0; | ||
| let clientComponentLoadTimes = 0; | ||
@@ -42,3 +43,5 @@ let clientComponentLoadCount = 0; | ||
| } finally{ | ||
| clientComponentLoadTimes += performance.now() - startTime; | ||
| const endTime = performance.now(); | ||
| clientComponentLoadEnd = endTime; | ||
| clientComponentLoadTimes += endTime - startTime; | ||
| } | ||
@@ -48,8 +51,14 @@ }, | ||
| const startTime = performance.now(); | ||
| if (clientComponentLoadStart === 0) { | ||
| clientComponentLoadStart = startTime; | ||
| } | ||
| const result = ComponentMod.__next_app__.loadChunk(...args); | ||
| // Avoid wrapping `loadChunk`'s result in an extra promise in case something like React depends on its identity. | ||
| // We only need to know when it's settled. | ||
| result.finally(()=>{ | ||
| clientComponentLoadTimes += performance.now() - startTime; | ||
| }); | ||
| const onSettled = ()=>{ | ||
| const endTime = performance.now(); | ||
| clientComponentLoadEnd = endTime; | ||
| clientComponentLoadTimes += endTime - startTime; | ||
| }; | ||
| result.then(onSettled, onSettled); | ||
| return result; | ||
@@ -62,2 +71,3 @@ } | ||
| clientComponentLoadStart, | ||
| clientComponentLoadEnd, | ||
| clientComponentLoadTimes, | ||
@@ -68,2 +78,3 @@ clientComponentLoadCount | ||
| clientComponentLoadStart = 0; | ||
| clientComponentLoadEnd = 0; | ||
| clientComponentLoadTimes = 0; | ||
@@ -70,0 +81,0 @@ clientComponentLoadCount = 0; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../src/server/client-component-renderer-logger.ts"],"sourcesContent":["import type { AppPageModule } from './route-modules/app-page/module'\n\n// Combined load times for loading client components\nlet clientComponentLoadStart = 0\nlet clientComponentLoadTimes = 0\nlet clientComponentLoadCount = 0\n\nexport function wrapClientComponentLoader(\n ComponentMod: AppPageModule,\n isTracingEnabled: boolean\n): AppPageModule['__next_app__'] {\n if (\n !('performance' in globalThis) ||\n (!process.env.NEXT_OTEL_PERFORMANCE_PREFIX && !isTracingEnabled)\n ) {\n return ComponentMod.__next_app__\n }\n\n return {\n require: (...args) => {\n const startTime = performance.now()\n\n if (clientComponentLoadStart === 0) {\n clientComponentLoadStart = startTime\n }\n\n try {\n clientComponentLoadCount += 1\n return ComponentMod.__next_app__.require(...args)\n } finally {\n clientComponentLoadTimes += performance.now() - startTime\n }\n },\n loadChunk: (...args) => {\n const startTime = performance.now()\n const result = ComponentMod.__next_app__.loadChunk(...args)\n // Avoid wrapping `loadChunk`'s result in an extra promise in case something like React depends on its identity.\n // We only need to know when it's settled.\n result.finally(() => {\n clientComponentLoadTimes += performance.now() - startTime\n })\n return result\n },\n }\n}\n\nexport function getClientComponentLoaderMetrics(\n options: { reset?: boolean } = {}\n) {\n const metrics =\n clientComponentLoadStart === 0\n ? undefined\n : {\n clientComponentLoadStart,\n clientComponentLoadTimes,\n clientComponentLoadCount,\n }\n\n if (options.reset) {\n clientComponentLoadStart = 0\n clientComponentLoadTimes = 0\n clientComponentLoadCount = 0\n }\n\n return metrics\n}\n"],"names":["getClientComponentLoaderMetrics","wrapClientComponentLoader","clientComponentLoadStart","clientComponentLoadTimes","clientComponentLoadCount","ComponentMod","isTracingEnabled","globalThis","process","env","NEXT_OTEL_PERFORMANCE_PREFIX","__next_app__","require","args","startTime","performance","now","loadChunk","result","finally","options","metrics","undefined","reset"],"mappings":";;;;;;;;;;;;;;;IA8CgBA,+BAA+B;eAA/BA;;IAvCAC,yBAAyB;eAAzBA;;;AALhB,oDAAoD;AACpD,IAAIC,2BAA2B;AAC/B,IAAIC,2BAA2B;AAC/B,IAAIC,2BAA2B;AAExB,SAASH,0BACdI,YAA2B,EAC3BC,gBAAyB;IAEzB,IACE,CAAE,CAAA,iBAAiBC,UAAS,KAC3B,CAACC,QAAQC,GAAG,CAACC,4BAA4B,IAAI,CAACJ,kBAC/C;QACA,OAAOD,aAAaM,YAAY;IAClC;IAEA,OAAO;QACLC,SAAS,CAAC,GAAGC;YACX,MAAMC,YAAYC,YAAYC,GAAG;YAEjC,IAAId,6BAA6B,GAAG;gBAClCA,2BAA2BY;YAC7B;YAEA,IAAI;gBACFV,4BAA4B;gBAC5B,OAAOC,aAAaM,YAAY,CAACC,OAAO,IAAIC;YAC9C,SAAU;gBACRV,4BAA4BY,YAAYC,GAAG,KAAKF;YAClD;QACF;QACAG,WAAW,CAAC,GAAGJ;YACb,MAAMC,YAAYC,YAAYC,GAAG;YACjC,MAAME,SAASb,aAAaM,YAAY,CAACM,SAAS,IAAIJ;YACtD,gHAAgH;YAChH,0CAA0C;YAC1CK,OAAOC,OAAO,CAAC;gBACbhB,4BAA4BY,YAAYC,GAAG,KAAKF;YAClD;YACA,OAAOI;QACT;IACF;AACF;AAEO,SAASlB,gCACdoB,UAA+B,CAAC,CAAC;IAEjC,MAAMC,UACJnB,6BAA6B,IACzBoB,YACA;QACEpB;QACAC;QACAC;IACF;IAEN,IAAIgB,QAAQG,KAAK,EAAE;QACjBrB,2BAA2B;QAC3BC,2BAA2B;QAC3BC,2BAA2B;IAC7B;IAEA,OAAOiB;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../src/server/client-component-renderer-logger.ts"],"sourcesContent":["import type { AppPageModule } from './route-modules/app-page/module'\n\n// Combined load times for loading client components\nlet clientComponentLoadStart = 0\nlet clientComponentLoadEnd = 0\nlet clientComponentLoadTimes = 0\nlet clientComponentLoadCount = 0\n\nexport function wrapClientComponentLoader(\n ComponentMod: AppPageModule,\n isTracingEnabled: boolean\n): AppPageModule['__next_app__'] {\n if (\n !('performance' in globalThis) ||\n (!process.env.NEXT_OTEL_PERFORMANCE_PREFIX && !isTracingEnabled)\n ) {\n return ComponentMod.__next_app__\n }\n\n return {\n require: (...args) => {\n const startTime = performance.now()\n\n if (clientComponentLoadStart === 0) {\n clientComponentLoadStart = startTime\n }\n\n try {\n clientComponentLoadCount += 1\n return ComponentMod.__next_app__.require(...args)\n } finally {\n const endTime = performance.now()\n clientComponentLoadEnd = endTime\n clientComponentLoadTimes += endTime - startTime\n }\n },\n loadChunk: (...args) => {\n const startTime = performance.now()\n\n if (clientComponentLoadStart === 0) {\n clientComponentLoadStart = startTime\n }\n\n const result = ComponentMod.__next_app__.loadChunk(...args)\n // Avoid wrapping `loadChunk`'s result in an extra promise in case something like React depends on its identity.\n // We only need to know when it's settled.\n const onSettled = () => {\n const endTime = performance.now()\n clientComponentLoadEnd = endTime\n clientComponentLoadTimes += endTime - startTime\n }\n result.then(onSettled, onSettled)\n return result\n },\n }\n}\n\nexport function getClientComponentLoaderMetrics(\n options: { reset?: boolean } = {}\n) {\n const metrics =\n clientComponentLoadStart === 0\n ? undefined\n : {\n clientComponentLoadStart,\n clientComponentLoadEnd,\n clientComponentLoadTimes,\n clientComponentLoadCount,\n }\n\n if (options.reset) {\n clientComponentLoadStart = 0\n clientComponentLoadEnd = 0\n clientComponentLoadTimes = 0\n clientComponentLoadCount = 0\n }\n\n return metrics\n}\n"],"names":["getClientComponentLoaderMetrics","wrapClientComponentLoader","clientComponentLoadStart","clientComponentLoadEnd","clientComponentLoadTimes","clientComponentLoadCount","ComponentMod","isTracingEnabled","globalThis","process","env","NEXT_OTEL_PERFORMANCE_PREFIX","__next_app__","require","args","startTime","performance","now","endTime","loadChunk","result","onSettled","then","options","metrics","undefined","reset"],"mappings":";;;;;;;;;;;;;;;IAyDgBA,+BAA+B;eAA/BA;;IAjDAC,yBAAyB;eAAzBA;;;AANhB,oDAAoD;AACpD,IAAIC,2BAA2B;AAC/B,IAAIC,yBAAyB;AAC7B,IAAIC,2BAA2B;AAC/B,IAAIC,2BAA2B;AAExB,SAASJ,0BACdK,YAA2B,EAC3BC,gBAAyB;IAEzB,IACE,CAAE,CAAA,iBAAiBC,UAAS,KAC3B,CAACC,QAAQC,GAAG,CAACC,4BAA4B,IAAI,CAACJ,kBAC/C;QACA,OAAOD,aAAaM,YAAY;IAClC;IAEA,OAAO;QACLC,SAAS,CAAC,GAAGC;YACX,MAAMC,YAAYC,YAAYC,GAAG;YAEjC,IAAIf,6BAA6B,GAAG;gBAClCA,2BAA2Ba;YAC7B;YAEA,IAAI;gBACFV,4BAA4B;gBAC5B,OAAOC,aAAaM,YAAY,CAACC,OAAO,IAAIC;YAC9C,SAAU;gBACR,MAAMI,UAAUF,YAAYC,GAAG;gBAC/Bd,yBAAyBe;gBACzBd,4BAA4Bc,UAAUH;YACxC;QACF;QACAI,WAAW,CAAC,GAAGL;YACb,MAAMC,YAAYC,YAAYC,GAAG;YAEjC,IAAIf,6BAA6B,GAAG;gBAClCA,2BAA2Ba;YAC7B;YAEA,MAAMK,SAASd,aAAaM,YAAY,CAACO,SAAS,IAAIL;YACtD,gHAAgH;YAChH,0CAA0C;YAC1C,MAAMO,YAAY;gBAChB,MAAMH,UAAUF,YAAYC,GAAG;gBAC/Bd,yBAAyBe;gBACzBd,4BAA4Bc,UAAUH;YACxC;YACAK,OAAOE,IAAI,CAACD,WAAWA;YACvB,OAAOD;QACT;IACF;AACF;AAEO,SAASpB,gCACduB,UAA+B,CAAC,CAAC;IAEjC,MAAMC,UACJtB,6BAA6B,IACzBuB,YACA;QACEvB;QACAC;QACAC;QACAC;IACF;IAEN,IAAIkB,QAAQG,KAAK,EAAE;QACjBxB,2BAA2B;QAC3BC,yBAAyB;QACzBC,2BAA2B;QAC3BC,2BAA2B;IAC7B;IAEA,OAAOmB;AACT","ignoreList":[0]} |
| import type { NextConfigComplete } from '../config-shared'; | ||
| import type { NodeJsPartialHmrUpdate } from '../../build/swc/types'; | ||
| interface InstallOptions { | ||
@@ -9,2 +10,20 @@ distDir: string; | ||
| /** | ||
| * One change the dev server made to its own module state — the modules it has | ||
| * loaded, and the manifest caches that describe them. | ||
| * | ||
| * The worker holds the same state, seeded from the same build output, and | ||
| * replays every change the dev server reports, so its state is the dev server's | ||
| * state by construction. | ||
| */ | ||
| type DevModuleStateChange = { | ||
| type: 'apply'; | ||
| update: NodeJsPartialHmrUpdate; | ||
| } | { | ||
| type: 'invalidate'; | ||
| filePaths: string[]; | ||
| evictModules: boolean; | ||
| }; | ||
| export declare function mirrorModuleStateToDevValidationWorker(change: DevModuleStateChange): void; | ||
| export declare function dropDevValidationWorker(): void; | ||
| /** | ||
| * Wire up the dev-server's validation worker: register the HMR teardown | ||
@@ -11,0 +30,0 @@ * listener and install the hook that `runDevValidationInBackground` calls once |
@@ -5,6 +5,22 @@ "use strict"; | ||
| }); | ||
| Object.defineProperty(exports, "installDevValidationWorker", { | ||
| enumerable: true, | ||
| get: function() { | ||
| 0 && (module.exports = { | ||
| dropDevValidationWorker: null, | ||
| installDevValidationWorker: null, | ||
| mirrorModuleStateToDevValidationWorker: null | ||
| }); | ||
| function _export(target, all) { | ||
| for(var name in all)Object.defineProperty(target, name, { | ||
| enumerable: true, | ||
| get: all[name] | ||
| }); | ||
| } | ||
| _export(exports, { | ||
| dropDevValidationWorker: function() { | ||
| return dropDevValidationWorker; | ||
| }, | ||
| installDevValidationWorker: function() { | ||
| return installDevValidationWorker; | ||
| }, | ||
| mirrorModuleStateToDevValidationWorker: function() { | ||
| return mirrorModuleStateToDevValidationWorker; | ||
| } | ||
@@ -17,2 +33,26 @@ }); | ||
| const _needsexperimentalreact = require("../../lib/needs-experimental-react"); | ||
| /** | ||
| * Replays a change the dev server made to its own module state in the | ||
| * validation worker. Installed alongside the worker, so it is absent when no | ||
| * worker runs (`experimental.devValidationWorker: false`, or Webpack). | ||
| */ let mirrorModuleState; | ||
| /** | ||
| * Drops the validation worker. Called when the dev server cannot repair its own | ||
| * module state in place and re-evaluates every module from disk, which the | ||
| * worker matches by starting over: the next validation spawns a worker that | ||
| * loads the current build output. | ||
| * | ||
| * A worker dropped on its own, by a failed replay or a crash, is the one case | ||
| * where the two can diverge. The dev server keeps the modules it evaluated from | ||
| * earlier updates, and a worker spawned afterwards has no way to obtain those | ||
| * scripts, so frames naming them stay unresolved until those modules change | ||
| * again. The validation itself is unaffected, because the worker loads the | ||
| * current code from disk. | ||
| */ let dropWorker; | ||
| function mirrorModuleStateToDevValidationWorker(change) { | ||
| mirrorModuleState == null ? void 0 : mirrorModuleState(change); | ||
| } | ||
| function dropDevValidationWorker() { | ||
| dropWorker == null ? void 0 : dropWorker(); | ||
| } | ||
| function installDevValidationWorker(options) { | ||
@@ -31,4 +71,35 @@ const { distDir, buildId, deploymentId, nextConfig } = options; | ||
| // across independent requests (e.g. multiple tabs) show a validation-latency | ||
| // tail. | ||
| // tail. Raising it means `mirrorChange` has to reach every worker instead of | ||
| // whichever one the pool hands the call to, and the ordering it relies on | ||
| // holds per worker rather than across them. | ||
| let pool; | ||
| const mirrorChange = (change)=>{ | ||
| const current = pool; | ||
| if (!current) { | ||
| // No worker to keep current, and nothing to replay into a later one: the | ||
| // compilation that produced this change also wrote the updated chunk to | ||
| // disk, so a worker spawning after it reads the current code through | ||
| // `loadComponents`. Evaluating the update is what an isolate that is | ||
| // already running needs, not what a new one does. | ||
| return; | ||
| } | ||
| // The worker runs one call at a time, in the order the calls were made | ||
| // (see `numWorkers` below), so this is replayed before any validation | ||
| // requested after it, and never in the middle of one. That ordering is by | ||
| // call time, which is why the call is made here, as the change arrives, | ||
| // rather than deferred onto a queue of our own. A validation already | ||
| // queued runs first, which is what its render needs: it was produced | ||
| // before this change. The dev server does not hold its own updates back | ||
| // for a validation running in process either. | ||
| const replayed = change.type === 'invalidate' ? current.invalidateCaches(change.filePaths, change.evictModules) : current.applyHmrUpdate(change.update).then(async (outcome)=>{ | ||
| if (outcome === 'failed') { | ||
| await tearDownPool(); | ||
| } | ||
| }); | ||
| void replayed.catch(async ()=>{ | ||
| // A replay that failed leaves the worker's state unknown, so it is | ||
| // dropped rather than trusted. | ||
| await tearDownPool(); | ||
| }); | ||
| }; | ||
| const getPool = ()=>{ | ||
@@ -69,3 +140,5 @@ if (pool) { | ||
| exposedMethods: [ | ||
| 'runDevValidation' | ||
| 'runDevValidation', | ||
| 'applyHmrUpdate', | ||
| 'invalidateCaches' | ||
| ], | ||
@@ -147,9 +220,15 @@ forkOptions: { | ||
| }; | ||
| // The dev server can't reach into the worker to clear its `require.cache` or | ||
| // manifest caches, so we drop the worker whenever the parent's caches are | ||
| // invalidated (HMR, route recompile). The next validation lazy-spawns a fresh | ||
| // worker with empty caches. | ||
| (0, _requirecache.onCacheInvalidation)(()=>{ | ||
| // The dev server just cleared these paths from its own `require.cache` and | ||
| // manifest caches. The worker clears them from its copies. | ||
| (0, _requirecache.onCacheInvalidation)((filePaths)=>{ | ||
| mirrorChange({ | ||
| type: 'invalidate', | ||
| filePaths, | ||
| evictModules: true | ||
| }); | ||
| }); | ||
| mirrorModuleState = mirrorChange; | ||
| dropWorker = ()=>{ | ||
| void tearDownPool(); | ||
| }); | ||
| }; | ||
| (0, _devvalidationworkerglobals.setDevValidationWorker)(runValidation); | ||
@@ -156,0 +235,0 @@ } |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/dev/dev-validation-worker-pool.ts"],"sourcesContent":["import type { NextConfigComplete } from '../config-shared'\nimport type { runDevValidation } from './dev-validation-worker'\nimport type {\n DevValidationSnapshot,\n DevValidationWorkerMessage,\n DevValidationWorkerResult,\n} from '../app-render/dev-validation-worker-globals'\n\nimport { Worker } from 'next/dist/compiled/jest-worker'\nimport { setDevValidationWorker } from '../app-render/dev-validation-worker-globals'\nimport { onCacheInvalidation } from './require-cache'\nimport { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'\nimport { needsExperimentalReact } from '../../lib/needs-experimental-react'\n\ninterface InstallOptions {\n distDir: string\n buildId: string\n deploymentId: string\n nextConfig: NextConfigComplete\n}\n\ntype ValidationPool = { [key: string]: any } & {\n runDevValidation: typeof runDevValidation\n}\n\n/**\n * Wire up the dev-server's validation worker: register the HMR teardown\n * listener and install the hook that `runDevValidationInBackground` calls once\n * a render has settled. The worker thread is spawned lazily, so nothing is\n * created until the first navigation actually validates.\n */\nexport function installDevValidationWorker(options: InstallOptions): void {\n const { distDir, buildId, deploymentId, nextConfig } = options\n\n // A single worker, not a pool. Validation for one navigation runs its depth\n // loop sequentially, and a newer navigation supersedes the previous one\n // (aborting it mid-run) rather than running concurrently, so there's no\n // per-request fan-out to parallelize (unlike the `'use cache'` probe, where\n // one request fans out into concurrent probes). One worker already frees the\n // main thread, which is the whole point; it also keeps each request's CLI\n // marker block contiguous in the piped output. Torn down on HMR (stale user\n // modules) and on crash.\n //\n // TODO(dev-validation-worker): raise `numWorkers` if concurrent navigations\n // across independent requests (e.g. multiple tabs) show a validation-latency\n // tail.\n let pool: ValidationPool | undefined\n\n const getPool = (): ValidationPool => {\n if (pool) {\n return pool\n }\n // Strip `--inspect` from any inherited `NODE_OPTIONS` so the worker doesn't\n // fight the parent for the same debug port.\n const workerNodeOptions = getFormattedNodeOptionsWithoutInspect()\n\n // The worker is shipped as four pre-bundled dev-only artifacts\n // ({webpack,turbopack} × {stable,experimental}), one per combination of the\n // user's bundler and vendored React channel. Pick the matching artifact\n // from runtime env so the worker stays in lockstep with the user's app\n // bundle. `needsExperimentalReact` is the same predicate `define-env.ts`\n // uses to wire `__NEXT_EXPERIMENTAL_REACT`.\n const turbo = process.env.TURBOPACK ? '-turbo' : ''\n const channel = needsExperimentalReact(nextConfig) ? '-experimental' : ''\n const workerPath = require.resolve(\n `next/dist/compiled/next-server/dev-validation-worker${turbo}${channel}.runtime.dev.js`\n )\n\n const worker = new Worker(workerPath, {\n maxRetries: 0,\n numWorkers: 1,\n // Always worker-threads, regardless of `experimental.workerThreads`.\n // Unlike the `'use cache'` probe (which follows the flag), validation has\n // no reason to prefer a child process: it doesn't need process-level\n // isolation (a worker thread already has its own V8 heap and module\n // registry, so the reloaded route is isolated from the main thread), and\n // threads let a superseded validation be aborted mid-run through a shared\n // `SharedArrayBuffer`, which a separate process can't receive. Threads\n // also carry the transported Flight bytes as typed arrays via structured\n // clone, with no JSON round-trip to corrupt them.\n enableWorkerThreads: true,\n // Listing the method explicitly tells jest-worker to skip the discovery\n // `require()` it would otherwise do in the parent process to enumerate\n // the module's exports. This worker's top-level imports (`require-hook`,\n // `node-environment`) run runtime setup meant only for the isolated\n // worker thread, so they must not be evaluated in the parent.\n exposedMethods: ['runDevValidation'],\n forkOptions: {\n env: {\n ...process.env,\n NODE_OPTIONS: workerNodeOptions,\n },\n },\n }) as Worker & ValidationPool\n worker.getStdout().pipe(process.stdout)\n worker.getStderr().pipe(process.stderr)\n pool = worker\n return worker\n }\n\n const tearDownPool = async (): Promise<void> => {\n const current = pool\n if (!current) {\n return\n }\n pool = undefined\n await current.end().catch(() => {\n // The worker thread exits on its own once its work settles; a failed\n // `.end()` here just means we couldn't wait for it cleanly.\n })\n }\n\n const runValidation = async (\n snapshot: DevValidationSnapshot,\n validationAbortSignal: AbortSignal\n ): Promise<DevValidationWorkerResult> => {\n let activePool: ValidationPool\n try {\n activePool = getPool()\n } catch {\n return null\n }\n\n const message: DevValidationWorkerMessage = {\n ...snapshot,\n distDir,\n buildId,\n deploymentId,\n nextConfigSerializable: {\n httpAgentOptions: nextConfig.httpAgentOptions,\n cacheLifeProfiles: nextConfig.cacheLife,\n useCacheTimeout: nextConfig.experimental.useCacheTimeout,\n staticPageGenerationTimeout: nextConfig.staticPageGenerationTimeout,\n },\n }\n\n // The worker runs as a thread (see `enableWorkerThreads` above), so an\n // abort reaches it through a one-slot shared flag rather than the abort\n // signal directly (a signal can't cross the thread boundary). Mirror an\n // abort of `validationAbortSignal` into the buffer and wake the worker's\n // `Atomics.waitAsync` on it, so it aborts the in-flight run at its next\n // depth boundary.\n const abortBuffer = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)\n const abortFlag = new Int32Array(abortBuffer)\n const propagateAbort = () => {\n Atomics.store(abortFlag, 0, 1)\n Atomics.notify(abortFlag, 0)\n }\n if (validationAbortSignal.aborted) {\n propagateAbort()\n } else {\n validationAbortSignal.addEventListener('abort', propagateAbort, {\n once: true,\n })\n }\n\n try {\n return await activePool.runDevValidation(message, abortBuffer)\n } catch {\n // Worker crash or IPC error: tear down so the next validation starts\n // fresh. The main thread treats a missing result as \"nothing to deliver.\"\n await tearDownPool()\n return null\n } finally {\n // `once` only auto-removes the listener if it fired, so remove it\n // explicitly to bound its lifetime to this run when validation completed\n // without being superseded.\n validationAbortSignal.removeEventListener('abort', propagateAbort)\n }\n }\n\n // The dev server can't reach into the worker to clear its `require.cache` or\n // manifest caches, so we drop the worker whenever the parent's caches are\n // invalidated (HMR, route recompile). The next validation lazy-spawns a fresh\n // worker with empty caches.\n onCacheInvalidation(() => {\n void tearDownPool()\n })\n\n setDevValidationWorker(runValidation)\n}\n"],"names":["installDevValidationWorker","options","distDir","buildId","deploymentId","nextConfig","pool","getPool","workerNodeOptions","getFormattedNodeOptionsWithoutInspect","turbo","process","env","TURBOPACK","channel","needsExperimentalReact","workerPath","require","resolve","worker","Worker","maxRetries","numWorkers","enableWorkerThreads","exposedMethods","forkOptions","NODE_OPTIONS","getStdout","pipe","stdout","getStderr","stderr","tearDownPool","current","undefined","end","catch","runValidation","snapshot","validationAbortSignal","activePool","message","nextConfigSerializable","httpAgentOptions","cacheLifeProfiles","cacheLife","useCacheTimeout","experimental","staticPageGenerationTimeout","abortBuffer","SharedArrayBuffer","Int32Array","BYTES_PER_ELEMENT","abortFlag","propagateAbort","Atomics","store","notify","aborted","addEventListener","once","runDevValidation","removeEventListener","onCacheInvalidation","setDevValidationWorker"],"mappings":";;;;+BA+BgBA;;;eAAAA;;;4BAvBO;4CACgB;8BACH;uBACkB;wCACf;AAmBhC,SAASA,2BAA2BC,OAAuB;IAChE,MAAM,EAAEC,OAAO,EAAEC,OAAO,EAAEC,YAAY,EAAEC,UAAU,EAAE,GAAGJ;IAEvD,4EAA4E;IAC5E,wEAAwE;IACxE,wEAAwE;IACxE,4EAA4E;IAC5E,6EAA6E;IAC7E,0EAA0E;IAC1E,4EAA4E;IAC5E,yBAAyB;IACzB,EAAE;IACF,4EAA4E;IAC5E,6EAA6E;IAC7E,QAAQ;IACR,IAAIK;IAEJ,MAAMC,UAAU;QACd,IAAID,MAAM;YACR,OAAOA;QACT;QACA,4EAA4E;QAC5E,4CAA4C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YACAsC,wBAAwB;gBACtBC,kBAAkBtC,WAAWsC,gBAAgB;gBAC7CC,mBAAmBvC,WAAWwC,SAAS;gBACvCC,iBAAiBzC,WAAW0C,YAAY,CAACD,eAAe;gBACxDE,6BAA6B3C,WAAW2C,2BAA2B;YACrE;QACF;QAEA,uEAAuE;QACvE,wEAAwE;QACxE,wEAAwE;QACxE,yEAAyE;QACzE,wEAAwE;QACxE,kBAAkB;QAClB,MAAMC,cAAc,IAAIC,kBAAkBC,WAAWC,iBAAiB;QACtE,MAAMC,YAAY,IAAIF,WAAWF;QACjC,MAAMK,iBAAiB;YACrBC,QAAQC,KAAK,CAACH,WAAW,GAAG;YAC5BE,QAAQE,MAAM,CAACJ,WAAW;QAC5B;QACA,IAAId,sBAAsBmB,OAAO,EAAE;YACjCJ;QACF,OAAO;YACLf,sBAAsBoB,gBAAgB,CAAC,SAASL,gBAAgB;gBAC9DM,MAAM;YACR;QACF;QAEA,IAAI;YACF,OAAO,MAAMpB,WAAWqB,gBAAgB,CAACpB,SAASQ;QACpD,EAAE,OAAM;YACN,qEAAqE;YACrE,0EAA0E;YAC1E,MAAMjB;YACN,OAAO;QACT,SAAU;YACR,kEAAkE;YAClE,yEAAyE;YACzE,4BAA4B;YAC5BO,sBAAsBuB,mBAAmB,CAAC,SAASR;QACrD;IACF;IAEA,6EAA6E;IAC7E,0EAA0E;IAC1E,8EAA8E;IAC9E,4BAA4B;IAC5BS,IAAAA,iCAAmB,EAAC;QAClB,KAAK/B;IACP;IAEAgC,IAAAA,kDAAsB,EAAC3B;AACzB","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/dev/dev-validation-worker-pool.ts"],"sourcesContent":["import type { NextConfigComplete } from '../config-shared'\nimport type { NodeJsPartialHmrUpdate } from '../../build/swc/types'\nimport type {\n applyHmrUpdate,\n invalidateCaches,\n runDevValidation,\n} from './dev-validation-worker'\nimport type {\n DevValidationSnapshot,\n DevValidationWorkerMessage,\n DevValidationWorkerResult,\n} from '../app-render/dev-validation-worker-globals'\n\nimport { Worker } from 'next/dist/compiled/jest-worker'\nimport { setDevValidationWorker } from '../app-render/dev-validation-worker-globals'\nimport { onCacheInvalidation } from './require-cache'\nimport { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'\nimport { needsExperimentalReact } from '../../lib/needs-experimental-react'\n\ninterface InstallOptions {\n distDir: string\n buildId: string\n deploymentId: string\n nextConfig: NextConfigComplete\n}\n\ntype ValidationPool = { [key: string]: any } & {\n runDevValidation: typeof runDevValidation\n applyHmrUpdate: typeof applyHmrUpdate\n invalidateCaches: typeof invalidateCaches\n}\n\n/**\n * One change the dev server made to its own module state — the modules it has\n * loaded, and the manifest caches that describe them.\n *\n * The worker holds the same state, seeded from the same build output, and\n * replays every change the dev server reports, so its state is the dev server's\n * state by construction.\n */\ntype DevModuleStateChange =\n | { type: 'apply'; update: NodeJsPartialHmrUpdate }\n | { type: 'invalidate'; filePaths: string[]; evictModules: boolean }\n\n/**\n * Replays a change the dev server made to its own module state in the\n * validation worker. Installed alongside the worker, so it is absent when no\n * worker runs (`experimental.devValidationWorker: false`, or Webpack).\n */\nlet mirrorModuleState: ((change: DevModuleStateChange) => void) | undefined\n\n/**\n * Drops the validation worker. Called when the dev server cannot repair its own\n * module state in place and re-evaluates every module from disk, which the\n * worker matches by starting over: the next validation spawns a worker that\n * loads the current build output.\n *\n * A worker dropped on its own, by a failed replay or a crash, is the one case\n * where the two can diverge. The dev server keeps the modules it evaluated from\n * earlier updates, and a worker spawned afterwards has no way to obtain those\n * scripts, so frames naming them stay unresolved until those modules change\n * again. The validation itself is unaffected, because the worker loads the\n * current code from disk.\n */\nlet dropWorker: (() => void) | undefined\n\nexport function mirrorModuleStateToDevValidationWorker(\n change: DevModuleStateChange\n): void {\n mirrorModuleState?.(change)\n}\n\nexport function dropDevValidationWorker(): void {\n dropWorker?.()\n}\n\n/**\n * Wire up the dev-server's validation worker: register the HMR teardown\n * listener and install the hook that `runDevValidationInBackground` calls once\n * a render has settled. The worker thread is spawned lazily, so nothing is\n * created until the first navigation actually validates.\n */\nexport function installDevValidationWorker(options: InstallOptions): void {\n const { distDir, buildId, deploymentId, nextConfig } = options\n\n // A single worker, not a pool. Validation for one navigation runs its depth\n // loop sequentially, and a newer navigation supersedes the previous one\n // (aborting it mid-run) rather than running concurrently, so there's no\n // per-request fan-out to parallelize (unlike the `'use cache'` probe, where\n // one request fans out into concurrent probes). One worker already frees the\n // main thread, which is the whole point; it also keeps each request's CLI\n // marker block contiguous in the piped output. Torn down on HMR (stale user\n // modules) and on crash.\n //\n // TODO(dev-validation-worker): raise `numWorkers` if concurrent navigations\n // across independent requests (e.g. multiple tabs) show a validation-latency\n // tail. Raising it means `mirrorChange` has to reach every worker instead of\n // whichever one the pool hands the call to, and the ordering it relies on\n // holds per worker rather than across them.\n let pool: ValidationPool | undefined\n\n const mirrorChange = (change: DevModuleStateChange): void => {\n const current = pool\n if (!current) {\n // No worker to keep current, and nothing to replay into a later one: the\n // compilation that produced this change also wrote the updated chunk to\n // disk, so a worker spawning after it reads the current code through\n // `loadComponents`. Evaluating the update is what an isolate that is\n // already running needs, not what a new one does.\n return\n }\n\n // The worker runs one call at a time, in the order the calls were made\n // (see `numWorkers` below), so this is replayed before any validation\n // requested after it, and never in the middle of one. That ordering is by\n // call time, which is why the call is made here, as the change arrives,\n // rather than deferred onto a queue of our own. A validation already\n // queued runs first, which is what its render needs: it was produced\n // before this change. The dev server does not hold its own updates back\n // for a validation running in process either.\n const replayed =\n change.type === 'invalidate'\n ? current.invalidateCaches(change.filePaths, change.evictModules)\n : current.applyHmrUpdate(change.update).then(async (outcome) => {\n if (outcome === 'failed') {\n await tearDownPool()\n }\n })\n\n void replayed.catch(async () => {\n // A replay that failed leaves the worker's state unknown, so it is\n // dropped rather than trusted.\n await tearDownPool()\n })\n }\n\n const getPool = (): ValidationPool => {\n if (pool) {\n return pool\n }\n // Strip `--inspect` from any inherited `NODE_OPTIONS` so the worker doesn't\n // fight the parent for the same debug port.\n const workerNodeOptions = getFormattedNodeOptionsWithoutInspect()\n\n // The worker is shipped as four pre-bundled dev-only artifacts\n // ({webpack,turbopack} × {stable,experimental}), one per combination of the\n // user's bundler and vendored React channel. Pick the matching artifact\n // from runtime env so the worker stays in lockstep with the user's app\n // bundle. `needsExperimentalReact` is the same predicate `define-env.ts`\n // uses to wire `__NEXT_EXPERIMENTAL_REACT`.\n const turbo = process.env.TURBOPACK ? '-turbo' : ''\n const channel = needsExperimentalReact(nextConfig) ? '-experimental' : ''\n const workerPath = require.resolve(\n `next/dist/compiled/next-server/dev-validation-worker${turbo}${channel}.runtime.dev.js`\n )\n\n const worker = new Worker(workerPath, {\n maxRetries: 0,\n numWorkers: 1,\n // Always worker-threads, regardless of `experimental.workerThreads`.\n // Unlike the `'use cache'` probe (which follows the flag), validation has\n // no reason to prefer a child process: it doesn't need process-level\n // isolation (a worker thread already has its own V8 heap and module\n // registry, so the reloaded route is isolated from the main thread), and\n // threads let a superseded validation be aborted mid-run through a shared\n // `SharedArrayBuffer`, which a separate process can't receive. Threads\n // also carry the transported Flight bytes as typed arrays via structured\n // clone, with no JSON round-trip to corrupt them.\n enableWorkerThreads: true,\n // Listing the method explicitly tells jest-worker to skip the discovery\n // `require()` it would otherwise do in the parent process to enumerate\n // the module's exports. This worker's top-level imports (`require-hook`,\n // `node-environment`) run runtime setup meant only for the isolated\n // worker thread, so they must not be evaluated in the parent.\n exposedMethods: [\n 'runDevValidation',\n 'applyHmrUpdate',\n 'invalidateCaches',\n ],\n forkOptions: {\n env: {\n ...process.env,\n NODE_OPTIONS: workerNodeOptions,\n },\n },\n }) as Worker & ValidationPool\n worker.getStdout().pipe(process.stdout)\n worker.getStderr().pipe(process.stderr)\n pool = worker\n return worker\n }\n\n const tearDownPool = async (): Promise<void> => {\n const current = pool\n if (!current) {\n return\n }\n pool = undefined\n await current.end().catch(() => {\n // The worker thread exits on its own once its work settles; a failed\n // `.end()` here just means we couldn't wait for it cleanly.\n })\n }\n\n const runValidation = async (\n snapshot: DevValidationSnapshot,\n validationAbortSignal: AbortSignal\n ): Promise<DevValidationWorkerResult> => {\n let activePool: ValidationPool\n try {\n activePool = getPool()\n } catch {\n return null\n }\n\n const message: DevValidationWorkerMessage = {\n ...snapshot,\n distDir,\n buildId,\n deploymentId,\n nextConfigSerializable: {\n httpAgentOptions: nextConfig.httpAgentOptions,\n cacheLifeProfiles: nextConfig.cacheLife,\n useCacheTimeout: nextConfig.experimental.useCacheTimeout,\n staticPageGenerationTimeout: nextConfig.staticPageGenerationTimeout,\n },\n }\n\n // The worker runs as a thread (see `enableWorkerThreads` above), so an\n // abort reaches it through a one-slot shared flag rather than the abort\n // signal directly (a signal can't cross the thread boundary). Mirror an\n // abort of `validationAbortSignal` into the buffer and wake the worker's\n // `Atomics.waitAsync` on it, so it aborts the in-flight run at its next\n // depth boundary.\n const abortBuffer = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)\n const abortFlag = new Int32Array(abortBuffer)\n const propagateAbort = () => {\n Atomics.store(abortFlag, 0, 1)\n Atomics.notify(abortFlag, 0)\n }\n if (validationAbortSignal.aborted) {\n propagateAbort()\n } else {\n validationAbortSignal.addEventListener('abort', propagateAbort, {\n once: true,\n })\n }\n\n try {\n return await activePool.runDevValidation(message, abortBuffer)\n } catch {\n // Worker crash or IPC error: tear down so the next validation starts\n // fresh. The main thread treats a missing result as \"nothing to deliver.\"\n await tearDownPool()\n return null\n } finally {\n // `once` only auto-removes the listener if it fired, so remove it\n // explicitly to bound its lifetime to this run when validation completed\n // without being superseded.\n validationAbortSignal.removeEventListener('abort', propagateAbort)\n }\n }\n\n // The dev server just cleared these paths from its own `require.cache` and\n // manifest caches. The worker clears them from its copies.\n onCacheInvalidation((filePaths) => {\n mirrorChange({\n type: 'invalidate',\n filePaths,\n evictModules: true,\n })\n })\n\n mirrorModuleState = mirrorChange\n dropWorker = () => {\n void tearDownPool()\n }\n\n setDevValidationWorker(runValidation)\n}\n"],"names":["dropDevValidationWorker","installDevValidationWorker","mirrorModuleStateToDevValidationWorker","mirrorModuleState","dropWorker","change","options","distDir","buildId","deploymentId","nextConfig","pool","mirrorChange","current","replayed","type","invalidateCaches","filePaths","evictModules","applyHmrUpdate","update","then","outcome","tearDownPool","catch","getPool","workerNodeOptions","getFormattedNodeOptionsWithoutInspect","turbo","process","env","TURBOPACK","channel","needsExperimentalReact","workerPath","require","resolve","worker","Worker","maxRetries","numWorkers","enableWorkerThreads","exposedMethods","forkOptions","NODE_OPTIONS","getStdout","pipe","stdout","getStderr","stderr","undefined","end","runValidation","snapshot","validationAbortSignal","activePool","message","nextConfigSerializable","httpAgentOptions","cacheLifeProfiles","cacheLife","useCacheTimeout","experimental","staticPageGenerationTimeout","abortBuffer","SharedArrayBuffer","Int32Array","BYTES_PER_ELEMENT","abortFlag","propagateAbort","Atomics","store","notify","aborted","addEventListener","once","runDevValidation","removeEventListener","onCacheInvalidation","setDevValidationWorker"],"mappings":";;;;;;;;;;;;;;;;IAwEgBA,uBAAuB;eAAvBA;;IAUAC,0BAA0B;eAA1BA;;IAhBAC,sCAAsC;eAAtCA;;;4BArDO;4CACgB;8BACH;uBACkB;wCACf;AA2BvC;;;;CAIC,GACD,IAAIC;AAEJ;;;;;;;;;;;;CAYC,GACD,IAAIC;AAEG,SAASF,uCACdG,MAA4B;IAE5BF,qCAAAA,kBAAoBE;AACtB;AAEO,SAASL;IACdI,8BAAAA;AACF;AAQO,SAASH,2BAA2BK,OAAuB;IAChE,MAAM,EAAEC,OAAO,EAAEC,OAAO,EAAEC,YAAY,EAAEC,UAAU,EAAE,GAAGJ;IAEvD,4EAA4E;IAC5E,wEAAwE;IACxE,wEAAwE;IACxE,4EAA4E;IAC5E,6EAA6E;IAC7E,0EAA0E;IAC1E,4EAA4E;IAC5E,yBAAyB;IACzB,EAAE;IACF,4EAA4E;IAC5E,6EAA6E;IAC7E,6EAA6E;IAC7E,0EAA0E;IAC1E,4CAA4C;IAC5C,IAAIK;IAEJ,MAAMC,eAAe,CAACP;QACpB,M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O,MAAMpB,WAAWqB,gBAAgB,CAACpB,SAASQ;QACpD,EAAE,OAAM;YACN,qEAAqE;YACrE,0EAA0E;YAC1E,MAAMzC;YACN,OAAO;QACT,SAAU;YACR,kEAAkE;YAClE,yEAAyE;YACzE,4BAA4B;YAC5B+B,sBAAsBuB,mBAAmB,CAAC,SAASR;QACrD;IACF;IAEA,2EAA2E;IAC3E,2DAA2D;IAC3DS,IAAAA,iCAAmB,EAAC,CAAC7D;QACnBL,aAAa;YACXG,MAAM;YACNE;YACAC,cAAc;QAChB;IACF;IAEAf,oBAAoBS;IACpBR,aAAa;QACX,KAAKmB;IACP;IAEAwD,IAAAA,kDAAsB,EAAC3B;AACzB","ignoreList":[0]} |
| import type { DevValidationWorkerMessage, DevValidationWorkerResult } from '../app-render/dev-validation-worker-globals'; | ||
| import type { NodeJsPartialHmrUpdate } from '../../build/swc/types'; | ||
| import '../require-hook'; | ||
| import '../node-environment'; | ||
| /** | ||
| * What this thread did with a forwarded HMR update. | ||
| * | ||
| * `no-runtime` is not a failure: no runtime the update routes to had been | ||
| * loaded here, so there was nothing to patch, and whatever loads that route | ||
| * later reads the updated chunk from disk. | ||
| */ | ||
| export type HmrApplyOutcome = 'applied' | 'no-runtime' | 'failed'; | ||
| /** | ||
| * Applies a server HMR update to this thread's module registry, mirroring the | ||
| * apply the dev server performed on its own. | ||
| * | ||
| * Turbopack's Node.js runtime registers the apply machinery per isolate (see | ||
| * `dev-nodejs.ts`), and `loadComponents` evaluates that runtime here, so this | ||
| * thread patches the same modules the dev server does. The apply also leaves | ||
| * the updated module's inline source map in this thread's Node.js cache, which | ||
| * is what makes a stack frame in that module source-mappable here. | ||
| */ | ||
| export declare function applyHmrUpdate(update: NodeJsPartialHmrUpdate): Promise<HmrApplyOutcome>; | ||
| /** | ||
| * Clears the same caches the dev server cleared, for the same paths. | ||
| * | ||
| * `evictModules` follows the dev server's own split: an applied update patches | ||
| * modules in place and clears only the manifest cache for the updated chunks, | ||
| * while a recompile evicts `require.cache` as well. This thread follows both, | ||
| * so its module state stays the dev server's module state. | ||
| */ | ||
| export declare function invalidateCaches(filePaths: string[], evictModules: boolean): Promise<void>; | ||
| /** | ||
| * Runs the dev instant/static-shell validation passes off the main thread. | ||
@@ -6,0 +35,0 @@ * Reloads the route's compiled module, then delegates the whole validation to |
@@ -5,5 +5,21 @@ "use strict"; | ||
| }); | ||
| Object.defineProperty(exports, "runDevValidation", { | ||
| enumerable: true, | ||
| get: function() { | ||
| 0 && (module.exports = { | ||
| applyHmrUpdate: null, | ||
| invalidateCaches: null, | ||
| runDevValidation: null | ||
| }); | ||
| function _export(target, all) { | ||
| for(var name in all)Object.defineProperty(target, name, { | ||
| enumerable: true, | ||
| get: all[name] | ||
| }); | ||
| } | ||
| _export(exports, { | ||
| applyHmrUpdate: function() { | ||
| return applyHmrUpdate; | ||
| }, | ||
| invalidateCaches: function() { | ||
| return invalidateCaches; | ||
| }, | ||
| runDevValidation: function() { | ||
| return runDevValidation; | ||
@@ -23,2 +39,4 @@ } | ||
| const _devvalidationevents = require("../app-render/dev-validation-events"); | ||
| const _loadmanifestexternal = require("../load-manifest.external"); | ||
| const _requirecache = require("./require-cache"); | ||
| const _manifestssingleton = require("../app-render/manifests-singleton"); | ||
@@ -38,7 +56,8 @@ const _patcherrorinspect = require("../patch-error-inspect"); | ||
| * | ||
| * This only helps Turbopack, which writes a `.map` beside every chunk. Webpack | ||
| * keeps its dev source maps in the compiler rather than on disk, so its frames | ||
| * from chunks this thread never evaluated stay unresolved, and its module URLs | ||
| * (`webpack-internal://…`) are declined below for the same reason. Frames from | ||
| * dependencies that are not bundled never reach this point, because | ||
| * Reading from disk covers the chunks, because the worker only runs under | ||
| * Turbopack (see `next-dev-server.ts`), which writes a `.map` beside every one | ||
| * of them. A module the server updated in place has no chunk of its own and is | ||
| * covered instead by this thread applying the same update (see | ||
| * `applyHmrUpdate`), which leaves its inline map in Node.js' cache here. Frames | ||
| * from dependencies that are not bundled never reach this point, because | ||
| * `filterStackFrameDEV` drops `node_modules` and `node:` frames; bundled | ||
@@ -65,3 +84,3 @@ * dependencies appear as chunks inside `distDir` like any other code. | ||
| if (!(0, _path.isAbsolute)(chunkPath)) { | ||
| // Not an emitted chunk, e.g. `webpack-internal://` or `<anonymous>`. | ||
| // Not an emitted chunk, e.g. `<anonymous>`. | ||
| return undefined; | ||
@@ -194,2 +213,25 @@ } | ||
| } | ||
| async function applyHmrUpdate(update) { | ||
| if (typeof __turbopack_server_hmr_apply__ !== 'function') { | ||
| return 'no-runtime'; | ||
| } | ||
| try { | ||
| __turbopack_server_hmr_apply__(update); | ||
| } catch { | ||
| // The dev server responds to the same failure by re-evaluating every | ||
| // module from disk. This thread cannot be repaired in place either, so the | ||
| // caller drops it. | ||
| return 'failed'; | ||
| } | ||
| return 'applied'; | ||
| } | ||
| async function invalidateCaches(filePaths, evictModules) { | ||
| if (evictModules) { | ||
| (0, _requirecache.deleteCache)(filePaths); | ||
| return; | ||
| } | ||
| for (const filePath of filePaths){ | ||
| (0, _loadmanifestexternal.clearManifestCache)(filePath); | ||
| } | ||
| } | ||
| async function runDevValidation(message, abortBuffer) { | ||
@@ -196,0 +238,0 @@ // Load the native SWC bindings and wire the code-frame renderer so the errors |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/dev/dev-validation-worker.ts"],"sourcesContent":["import type { AppPageModule } from '../route-modules/app-page/module'\nimport type {\n DevValidationWorkerMessage,\n DevValidationWorkerResult,\n} from '../app-render/dev-validation-worker-globals'\n\nimport '../require-hook'\nimport '../node-environment'\n\nimport { isAbsolute, relative } from 'path'\nimport { readFileSync, realpathSync } from 'fs'\nimport { fileURLToPath } from 'url'\nimport { installBindings } from '../../build/swc/install-bindings'\nimport { installCodeFrameSupport } from '../lib/install-code-frame'\nimport {\n loadClientReferenceManifestForPage,\n loadComponents,\n} from '../load-components'\nimport { setHttpClientAndAgentOptions } from '../setup-http-agent-env'\nimport { serializeValidationErrorsToFlight } from '../app-render/dev-validation-error-delivery'\nimport { formatValidationEvent } from '../app-render/dev-validation-events'\nimport {\n getServerActionsManifest,\n setManifestsSingleton,\n} from '../app-render/manifests-singleton'\nimport { setBundlerFindSourceMapImplementation } from '../patch-error-inspect'\nimport type { ModernSourceMapPayload } from '../lib/source-maps'\n\n/**\n * Resolves a chunk's source map by reading the `.map` file the bundler emitted\n * next to it, for chunks inside `distDir`.\n *\n * The main thread answers the same question through the Turbopack project\n * handle, which cannot cross a thread boundary. Reading from disk is\n * project-free and, more importantly, does not depend on the chunk having been\n * evaluated in this thread: Node.js caches source maps per isolate, and the\n * worker never renders server components, so it holds maps only for the chunks\n * `loadComponents` pulled in. Frames arriving in the transported payload can\n * point at any chunk the main render touched.\n *\n * This only helps Turbopack, which writes a `.map` beside every chunk. Webpack\n * keeps its dev source maps in the compiler rather than on disk, so its frames\n * from chunks this thread never evaluated stay unresolved, and its module URLs\n * (`webpack-internal://…`) are declined below for the same reason. Frames from\n * dependencies that are not bundled never reach this point, because\n * `filterStackFrameDEV` drops `node_modules` and `node:` frames; bundled\n * dependencies appear as chunks inside `distDir` like any other code.\n */\nfunction createDiskSourceMapLookup(\n distDir: string\n): (sourceURL: string) => ModernSourceMapPayload | undefined {\n // The frames carry resolved paths, so compare against the resolved `distDir`\n // to keep the containment check meaningful when the project sits behind a\n // symlink.\n let canonicalDistDir = distDir\n try {\n canonicalDistDir = realpathSync(distDir)\n } catch {}\n\n const payloads = new Map<string, ModernSourceMapPayload | undefined>()\n\n return function findSourceMapPayloadOnDisk(sourceURL) {\n let chunkPath = sourceURL\n\n if (chunkPath.startsWith('file://')) {\n try {\n chunkPath = fileURLToPath(chunkPath)\n } catch {\n return undefined\n }\n }\n\n if (!isAbsolute(chunkPath)) {\n // Not an emitted chunk, e.g. `webpack-internal://` or `<anonymous>`.\n return undefined\n }\n\n const cached = payloads.get(chunkPath)\n if (cached !== undefined || payloads.has(chunkPath)) {\n return cached\n }\n\n let payload: ModernSourceMapPayload | undefined\n const relativePath = relative(canonicalDistDir, chunkPath)\n\n // Only chunks emitted into `distDir` have a source map to point at, and\n // this keeps the lookup from reading arbitrary paths off disk.\n if (!relativePath.startsWith('..') && !isAbsolute(relativePath)) {\n try {\n payload = JSON.parse(readFileSync(chunkPath + '.map', 'utf8'))\n } catch {\n payload = undefined\n }\n }\n\n payloads.set(chunkPath, payload)\n\n return payload\n }\n}\n\n// Match the main dev server (`next-dev-server.ts`), which raises this so the\n// server captures deeper stacks. React's owner-stack capture during the\n// validation prerenders depends on it, so without it the worker's errors lose\n// their owner-stack source attribution.\ntry {\n Error.stackTraceLimit = 50\n} catch {}\n\n// The lifecycle markers E2E tests read from the CLI. Emitted on the worker's\n// stdout (piped to the parent) so they interleave with the parent's captured\n// output the same way the in-process `runWithDevValidationLogging` markers do.\n// Gated on the same test env that path checks.\nconst isTestLoggingEnabled = !!(\n process.env.__NEXT_TEST_MODE && process.env.NEXT_TEST_LOG_VALIDATION\n)\n\n/**\n * Adapts the pool's supersede flag into an `AbortSignal` the validation passes\n * check at their depth/yield boundaries. The pool shares an `Int32Array`-backed\n * `SharedArrayBuffer` whose first slot the main thread flips to non-zero (with\n * `Atomics.store` + `Atomics.notify`) when a newer navigation supersedes this\n * one. We wait for that notification with `Atomics.waitAsync`, which is\n * event-driven rather than polled. A validation that finishes without being\n * superseded calls `cleanup()`, which wakes our own still-pending wait so it\n * leaves no waiter (and no retained buffer) behind.\n */\nfunction createSupersedeSignal(abortBuffer: SharedArrayBuffer): {\n signal: AbortSignal\n cleanup: () => void\n} {\n const controller = new AbortController()\n const flag = new Int32Array(abortBuffer)\n\n if (Atomics.load(flag, 0) !== 0) {\n controller.abort()\n return { signal: controller.signal, cleanup: () => {} }\n }\n\n let settled = false\n const wait = Atomics.waitAsync(flag, 0, 0)\n if (wait.async) {\n wait.value.then(() => {\n if (settled) {\n return\n }\n settled = true\n // Woken either by a real supersede or by `cleanup()`; only the former\n // leaves the flag set.\n if (Atomics.load(flag, 0) !== 0) {\n controller.abort()\n }\n })\n } else if (Atomics.load(flag, 0) !== 0) {\n // The flag flipped between the load above and the wait.\n controller.abort()\n }\n\n return {\n signal: controller.signal,\n cleanup: () => {\n if (!settled) {\n Atomics.notify(flag, 0)\n }\n },\n }\n}\n\n/**\n * Waits out the test-only validation delay, resolving early if the render is\n * superseded. Mirrors the delay in `runWithDevValidationLogging` so scheduler\n * tests observe the same in-flight window on the worker path.\n */\nasync function applyTestValidationDelay(signal: AbortSignal): Promise<void> {\n const delayMs = Number(process.env.NEXT_TEST_DEV_VALIDATION_DELAY_MS)\n if (!Number.isFinite(delayMs) || delayMs <= 0 || signal.aborted) {\n return\n }\n\n await new Promise<void>((resolve) => {\n const finishDelay = () => {\n clearTimeout(timeout)\n signal.removeEventListener('abort', finishDelay)\n resolve()\n }\n const timeout = setTimeout(finishDelay, delayMs)\n signal.addEventListener('abort', finishDelay, { once: true })\n })\n}\n\n/**\n * Registers the client reference manifests of the pages that supplied client\n * references to the render being validated, beyond the validated route's own\n * manifest. This thread has its own manifests singleton, which `loadComponents`\n * seeds with only the validated route, so without these the dev-only cross-page\n * lookup in `createProxiedClientReferenceManifest` has no other manifest to\n * search and decoding the transported payload fails. Usually a no-op, since the\n * main thread only records a page when React's I/O tracking actually carried a\n * reference across pages.\n */\nasync function registerAdditionalClientReferenceManifests(\n distDir: string,\n pages: string[]\n): Promise<void> {\n if (pages.length === 0) {\n return\n }\n\n // Set by `loadComponents`. One server actions manifest covers the whole app,\n // so the pages registered here share the validated route's.\n const serverActionsManifest = getServerActionsManifest()\n\n await Promise.all(\n pages.map(async (page) => {\n const clientReferenceManifest = await loadClientReferenceManifestForPage(\n distDir,\n page\n )\n\n if (clientReferenceManifest) {\n setManifestsSingleton({\n page,\n clientReferenceManifest,\n serverActionsManifest,\n })\n }\n })\n )\n}\n\n/**\n * Runs the dev instant/static-shell validation passes off the main thread.\n * Reloads the route's compiled module, then delegates the whole validation to\n * that module via `ComponentMod.routeModule.runValidationInDev`, so every\n * render (flight re-encodes and client prerenders) runs inside the app-page\n * bundle's single React instance. Logs any returned errors to the worker's\n * stderr with source-mapped code frames, then encodes them as RSC Flight bytes\n * for the main thread to forward to the dev overlay. Returns `null` when\n * validation was superseded or produced no errors.\n */\nexport async function runDevValidation(\n message: DevValidationWorkerMessage,\n abortBuffer: SharedArrayBuffer\n): Promise<DevValidationWorkerResult> {\n // Load the native SWC bindings and wire the code-frame renderer so the errors\n // logged below render with a source-mapped code frame, matching the\n // in-process dev output (the E2E tests snapshot the CLI text between the\n // validation markers). The `build/swc` graph these pull in is bundled as a\n // runtime external (see `next-runtime.webpack-config.js`), so it resolves\n // from the installed `next/dist` tree rather than being compiled into this\n // worker bundle, the same way the unbundled build worker loads it.\n await installBindings()\n installCodeFrameSupport()\n setBundlerFindSourceMapImplementation(\n createDiskSourceMapLookup(message.distDir)\n )\n setHttpClientAndAgentOptions({\n httpAgentOptions: message.nextConfigSerializable.httpAgentOptions,\n })\n\n // Populates the manifests singleton for the route via `setManifestsSingleton`\n // inside `loadComponents`, exactly as a real request does. The pool tears the\n // worker down on HMR / route recompile so the next validation reloads from a\n // clean require cache.\n const { ComponentMod } = await loadComponents<AppPageModule>({\n distDir: message.distDir,\n page: message.page,\n isAppPath: true,\n isDev: true,\n sriEnabled: false,\n needsManifestsForLegacyReasons: true,\n })\n\n await registerAdditionalClientReferenceManifests(\n message.distDir,\n message.additionalClientReferenceManifestPages\n )\n\n const { signal, cleanup } = createSupersedeSignal(abortBuffer)\n\n if (isTestLoggingEnabled) {\n console.log(\n formatValidationEvent({\n type: 'validation_start',\n requestId: message.requestId,\n url: message.request.urlPathname + message.request.urlSearch,\n responseFinished: message.responseFinished,\n })\n )\n }\n\n try {\n if (isTestLoggingEnabled) {\n await applyTestValidationDelay(signal)\n }\n\n if (signal.aborted) {\n return null\n }\n\n // Crossing into the app-page bundle: the entire validation runs there, so\n // the client prerenders use the same React the user's client components\n // resolve through `ComponentMod`.\n const validationErrors = await ComponentMod.routeModule.runValidationInDev(\n ComponentMod,\n message,\n signal\n )\n\n if (validationErrors === undefined || signal.aborted) {\n return null\n }\n\n const errors: Error[] = []\n for (const validationError of validationErrors) {\n // Log to the worker's stderr; `node-environment` +\n // `installCodeFrameSupport` render the source-mapped stack and code frame\n // there, matching the in-process CLI output.\n console.error(validationError)\n if (validationError instanceof Error) {\n errors.push(validationError)\n }\n }\n\n if (errors.length === 0) {\n return null\n }\n\n return await serializeValidationErrorsToFlight(ComponentMod, errors)\n } finally {\n cleanup()\n if (isTestLoggingEnabled) {\n console.log(\n formatValidationEvent({\n type: signal.aborted ? 'validation_aborted' : 'validation_end',\n requestId: message.requestId,\n url: message.request.urlPathname + message.request.urlSearch,\n })\n )\n }\n }\n}\n"],"names":["runDevValidation","createDiskSourceMapLookup","distDir","canonicalDistDir","realpathSync","payloads","Map","findSourceMapPayloadOnDisk","sourceURL","chunkPath","startsWith","fileURLToPath","undefined","isAbsolute","cached","get","has","payload","relativePath","relative","JSON","parse","readFileSync","set","Error","stackTraceLimit","isTestLoggingEnabled","process","env","__NEXT_TEST_MODE","NEXT_TEST_LOG_VALIDATION","createSupersedeSignal","abortBuffer","controller","AbortController","flag","Int32Array","Atomics","load","abort","signal","cleanup","settled","wait","waitAsync","async","value","then","notify","applyTestValidationDelay","delayMs","Number","NEXT_TEST_DEV_VALIDATION_DELAY_MS","isFinite","aborted","Promise","resolve","finishDelay","clearTimeout","timeout","removeEventListener","setTimeout","addEventListener","once","registerAdditionalClientReferenceManifests","pages","length","serverActionsManifest","getServerActionsManifest","all","map","page","clientReferenceManifest","loadClientReferenceManifestForPage","setManifestsSingleton","message","installBindings","installCodeFrameSupport","setBundlerFindSourceMapImplementation","setHttpClientAndAgentOptions","httpAgentOptions","nextConfigSerializable","ComponentMod","loadComponents","isAppPath","isDev","sriEnabled","needsManifestsForLegacyReasons","additionalClientReferenceManifestPages","console","log","formatValidationEvent","type","requestId","url","request","urlPathname","urlSearch","responseFinished","validationErrors","routeModule","runValidationInDev","errors","validationError","error","push","serializeValidationErrorsToFlight"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QAAQC,GAAG,CACTC,IAAAA,0CAAqB,EAAC;YACpBC,MAAM;YACNC,WAAWlB,QAAQkB,SAAS;YAC5BC,KAAKnB,QAAQoB,OAAO,CAACC,WAAW,GAAGrB,QAAQoB,OAAO,CAACE,SAAS;YAC5DC,kBAAkBvB,QAAQuB,gBAAgB;QAC5C;IAEJ;IAEA,IAAI;QACF,IAAIxE,sBAAsB;YACxB,MAAMuB,yBAAyBT;QACjC;QAEA,IAAIA,OAAOc,OAAO,EAAE;YAClB,OAAO;QACT;QAEA,0EAA0E;QAC1E,wEAAwE;QACxE,kCAAkC;QAClC,MAAM6C,mBAAmB,MAAMjB,aAAakB,WAAW,CAACC,kBAAkB,CACxEnB,cACAP,SACAnC;QAGF,IAAI2D,qBAAqBvF,aAAa4B,OAAOc,OAAO,EAAE;YACpD,OAAO;QACT;QAEA,MAAMgD,SAAkB,EAAE;QAC1B,KAAK,MAAMC,mBAAmBJ,iBAAkB;YAC9C,mDAAmD;YACnD,0EAA0E;YAC1E,6CAA6C;YAC7CV,QAAQe,KAAK,CAACD;YACd,IAAIA,2BAA2B/E,OAAO;gBACpC8E,OAAOG,IAAI,CAACF;YACd;QACF;QAEA,IAAID,OAAOpC,MAAM,KAAK,GAAG;YACvB,OAAO;QACT;QAEA,OAAO,MAAMwC,IAAAA,6DAAiC,EAACxB,cAAcoB;IAC/D,SAAU;QACR7D;QACA,IAAIf,sBAAsB;YACxB+D,QAAQC,GAAG,CACTC,IAAAA,0CAAqB,EAAC;gBACpBC,MAAMpD,OAAOc,OAAO,GAAG,uBAAuB;gBAC9CuC,WAAWlB,QAAQkB,SAAS;gBAC5BC,KAAKnB,QAAQoB,OAAO,CAACC,WAAW,GAAGrB,QAAQoB,OAAO,CAACE,SAAS;YAC9D;QAEJ;IACF;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/dev/dev-validation-worker.ts"],"sourcesContent":["import type { AppPageModule } from '../route-modules/app-page/module'\nimport type {\n DevValidationWorkerMessage,\n DevValidationWorkerResult,\n} from '../app-render/dev-validation-worker-globals'\nimport type { NodeJsPartialHmrUpdate } from '../../build/swc/types'\n\nimport '../require-hook'\nimport '../node-environment'\n\nimport { isAbsolute, relative } from 'path'\nimport { readFileSync, realpathSync } from 'fs'\nimport { fileURLToPath } from 'url'\nimport { installBindings } from '../../build/swc/install-bindings'\nimport { installCodeFrameSupport } from '../lib/install-code-frame'\nimport {\n loadClientReferenceManifestForPage,\n loadComponents,\n} from '../load-components'\nimport { setHttpClientAndAgentOptions } from '../setup-http-agent-env'\nimport { serializeValidationErrorsToFlight } from '../app-render/dev-validation-error-delivery'\nimport { formatValidationEvent } from '../app-render/dev-validation-events'\nimport { clearManifestCache } from '../load-manifest.external'\nimport { deleteCache } from './require-cache'\nimport {\n getServerActionsManifest,\n setManifestsSingleton,\n} from '../app-render/manifests-singleton'\nimport { setBundlerFindSourceMapImplementation } from '../patch-error-inspect'\nimport type { ModernSourceMapPayload } from '../lib/source-maps'\n\n/**\n * Resolves a chunk's source map by reading the `.map` file the bundler emitted\n * next to it, for chunks inside `distDir`.\n *\n * The main thread answers the same question through the Turbopack project\n * handle, which cannot cross a thread boundary. Reading from disk is\n * project-free and, more importantly, does not depend on the chunk having been\n * evaluated in this thread: Node.js caches source maps per isolate, and the\n * worker never renders server components, so it holds maps only for the chunks\n * `loadComponents` pulled in. Frames arriving in the transported payload can\n * point at any chunk the main render touched.\n *\n * Reading from disk covers the chunks, because the worker only runs under\n * Turbopack (see `next-dev-server.ts`), which writes a `.map` beside every one\n * of them. A module the server updated in place has no chunk of its own and is\n * covered instead by this thread applying the same update (see\n * `applyHmrUpdate`), which leaves its inline map in Node.js' cache here. Frames\n * from dependencies that are not bundled never reach this point, because\n * `filterStackFrameDEV` drops `node_modules` and `node:` frames; bundled\n * dependencies appear as chunks inside `distDir` like any other code.\n */\nfunction createDiskSourceMapLookup(\n distDir: string\n): (sourceURL: string) => ModernSourceMapPayload | undefined {\n // The frames carry resolved paths, so compare against the resolved `distDir`\n // to keep the containment check meaningful when the project sits behind a\n // symlink.\n let canonicalDistDir = distDir\n try {\n canonicalDistDir = realpathSync(distDir)\n } catch {}\n\n const payloads = new Map<string, ModernSourceMapPayload | undefined>()\n\n return function findSourceMapPayloadOnDisk(sourceURL) {\n let chunkPath = sourceURL\n\n if (chunkPath.startsWith('file://')) {\n try {\n chunkPath = fileURLToPath(chunkPath)\n } catch {\n return undefined\n }\n }\n\n if (!isAbsolute(chunkPath)) {\n // Not an emitted chunk, e.g. `<anonymous>`.\n return undefined\n }\n\n const cached = payloads.get(chunkPath)\n if (cached !== undefined || payloads.has(chunkPath)) {\n return cached\n }\n\n let payload: ModernSourceMapPayload | undefined\n const relativePath = relative(canonicalDistDir, chunkPath)\n\n // Only chunks emitted into `distDir` have a source map to point at, and\n // this keeps the lookup from reading arbitrary paths off disk.\n if (!relativePath.startsWith('..') && !isAbsolute(relativePath)) {\n try {\n payload = JSON.parse(readFileSync(chunkPath + '.map', 'utf8'))\n } catch {\n payload = undefined\n }\n }\n\n payloads.set(chunkPath, payload)\n\n return payload\n }\n}\n\n// Match the main dev server (`next-dev-server.ts`), which raises this so the\n// server captures deeper stacks. React's owner-stack capture during the\n// validation prerenders depends on it, so without it the worker's errors lose\n// their owner-stack source attribution.\ntry {\n Error.stackTraceLimit = 50\n} catch {}\n\n// The lifecycle markers E2E tests read from the CLI. Emitted on the worker's\n// stdout (piped to the parent) so they interleave with the parent's captured\n// output the same way the in-process `runWithDevValidationLogging` markers do.\n// Gated on the same test env that path checks.\nconst isTestLoggingEnabled = !!(\n process.env.__NEXT_TEST_MODE && process.env.NEXT_TEST_LOG_VALIDATION\n)\n\n/**\n * Adapts the pool's supersede flag into an `AbortSignal` the validation passes\n * check at their depth/yield boundaries. The pool shares an `Int32Array`-backed\n * `SharedArrayBuffer` whose first slot the main thread flips to non-zero (with\n * `Atomics.store` + `Atomics.notify`) when a newer navigation supersedes this\n * one. We wait for that notification with `Atomics.waitAsync`, which is\n * event-driven rather than polled. A validation that finishes without being\n * superseded calls `cleanup()`, which wakes our own still-pending wait so it\n * leaves no waiter (and no retained buffer) behind.\n */\nfunction createSupersedeSignal(abortBuffer: SharedArrayBuffer): {\n signal: AbortSignal\n cleanup: () => void\n} {\n const controller = new AbortController()\n const flag = new Int32Array(abortBuffer)\n\n if (Atomics.load(flag, 0) !== 0) {\n controller.abort()\n return { signal: controller.signal, cleanup: () => {} }\n }\n\n let settled = false\n const wait = Atomics.waitAsync(flag, 0, 0)\n if (wait.async) {\n wait.value.then(() => {\n if (settled) {\n return\n }\n settled = true\n // Woken either by a real supersede or by `cleanup()`; only the former\n // leaves the flag set.\n if (Atomics.load(flag, 0) !== 0) {\n controller.abort()\n }\n })\n } else if (Atomics.load(flag, 0) !== 0) {\n // The flag flipped between the load above and the wait.\n controller.abort()\n }\n\n return {\n signal: controller.signal,\n cleanup: () => {\n if (!settled) {\n Atomics.notify(flag, 0)\n }\n },\n }\n}\n\n/**\n * Waits out the test-only validation delay, resolving early if the render is\n * superseded. Mirrors the delay in `runWithDevValidationLogging` so scheduler\n * tests observe the same in-flight window on the worker path.\n */\nasync function applyTestValidationDelay(signal: AbortSignal): Promise<void> {\n const delayMs = Number(process.env.NEXT_TEST_DEV_VALIDATION_DELAY_MS)\n if (!Number.isFinite(delayMs) || delayMs <= 0 || signal.aborted) {\n return\n }\n\n await new Promise<void>((resolve) => {\n const finishDelay = () => {\n clearTimeout(timeout)\n signal.removeEventListener('abort', finishDelay)\n resolve()\n }\n const timeout = setTimeout(finishDelay, delayMs)\n signal.addEventListener('abort', finishDelay, { once: true })\n })\n}\n\n/**\n * Registers the client reference manifests of the pages that supplied client\n * references to the render being validated, beyond the validated route's own\n * manifest. This thread has its own manifests singleton, which `loadComponents`\n * seeds with only the validated route, so without these the dev-only cross-page\n * lookup in `createProxiedClientReferenceManifest` has no other manifest to\n * search and decoding the transported payload fails. Usually a no-op, since the\n * main thread only records a page when React's I/O tracking actually carried a\n * reference across pages.\n */\nasync function registerAdditionalClientReferenceManifests(\n distDir: string,\n pages: string[]\n): Promise<void> {\n if (pages.length === 0) {\n return\n }\n\n // Set by `loadComponents`. One server actions manifest covers the whole app,\n // so the pages registered here share the validated route's.\n const serverActionsManifest = getServerActionsManifest()\n\n await Promise.all(\n pages.map(async (page) => {\n const clientReferenceManifest = await loadClientReferenceManifestForPage(\n distDir,\n page\n )\n\n if (clientReferenceManifest) {\n setManifestsSingleton({\n page,\n clientReferenceManifest,\n serverActionsManifest,\n })\n }\n })\n )\n}\n\ndeclare const __turbopack_server_hmr_apply__:\n | ((update: NodeJsPartialHmrUpdate) => void)\n | undefined\n\n/**\n * What this thread did with a forwarded HMR update.\n *\n * `no-runtime` is not a failure: no runtime the update routes to had been\n * loaded here, so there was nothing to patch, and whatever loads that route\n * later reads the updated chunk from disk.\n */\nexport type HmrApplyOutcome = 'applied' | 'no-runtime' | 'failed'\n\n/**\n * Applies a server HMR update to this thread's module registry, mirroring the\n * apply the dev server performed on its own.\n *\n * Turbopack's Node.js runtime registers the apply machinery per isolate (see\n * `dev-nodejs.ts`), and `loadComponents` evaluates that runtime here, so this\n * thread patches the same modules the dev server does. The apply also leaves\n * the updated module's inline source map in this thread's Node.js cache, which\n * is what makes a stack frame in that module source-mappable here.\n */\nexport async function applyHmrUpdate(\n update: NodeJsPartialHmrUpdate\n): Promise<HmrApplyOutcome> {\n if (typeof __turbopack_server_hmr_apply__ !== 'function') {\n return 'no-runtime'\n }\n\n try {\n __turbopack_server_hmr_apply__(update)\n } catch {\n // The dev server responds to the same failure by re-evaluating every\n // module from disk. This thread cannot be repaired in place either, so the\n // caller drops it.\n return 'failed'\n }\n\n return 'applied'\n}\n\n/**\n * Clears the same caches the dev server cleared, for the same paths.\n *\n * `evictModules` follows the dev server's own split: an applied update patches\n * modules in place and clears only the manifest cache for the updated chunks,\n * while a recompile evicts `require.cache` as well. This thread follows both,\n * so its module state stays the dev server's module state.\n */\nexport async function invalidateCaches(\n filePaths: string[],\n evictModules: boolean\n): Promise<void> {\n if (evictModules) {\n deleteCache(filePaths)\n return\n }\n\n for (const filePath of filePaths) {\n clearManifestCache(filePath)\n }\n}\n\n/**\n * Runs the dev instant/static-shell validation passes off the main thread.\n * Reloads the route's compiled module, then delegates the whole validation to\n * that module via `ComponentMod.routeModule.runValidationInDev`, so every\n * render (flight re-encodes and client prerenders) runs inside the app-page\n * bundle's single React instance. Logs any returned errors to the worker's\n * stderr with source-mapped code frames, then encodes them as RSC Flight bytes\n * for the main thread to forward to the dev overlay. Returns `null` when\n * validation was superseded or produced no errors.\n */\nexport async function runDevValidation(\n message: DevValidationWorkerMessage,\n abortBuffer: SharedArrayBuffer\n): Promise<DevValidationWorkerResult> {\n // Load the native SWC bindings and wire the code-frame renderer so the errors\n // logged below render with a source-mapped code frame, matching the\n // in-process dev output (the E2E tests snapshot the CLI text between the\n // validation markers). The `build/swc` graph these pull in is bundled as a\n // runtime external (see `next-runtime.webpack-config.js`), so it resolves\n // from the installed `next/dist` tree rather than being compiled into this\n // worker bundle, the same way the unbundled build worker loads it.\n await installBindings()\n installCodeFrameSupport()\n setBundlerFindSourceMapImplementation(\n createDiskSourceMapLookup(message.distDir)\n )\n setHttpClientAndAgentOptions({\n httpAgentOptions: message.nextConfigSerializable.httpAgentOptions,\n })\n\n // Populates the manifests singleton for the route via `setManifestsSingleton`\n // inside `loadComponents`, exactly as a real request does. The pool tears the\n // worker down on HMR / route recompile so the next validation reloads from a\n // clean require cache.\n const { ComponentMod } = await loadComponents<AppPageModule>({\n distDir: message.distDir,\n page: message.page,\n isAppPath: true,\n isDev: true,\n sriEnabled: false,\n needsManifestsForLegacyReasons: true,\n })\n\n await registerAdditionalClientReferenceManifests(\n message.distDir,\n message.additionalClientReferenceManifestPages\n )\n\n const { signal, cleanup } = createSupersedeSignal(abortBuffer)\n\n if (isTestLoggingEnabled) {\n console.log(\n formatValidationEvent({\n type: 'validation_start',\n requestId: message.requestId,\n url: message.request.urlPathname + message.request.urlSearch,\n responseFinished: message.responseFinished,\n })\n )\n }\n\n try {\n if (isTestLoggingEnabled) {\n await applyTestValidationDelay(signal)\n }\n\n if (signal.aborted) {\n return null\n }\n\n // Crossing into the app-page bundle: the entire validation runs there, so\n // the client prerenders use the same React the user's client components\n // resolve through `ComponentMod`.\n const validationErrors = await ComponentMod.routeModule.runValidationInDev(\n ComponentMod,\n message,\n signal\n )\n\n if (validationErrors === undefined || signal.aborted) {\n return null\n }\n\n const errors: Error[] = []\n for (const validationError of validationErrors) {\n // Log to the worker's stderr; `node-environment` +\n // `installCodeFrameSupport` render the source-mapped stack and code frame\n // there, matching the in-process CLI output.\n console.error(validationError)\n if (validationError instanceof Error) {\n errors.push(validationError)\n }\n }\n\n if (errors.length === 0) {\n return null\n }\n\n return await serializeValidationErrorsToFlight(ComponentMod, errors)\n } finally {\n cleanup()\n if (isTestLoggingEnabled) {\n console.log(\n formatValidationEvent({\n type: signal.aborted ? 'validation_aborted' : 'validation_end',\n requestId: message.requestId,\n url: message.request.urlPathname + message.request.urlSearch,\n })\n )\n }\n }\n}\n"],"names":["applyHmrUpdate","invalidateCaches","runDevValidation","createDiskSourceMapLookup","distDir","canonicalDistDir","realpathSync","payloads","Map","findSourceMapPayloadOnDisk","sourceURL","chunkPath","startsWith","fileURLToPath","undefined","isAbsolute","cached","get","has","payload","relativePath","relative","JSON","parse","readFileSync","set","Error","stackTraceLimit","isTestLoggingEnabled","process","env","__NEXT_TEST_MODE","NEXT_TEST_LOG_VALIDATION","createSupersedeSignal","abortBuffer","controller","AbortController","flag","Int32Array","Atomics","load","abort","signal","cleanup","settled","wait","waitAsync","async","value","then","notify","applyTestValidationDelay","delayMs","Number","NEXT_TEST_DEV_VALIDATION_DELAY_MS","isFinite","aborted","Promise","resolve","finishDelay","clearTimeout","timeout","removeEventListener","setTimeout","addEventListener","once","registerAdditionalClientReferenceManifests","pages","length","serverActionsManifest","getServerActionsManifest","all","map","page","clientReferenceManifest","loadClientReferenceManifestForPage","setManifestsSingleton","update","__turbopack_server_hmr_apply__","filePaths","evictModules","deleteCache","filePath","clearManifestCache","message","installBindings","installCodeFrameSupport","setBundlerFindSourceMapImplementation","setHttpClientAndAgentOptions","httpAgentOptions","nextConfigSerializable","ComponentMod","loadComponents","isAppPath","isDev","sriEnabled","needsManifestsForLegacyReasons","additionalClientReferenceManifestPages","console","log","formatValidationEvent","type","requestId","url","request","urlPathname","urlSearch","responseFinished","validationErrors","routeModule","runValidationInDev","errors","validationError","error","push","serializeValidationErrorsToFlight"],"mappings":";;;;;;;;;;;;;;;;IAiQsBA,cAAc;eAAdA;;IA2BAC,gBAAgB;eAAhBA;;IAwBAC,gBAAgB;eAAhBA;;;QA7Sf;QACA;sBAE8B;oBACM;qBACb;iCACE;kCACQ;gCAIjC;mCACsC;4CACK;qCACZ;sCACH;8BACP;oCAIrB;mCAC+C;AAGtD;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,SAASC,0BACPC,OAAe;IAEf,6EAA6E;IAC7E,0EAA0E;IAC1E,WAAW;IACX,IAAIC,mBAAmBD;IACvB,IAAI;QACFC,mBAAmBC,IAAAA,gBAAY,EAACF;IAClC,EAAE,OAAM,CAAC;IAET,MAAMG,WAAW,IAAIC;IAErB,OAAO,SAASC,2BAA2BC,SAAS;QAClD,IAAIC,YAAYD;QAEhB,IAAIC,UAAUC,UAAU,CAAC,YAAY;YACnC,IAAI;gBACFD,YAAYE,IAAAA,kBAAa,EAACF;YAC5B,EAAE,OAAM;gBACN,OAAOG;YACT;QACF;QAEA,IAAI,CAACC,IAAAA,gBAAU,EAACJ,YAAY;YAC1B,4CAA4C;YAC5C,OAAOG;QACT;QAEA,MAAME,SAAST,SAASU,GAAG,CAACN;QAC5B,IAAIK,WAAWF,aAAaP,SAASW,GAAG,CAACP,YAAY;YACnD,OAAOK;QACT;QAEA,IAAIG;QACJ,MAAMC,eAAeC,IAAAA,cAAQ,EAAChB,kBAAkBM;QAEhD,wEAAwE;QACxE,+DAA+D;QAC/D,IAAI,CAACS,aAAaR,UAAU,CAAC,SA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,aAAa4B,OAAOc,OAAO,EAAE;YACpD,OAAO;QACT;QAEA,MAAMuD,SAAkB,EAAE;QAC1B,KAAK,MAAMC,mBAAmBJ,iBAAkB;YAC9C,mDAAmD;YACnD,0EAA0E;YAC1E,6CAA6C;YAC7CV,QAAQe,KAAK,CAACD;YACd,IAAIA,2BAA2BtF,OAAO;gBACpCqF,OAAOG,IAAI,CAACF;YACd;QACF;QAEA,IAAID,OAAO3C,MAAM,KAAK,GAAG;YACvB,OAAO;QACT;QAEA,OAAO,MAAM+C,IAAAA,6DAAiC,EAACxB,cAAcoB;IAC/D,SAAU;QACRpE;QACA,IAAIf,sBAAsB;YACxBsE,QAAQC,GAAG,CACTC,IAAAA,0CAAqB,EAAC;gBACpBC,MAAM3D,OAAOc,OAAO,GAAG,uBAAuB;gBAC9C8C,WAAWlB,QAAQkB,SAAS;gBAC5BC,KAAKnB,QAAQoB,OAAO,CAACC,WAAW,GAAGrB,QAAQoB,OAAO,CAACE,SAAS;YAC9D;QAEJ;IACF;AACF","ignoreList":[0]} |
@@ -41,2 +41,3 @@ import { RenderStage, type AdvanceableRenderStage } from './app-render/staged-rendering'; | ||
| export declare function trackFallbackParamsAccessed(workUnitStore: WorkUnitStore): void; | ||
| export declare function trackIncompatibleShellContent(workUnitStore: RequestStore): void; | ||
| export declare function makeClientHookHangingPromise<T>(signal: AbortSignal, error: ClientHookDynamicError): Promise<T>; | ||
@@ -51,2 +52,4 @@ /** | ||
| export declare function makeDevtoolsIOAwarePromise<T>(underlying: T, requestStore: RequestStore, stage: AdvanceableRenderStage): Promise<T>; | ||
| /** Invokes `onUse` whenever `then()/catch()/finally()` are called on the promise. */ | ||
| export declare function trackPromiseUsed<T>(promise: Promise<T>, onUse: () => void): Promise<T>; | ||
| export declare const RENDER_STAGES_BY_DATA_KIND: { | ||
@@ -53,0 +56,0 @@ sessionData: RenderStage.ShellRuntime; |
@@ -20,2 +20,4 @@ "use strict"; | ||
| trackFallbackParamsAccessed: null, | ||
| trackIncompatibleShellContent: null, | ||
| trackPromiseUsed: null, | ||
| trackRuntimeDataAccessed: null | ||
@@ -72,2 +74,8 @@ }); | ||
| }, | ||
| trackIncompatibleShellContent: function() { | ||
| return trackIncompatibleShellContent; | ||
| }, | ||
| trackPromiseUsed: function() { | ||
| return trackPromiseUsed; | ||
| }, | ||
| trackRuntimeDataAccessed: function() { | ||
@@ -80,2 +88,3 @@ return trackRuntimeDataAccessed; | ||
| const _runtimereactsexternal = require("./runtime-reacts.external"); | ||
| const _reflect = require("./web/spec-extension/adapters/reflect"); | ||
| function isHangingPromiseRejectionError(err) { | ||
@@ -181,2 +190,5 @@ if (typeof err !== 'object' || err === null || !('digest' in err)) { | ||
| } | ||
| function trackIncompatibleShellContent(workUnitStore) { | ||
| workUnitStore.hasIncompatibleShellContent = true; | ||
| } | ||
| function makeClientHookHangingPromise(signal, error) { | ||
@@ -235,2 +247,30 @@ return makeHangingPromiseWithError(signal, error); | ||
| } | ||
| function trackPromiseUsed(promise, onUse) { | ||
| const methodCache = {}; | ||
| return new Proxy(promise, { | ||
| get (target, prop, receiver) { | ||
| if (prop === 'then' || prop === 'catch' || prop === 'finally') { | ||
| let patchedMethod = methodCache[prop]; | ||
| if (patchedMethod !== undefined) { | ||
| return patchedMethod; | ||
| } | ||
| const originalMethod = _reflect.ReflectAdapter.get(target, prop, receiver); | ||
| patchedMethod = ({ | ||
| [prop]: (...args)=>{ | ||
| try { | ||
| onUse(); | ||
| } catch (err) { | ||
| // We don't want to break the method even if our tracking errored. | ||
| console.error(err); | ||
| } | ||
| return originalMethod.apply(target, args); | ||
| } | ||
| })[prop]; | ||
| methodCache[prop] = patchedMethod; | ||
| return patchedMethod; | ||
| } | ||
| return _reflect.ReflectAdapter.get(target, prop, receiver); | ||
| } | ||
| }); | ||
| } | ||
| const RENDER_STAGES_BY_DATA_KIND = { | ||
@@ -237,0 +277,0 @@ sessionData: _stagedrendering.RenderStage.ShellRuntime, |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../src/server/dynamic-rendering-utils.ts"],"sourcesContent":["import {\n RenderStage,\n type AdvanceableRenderStage,\n} from './app-render/staged-rendering'\nimport type {\n RequestStore,\n WorkUnitStore,\n} from './app-render/work-unit-async-storage.external'\nimport { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'\nimport { getServerReact, getClientReact } from './runtime-reacts.external'\n\nexport function isHangingPromiseRejectionError(\n err: unknown\n): err is HangingPromiseRejectionError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === HANGING_PROMISE_REJECTION\n}\n\nconst HANGING_PROMISE_REJECTION = 'HANGING_PROMISE_REJECTION'\n\nclass HangingPromiseRejectionError extends Error {\n public readonly digest = HANGING_PROMISE_REJECTION\n\n constructor(\n public readonly route: string,\n public readonly expression: string\n ) {\n super(\n `During prerendering, ${expression} rejects when the prerender is complete. Typically these errors are handled by React but if you move ${expression} to a different context by using \\`setTimeout\\`, \\`after\\`, or similar functions you may observe this error and you should handle it in that context. This occurred at route \"${route}\".`\n )\n }\n}\n\nconst CLIENT_HOOK_DYNAMIC = 'CLIENT_HOOK_DYNAMIC'\n\nexport class ClientHookDynamicError extends Error {\n public readonly digest = CLIENT_HOOK_DYNAMIC\n\n constructor(route: string, expression: string) {\n super(\n `Route \"${route}\": Next.js encountered URL data \\`${expression}\\` in a Client Component outside of \\`<Suspense>\\`.\\n\\n` +\n `This blocks prerendering because the value is only available at runtime.\\n\\n` +\n `Ways to fix this:\\n` +\n ` - [stream] Wrap the component in \\`<Suspense fallback={...}>\\` so the hook value streams in after prerendering\\n` +\n ` - [block] Set \\`export const instant = false\\` to allow a blocking route\\n\\n` +\n `Learn more: https://nextjs.org/docs/messages/blocking-prerender-client-hook`\n )\n }\n}\n\nexport function isClientHookDynamicError(\n err: unknown\n): err is ClientHookDynamicError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === CLIENT_HOOK_DYNAMIC\n}\n\ntype AbortListeners = Array<() => void>\nconst abortListenersBySignal = new WeakMap<AbortSignal, AbortListeners>()\n\n/**\n * Constructs a promise that never resolves, standing in for *dynamic* data:\n * data that is only available during a real dynamic request and hangs in\n * every kind of prerender — `io()`, `connection()`, uncached `fetch()`.\n *\n * This is primarily useful for cacheComponents where we use promise\n * resolution timing to determine which parts of a render can be included in a\n * prerender.\n *\n * Records nothing on the prerender store: the promise's holes are only ever\n * filled by a real dynamic request, so a runtime prefetch response would have\n * the same holes as the static one. If the data source would resolve during a\n * runtime prerender, use `makeRuntimeHangingPromise` instead.\n *\n * @internal\n */\nexport function makeDynamicHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\nexport function makeUntrackedHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for *runtime* data:\n * data that hangs during a static prerender but is available during a runtime\n * prerender (the kind that backs a runtime prefetch request: request data\n * like cookies and headers is available, but the render is still not a real\n * dynamic request). Examples: cookies, headers, fallback params,\n * searchParams, and cache entries that are excluded only from static\n * prerenders.\n *\n * Creating one of these during a static prerender records on the prerender\n * store that a runtime prefetch would produce more content than the static\n * response (`runtimeDataAccessed`), which the segment prefetch encoding uses\n * to tell the client whether a runtime prefetch request could be skipped.\n *\n * When unsure whether data is dynamic or runtime, prefer this method — the\n * cost of over-recording is a redundant runtime prefetch request; the cost of\n * under-recording is a permanently missing one.\n *\n * `workUnitStore` may be null ONLY when the caller tracks the access itself\n * at observation time instead of creation time. This is for promises the\n * framework creates eagerly whether or not anything reads them (e.g. the\n * `searchParams` prop constructed for every page): recording at creation\n * would mark every render. Such a caller MUST call `trackRuntimeDataAccessed`\n * from every path that observes the promise (e.g. the proxy traps for\n * `then`/`status`), against the work unit store active at access time.\n *\n * For fallback-param data — data a concrete (ISR-upgraded) prerender would\n * resolve — use `makeFallbackParamsHangingPromise` instead, so the access\n * is recorded with the right effect on the static-prefetch hint.\n *\n * @internal\n */\nexport function makeRuntimeHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore | null\n): Promise<T> {\n if (workUnitStore !== null) {\n trackRuntimeDataAccessed(workUnitStore)\n }\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Variant of `makeRuntimeHangingPromise` for *fallback-param* data: fallback\n * route params and values derived solely from them (`params`, `rootParams`,\n * `pathname` during a fallback prerender). Like every runtime data access it\n * records the access on the prerender store's response-level flag, but its\n * effect on the build-time static-prefetch hint differs — on a\n * fallback-upgradeable route the access is transient (a concrete prerender\n * resolves it), so it leaves the hint intact. See\n * `trackFallbackParamsAccessed`.\n *\n * As with `makeRuntimeHangingPromise`, `workUnitStore` may be null ONLY when\n * the caller tracks the access itself at observation time instead of creation\n * time, by calling `trackFallbackParamsAccessed` from every path that\n * observes the promise.\n *\n * @internal\n */\nexport function makeFallbackParamsHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore | null\n): Promise<T> {\n if (workUnitStore !== null) {\n trackFallbackParamsAccessed(workUnitStore)\n }\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for data that is only\n * accessible in a later *stage* of rendering than this render reaches — e.g.\n * a prefetchable short-stale cache entry that's excluded from shells when the\n * render ends at the shell stage, or params during a runtime-prefetch render\n * that stops before the stage where params resolve.\n *\n * A render that runs through the later stage would include the data; in\n * particular a runtime prefetch renders through its later stages, so on a\n * static prerender store this records `runtimeDataAccessed`, same as\n * `makeRuntimeHangingPromise`.\n *\n * @internal\n */\nexport function makeStageHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore\n): Promise<T> {\n trackRuntimeDataAccessed(workUnitStore)\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Records on a static prerender store that the render accessed a data source\n * which would have resolved during a runtime prerender. No-op for all other\n * store types.\n *\n * `makeRuntimeHangingPromise` and `makeStageHangingPromise` call this\n * automatically; call it directly only where the access is observed\n * separately from the promise's creation (see the null `workUnitStore` case\n * of `makeRuntimeHangingPromise`), or where the prerender is aborted\n * synchronously instead of hanging.\n *\n * For fallback-param data, use `trackFallbackParamsAccessed` instead. When\n * unsure, this is the conservative choice: it unconditionally clears the\n * static-prefetch hint.\n */\nexport function trackRuntimeDataAccessed(workUnitStore: WorkUnitStore): void {\n trackRuntimeDataAccessedImpl(workUnitStore, false)\n}\n\n/**\n * Fallback-param variant of `trackRuntimeDataAccessed`, for accesses of\n * fallback route params and values derived solely from them. It records the\n * response-level flag all the same, but only clears the build-time\n * static-prefetch hint when the route is not fallback-upgradeable — on an\n * upgradeable route the access is transient, since ISR later produces a\n * concrete prerender that resolves it.\n */\nexport function trackFallbackParamsAccessed(\n workUnitStore: WorkUnitStore\n): void {\n trackRuntimeDataAccessedImpl(workUnitStore, true)\n}\n\nfunction trackRuntimeDataAccessedImpl(\n workUnitStore: WorkUnitStore,\n isFallbackParamAccess: boolean\n): void {\n switch (workUnitStore.type) {\n case 'prerender': {\n // Response-level flag (the payload's `u`, forwarded to segment\n // responses as `needsRuntimeRequest`): resolved for every kind of\n // access — a pre-upgrade fallback response must keep reporting that\n // a runtime request would return more. The fulfillment row lands at\n // the current position in the Flight stream, which is what makes the\n // value rewindable per stage. Promise resolution is idempotent, so\n // repeated accesses are free.\n workUnitStore.runtimeDataAccessed?.resolve(true)\n\n // Hint cell (holds the build-constant\n // PrefetchHint.ShouldAttemptStaticPrefetch value directly): a\n // fallback-param access is transient when the route is\n // fallback-upgradeable — ISR later produces the concrete prerender a\n // static prefetch attempt would hit — so it leaves the hint intact.\n // (Until that upgrade, the response-level flag above keeps directing\n // the client to a runtime fallback; the hint only costs a wasted\n // static attempt in the interim.) Every other access clears it.\n const hintCell = workUnitStore.shouldAttemptStaticPrefetch\n if (\n hintCell !== null &&\n (!isFallbackParamAccess || !workUnitStore.isFallbackUpgradeable)\n ) {\n hintCell.current = false\n }\n break\n }\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'validation-client':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n // Only the modern server prerender tracks this; see the field docs on\n // PrerenderStoreModernServer.\n break\n default:\n workUnitStore satisfies never\n }\n}\n\nexport function makeClientHookHangingPromise<T>(\n signal: AbortSignal,\n error: ClientHookDynamicError\n): Promise<T> {\n return makeHangingPromiseWithError(signal, error)\n}\n\nfunction makeHangingPromiseWithError<T>(\n signal: AbortSignal,\n error: Error\n): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(error)\n } else {\n const hangingPromise = new Promise<T>((_, reject) => {\n const boundRejection = reject.bind(null, error)\n let currentListeners = abortListenersBySignal.get(signal)\n if (currentListeners) {\n currentListeners.push(boundRejection)\n } else {\n const listeners = [boundRejection]\n abortListenersBySignal.set(signal, listeners)\n signal.addEventListener(\n 'abort',\n () => {\n for (let i = 0; i < listeners.length; i++) {\n listeners[i]()\n }\n },\n { once: true }\n )\n }\n })\n // We are fine if no one actually awaits this promise. We shouldn't consider this an unhandled rejection so\n // we attach a noop catch handler here to suppress this warning. If you actually await somewhere or construct\n // your own promise out of it you'll need to ensure you handle the error when it rejects.\n hangingPromise.catch(ignoreReject)\n return hangingPromise\n }\n}\n\nfunction ignoreReject() {}\n\n/**\n * Creates a promise that will be triggered when another promise resolves.\n * It will not emit unhandled rejections, which is important if the trigger\n * is a promise that might itself get rejected (e.g. when a prerender/render\n * are aborted due to sync IO)\n */\nexport function makePromiseFromTrigger<T>(\n trigger: Promise<any>,\n value: T\n): Promise<T> {\n const promise = trigger.then(() => value)\n promise.catch(ignoreReject)\n return promise\n}\n\nexport function makeDevtoolsIOAwarePromise<T>(\n underlying: T,\n requestStore: RequestStore,\n stage: AdvanceableRenderStage\n): Promise<T> {\n if (requestStore.stagedRendering) {\n // We resolve each stage in a timeout, so React DevTools will pick this up as IO.\n return requestStore.stagedRendering.delayUntilStage(\n stage,\n undefined,\n underlying\n )\n }\n // in React DevTools if we resolve in a setTimeout we will observe\n // the promise resolution as something that can suspend a boundary or root.\n return new Promise<T>((resolve) => {\n // Must use setTimeout to be considered IO React DevTools. setImmediate will not work.\n setTimeout(() => {\n resolve(underlying)\n }, 0)\n })\n}\n\nexport const RENDER_STAGES_BY_DATA_KIND = {\n sessionData: RenderStage.ShellRuntime as const,\n staticLinkData: RenderStage.Static as const,\n runtimeLinkData: RenderStage.Runtime as const,\n}\n\nexport function applyOwnerStack(error: Error): Error {\n if (process.env.NODE_ENV !== 'production') {\n let ownerStack: string | undefined | null\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // captureOwnerStack() returns the owner stack for the current React\n // rendering context. Inside a cache scope this only includes the inner\n // component tree. The outer owner stack (captured before entering the\n // cache boundary in use-cache-wrapper.ts) is stored on the cache store.\n // We concatenate both to get the full component tree.\n const innerOwnerStack =\n getClientReact()?.captureOwnerStack?.() ??\n getServerReact()?.captureOwnerStack?.()\n\n switch (workUnitStore?.type) {\n case 'cache':\n case 'private-cache':\n ownerStack =\n (innerOwnerStack || '') + (workUnitStore.outerOwnerStack || '') ||\n undefined\n break\n case 'unstable-cache':\n case 'request':\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'generate-static-params':\n case undefined:\n ownerStack = innerOwnerStack\n break\n default:\n workUnitStore satisfies never\n }\n\n if (ownerStack) {\n let stack = ownerStack\n\n if (error.stack) {\n const frames: string[] = []\n\n for (const frame of error.stack.split('\\n').slice(1)) {\n if (frame.includes('react_stack_bottom_frame')) {\n break\n }\n\n frames.push(frame)\n }\n\n stack = '\\n' + frames.join('\\n') + stack\n }\n\n error.stack = error.name + ': ' + error.message + stack\n }\n }\n\n return error\n}\n"],"names":["ClientHookDynamicError","RENDER_STAGES_BY_DATA_KIND","applyOwnerStack","isClientHookDynamicError","isHangingPromiseRejectionError","makeClientHookHangingPromise","makeDevtoolsIOAwarePromise","makeDynamicHangingPromise","makeFallbackParamsHangingPromise","makePromiseFromTrigger","makeRuntimeHangingPromise","makeStageHangingPromise","makeUntrackedHangingPromise","trackFallbackParamsAccessed","trackRuntimeDataAccessed","err","digest","HANGING_PROMISE_REJECTION","HangingPromiseRejectionError","Error","constructor","route","expression","CLIENT_HOOK_DYNAMIC","abortListenersBySignal","WeakMap","signal","makeHangingPromiseWithError","workUnitStore","trackRuntimeDataAccessedImpl","isFallbackParamAccess","type","runtimeDataAccessed","resolve","hintCell","shouldAttemptStaticPrefetch","isFallbackUpgradeable","current","error","aborted","Promise","reject","hangingPromise","_","boundRejection","bind","currentListeners","get","push","listeners","set","addEventListener","i","length","once","catch","ignoreReject","trigger","value","promise","then","underlying","requestStore","stage","stagedRendering","delayUntilStage","undefined","setTimeout","sessionData","RenderStage","ShellRuntime","staticLinkData","Static","runtimeLinkData","Runtime","process","env","NODE_ENV","getClientReact","getServerReact","ownerStack","workUnitAsyncStorage","getStore","innerOwnerStack","captureOwnerStack","outerOwnerStack","stack","frames","frame","split","slice","includes","join","name","message"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;IAsCaA,sBAAsB;eAAtBA;;IAgVAC,0BAA0B;eAA1BA;;IAMGC,eAAe;eAAfA;;IAvUAC,wBAAwB;eAAxBA;;IA1CAC,8BAA8B;eAA9BA;;IA0RAC,4BAA4B;eAA5BA;;IA0DAC,0BAA0B;eAA1BA;;IA7QAC,yBAAyB;eAAzBA;;IAsFAC,gCAAgC;eAAhCA;;IA8KAC,sBAAsB;eAAtBA;;IA9MAC,yBAAyB;eAAzBA;;IA6DAC,uBAAuB;eAAvBA;;IA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BACpD,IAAIF,MAAMG,QAAQ,CAAC,6BAA6B;wBAC9C;oBACF;oBAEAJ,OAAOvC,IAAI,CAACwC;gBACd;gBAEAF,QAAQ,OAAOC,OAAOK,IAAI,CAAC,QAAQN;YACrC;YAEAhD,MAAMgD,KAAK,GAAGhD,MAAMuD,IAAI,GAAG,OAAOvD,MAAMwD,OAAO,GAAGR;QACpD;IACF;IAEA,OAAOhD;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../src/server/dynamic-rendering-utils.ts"],"sourcesContent":["import {\n RenderStage,\n type AdvanceableRenderStage,\n} from './app-render/staged-rendering'\nimport type {\n RequestStore,\n WorkUnitStore,\n} from './app-render/work-unit-async-storage.external'\nimport { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'\nimport { getServerReact, getClientReact } from './runtime-reacts.external'\nimport { ReflectAdapter } from './web/spec-extension/adapters/reflect'\n\nexport function isHangingPromiseRejectionError(\n err: unknown\n): err is HangingPromiseRejectionError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === HANGING_PROMISE_REJECTION\n}\n\nconst HANGING_PROMISE_REJECTION = 'HANGING_PROMISE_REJECTION'\n\nclass HangingPromiseRejectionError extends Error {\n public readonly digest = HANGING_PROMISE_REJECTION\n\n constructor(\n public readonly route: string,\n public readonly expression: string\n ) {\n super(\n `During prerendering, ${expression} rejects when the prerender is complete. Typically these errors are handled by React but if you move ${expression} to a different context by using \\`setTimeout\\`, \\`after\\`, or similar functions you may observe this error and you should handle it in that context. This occurred at route \"${route}\".`\n )\n }\n}\n\nconst CLIENT_HOOK_DYNAMIC = 'CLIENT_HOOK_DYNAMIC'\n\nexport class ClientHookDynamicError extends Error {\n public readonly digest = CLIENT_HOOK_DYNAMIC\n\n constructor(route: string, expression: string) {\n super(\n `Route \"${route}\": Next.js encountered URL data \\`${expression}\\` in a Client Component outside of \\`<Suspense>\\`.\\n\\n` +\n `This blocks prerendering because the value is only available at runtime.\\n\\n` +\n `Ways to fix this:\\n` +\n ` - [stream] Wrap the component in \\`<Suspense fallback={...}>\\` so the hook value streams in after prerendering\\n` +\n ` - [block] Set \\`export const instant = false\\` to allow a blocking route\\n\\n` +\n `Learn more: https://nextjs.org/docs/messages/blocking-prerender-client-hook`\n )\n }\n}\n\nexport function isClientHookDynamicError(\n err: unknown\n): err is ClientHookDynamicError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === CLIENT_HOOK_DYNAMIC\n}\n\ntype AbortListeners = Array<() => void>\nconst abortListenersBySignal = new WeakMap<AbortSignal, AbortListeners>()\n\n/**\n * Constructs a promise that never resolves, standing in for *dynamic* data:\n * data that is only available during a real dynamic request and hangs in\n * every kind of prerender — `io()`, `connection()`, uncached `fetch()`.\n *\n * This is primarily useful for cacheComponents where we use promise\n * resolution timing to determine which parts of a render can be included in a\n * prerender.\n *\n * Records nothing on the prerender store: the promise's holes are only ever\n * filled by a real dynamic request, so a runtime prefetch response would have\n * the same holes as the static one. If the data source would resolve during a\n * runtime prerender, use `makeRuntimeHangingPromise` instead.\n *\n * @internal\n */\nexport function makeDynamicHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\nexport function makeUntrackedHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for *runtime* data:\n * data that hangs during a static prerender but is available during a runtime\n * prerender (the kind that backs a runtime prefetch request: request data\n * like cookies and headers is available, but the render is still not a real\n * dynamic request). Examples: cookies, headers, fallback params,\n * searchParams, and cache entries that are excluded only from static\n * prerenders.\n *\n * Creating one of these during a static prerender records on the prerender\n * store that a runtime prefetch would produce more content than the static\n * response (`runtimeDataAccessed`), which the segment prefetch encoding uses\n * to tell the client whether a runtime prefetch request could be skipped.\n *\n * When unsure whether data is dynamic or runtime, prefer this method — the\n * cost of over-recording is a redundant runtime prefetch request; the cost of\n * under-recording is a permanently missing one.\n *\n * `workUnitStore` may be null ONLY when the caller tracks the access itself\n * at observation time instead of creation time. This is for promises the\n * framework creates eagerly whether or not anything reads them (e.g. the\n * `searchParams` prop constructed for every page): recording at creation\n * would mark every render. Such a caller MUST call `trackRuntimeDataAccessed`\n * from every path that observes the promise (e.g. the proxy traps for\n * `then`/`status`), against the work unit store active at access time.\n *\n * For fallback-param data — data a concrete (ISR-upgraded) prerender would\n * resolve — use `makeFallbackParamsHangingPromise` instead, so the access\n * is recorded with the right effect on the static-prefetch hint.\n *\n * @internal\n */\nexport function makeRuntimeHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore | null\n): Promise<T> {\n if (workUnitStore !== null) {\n trackRuntimeDataAccessed(workUnitStore)\n }\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Variant of `makeRuntimeHangingPromise` for *fallback-param* data: fallback\n * route params and values derived solely from them (`params`, `rootParams`,\n * `pathname` during a fallback prerender). Like every runtime data access it\n * records the access on the prerender store's response-level flag, but its\n * effect on the build-time static-prefetch hint differs — on a\n * fallback-upgradeable route the access is transient (a concrete prerender\n * resolves it), so it leaves the hint intact. See\n * `trackFallbackParamsAccessed`.\n *\n * As with `makeRuntimeHangingPromise`, `workUnitStore` may be null ONLY when\n * the caller tracks the access itself at observation time instead of creation\n * time, by calling `trackFallbackParamsAccessed` from every path that\n * observes the promise.\n *\n * @internal\n */\nexport function makeFallbackParamsHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore | null\n): Promise<T> {\n if (workUnitStore !== null) {\n trackFallbackParamsAccessed(workUnitStore)\n }\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for data that is only\n * accessible in a later *stage* of rendering than this render reaches — e.g.\n * a prefetchable short-stale cache entry that's excluded from shells when the\n * render ends at the shell stage, or params during a runtime-prefetch render\n * that stops before the stage where params resolve.\n *\n * A render that runs through the later stage would include the data; in\n * particular a runtime prefetch renders through its later stages, so on a\n * static prerender store this records `runtimeDataAccessed`, same as\n * `makeRuntimeHangingPromise`.\n *\n * @internal\n */\nexport function makeStageHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore\n): Promise<T> {\n trackRuntimeDataAccessed(workUnitStore)\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Records on a static prerender store that the render accessed a data source\n * which would have resolved during a runtime prerender. No-op for all other\n * store types.\n *\n * `makeRuntimeHangingPromise` and `makeStageHangingPromise` call this\n * automatically; call it directly only where the access is observed\n * separately from the promise's creation (see the null `workUnitStore` case\n * of `makeRuntimeHangingPromise`), or where the prerender is aborted\n * synchronously instead of hanging.\n *\n * For fallback-param data, use `trackFallbackParamsAccessed` instead. When\n * unsure, this is the conservative choice: it unconditionally clears the\n * static-prefetch hint.\n */\nexport function trackRuntimeDataAccessed(workUnitStore: WorkUnitStore): void {\n trackRuntimeDataAccessedImpl(workUnitStore, false)\n}\n\n/**\n * Fallback-param variant of `trackRuntimeDataAccessed`, for accesses of\n * fallback route params and values derived solely from them. It records the\n * response-level flag all the same, but only clears the build-time\n * static-prefetch hint when the route is not fallback-upgradeable — on an\n * upgradeable route the access is transient, since ISR later produces a\n * concrete prerender that resolves it.\n */\nexport function trackFallbackParamsAccessed(\n workUnitStore: WorkUnitStore\n): void {\n trackRuntimeDataAccessedImpl(workUnitStore, true)\n}\n\nfunction trackRuntimeDataAccessedImpl(\n workUnitStore: WorkUnitStore,\n isFallbackParamAccess: boolean\n): void {\n switch (workUnitStore.type) {\n case 'prerender': {\n // Response-level flag (the payload's `u`, forwarded to segment\n // responses as `needsRuntimeRequest`): resolved for every kind of\n // access — a pre-upgrade fallback response must keep reporting that\n // a runtime request would return more. The fulfillment row lands at\n // the current position in the Flight stream, which is what makes the\n // value rewindable per stage. Promise resolution is idempotent, so\n // repeated accesses are free.\n workUnitStore.runtimeDataAccessed?.resolve(true)\n\n // Hint cell (holds the build-constant\n // PrefetchHint.ShouldAttemptStaticPrefetch value directly): a\n // fallback-param access is transient when the route is\n // fallback-upgradeable — ISR later produces the concrete prerender a\n // static prefetch attempt would hit — so it leaves the hint intact.\n // (Until that upgrade, the response-level flag above keeps directing\n // the client to a runtime fallback; the hint only costs a wasted\n // static attempt in the interim.) Every other access clears it.\n const hintCell = workUnitStore.shouldAttemptStaticPrefetch\n if (\n hintCell !== null &&\n (!isFallbackParamAccess || !workUnitStore.isFallbackUpgradeable)\n ) {\n hintCell.current = false\n }\n break\n }\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'validation-client':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n // Only the modern server prerender tracks this; see the field docs on\n // PrerenderStoreModernServer.\n break\n default:\n workUnitStore satisfies never\n }\n}\n\nexport function trackIncompatibleShellContent(workUnitStore: RequestStore) {\n workUnitStore.hasIncompatibleShellContent = true\n}\n\nexport function makeClientHookHangingPromise<T>(\n signal: AbortSignal,\n error: ClientHookDynamicError\n): Promise<T> {\n return makeHangingPromiseWithError(signal, error)\n}\n\nfunction makeHangingPromiseWithError<T>(\n signal: AbortSignal,\n error: Error\n): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(error)\n } else {\n const hangingPromise = new Promise<T>((_, reject) => {\n const boundRejection = reject.bind(null, error)\n let currentListeners = abortListenersBySignal.get(signal)\n if (currentListeners) {\n currentListeners.push(boundRejection)\n } else {\n const listeners = [boundRejection]\n abortListenersBySignal.set(signal, listeners)\n signal.addEventListener(\n 'abort',\n () => {\n for (let i = 0; i < listeners.length; i++) {\n listeners[i]()\n }\n },\n { once: true }\n )\n }\n })\n // We are fine if no one actually awaits this promise. We shouldn't consider this an unhandled rejection so\n // we attach a noop catch handler here to suppress this warning. If you actually await somewhere or construct\n // your own promise out of it you'll need to ensure you handle the error when it rejects.\n hangingPromise.catch(ignoreReject)\n return hangingPromise\n }\n}\n\nfunction ignoreReject() {}\n\n/**\n * Creates a promise that will be triggered when another promise resolves.\n * It will not emit unhandled rejections, which is important if the trigger\n * is a promise that might itself get rejected (e.g. when a prerender/render\n * are aborted due to sync IO)\n */\nexport function makePromiseFromTrigger<T>(\n trigger: Promise<any>,\n value: T\n): Promise<T> {\n const promise = trigger.then(() => value)\n promise.catch(ignoreReject)\n return promise\n}\n\nexport function makeDevtoolsIOAwarePromise<T>(\n underlying: T,\n requestStore: RequestStore,\n stage: AdvanceableRenderStage\n): Promise<T> {\n if (requestStore.stagedRendering) {\n // We resolve each stage in a timeout, so React DevTools will pick this up as IO.\n return requestStore.stagedRendering.delayUntilStage(\n stage,\n undefined,\n underlying\n )\n }\n // in React DevTools if we resolve in a setTimeout we will observe\n // the promise resolution as something that can suspend a boundary or root.\n return new Promise<T>((resolve) => {\n // Must use setTimeout to be considered IO React DevTools. setImmediate will not work.\n setTimeout(() => {\n resolve(underlying)\n }, 0)\n })\n}\n\n/** Invokes `onUse` whenever `then()/catch()/finally()` are called on the promise. */\nexport function trackPromiseUsed<T>(promise: Promise<T>, onUse: () => void) {\n const methodCache: Record<string, (...args: any[]) => any> = {}\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n let patchedMethod = methodCache[prop]\n if (patchedMethod !== undefined) {\n return patchedMethod\n }\n\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n patchedMethod = {\n [prop]: (...args: unknown[]) => {\n try {\n onUse()\n } catch (err) {\n // We don't want to break the method even if our tracking errored.\n console.error(err)\n }\n\n return originalMethod.apply(target, args)\n },\n }[prop]\n\n methodCache[prop] = patchedMethod\n return patchedMethod\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n}\n\nexport const RENDER_STAGES_BY_DATA_KIND = {\n sessionData: RenderStage.ShellRuntime as const,\n staticLinkData: RenderStage.Static as const,\n runtimeLinkData: RenderStage.Runtime as const,\n}\n\nexport function applyOwnerStack(error: Error): Error {\n if (process.env.NODE_ENV !== 'production') {\n let ownerStack: string | undefined | null\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // captureOwnerStack() returns the owner stack for the current React\n // rendering context. Inside a cache scope this only includes the inner\n // component tree. The outer owner stack (captured before entering the\n // cache boundary in use-cache-wrapper.ts) is stored on the cache store.\n // We concatenate both to get the full component tree.\n const innerOwnerStack =\n getClientReact()?.captureOwnerStack?.() ??\n getServerReact()?.captureOwnerStack?.()\n\n switch (workUnitStore?.type) {\n case 'cache':\n case 'private-cache':\n ownerStack =\n (innerOwnerStack || '') + (workUnitStore.outerOwnerStack || '') ||\n undefined\n break\n case 'unstable-cache':\n case 'request':\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'generate-static-params':\n case undefined:\n ownerStack = innerOwnerStack\n break\n default:\n workUnitStore satisfies never\n }\n\n if (ownerStack) {\n let stack = ownerStack\n\n if (error.stack) {\n const frames: string[] = []\n\n for (const frame of error.stack.split('\\n').slice(1)) {\n if (frame.includes('react_stack_bottom_frame')) {\n break\n }\n\n frames.push(frame)\n }\n\n stack = '\\n' + frames.join('\\n') + stack\n }\n\n error.stack = error.name + ': ' + error.message + stack\n }\n }\n\n return error\n}\n"],"names":["ClientHookDynamicError","RENDER_STAGES_BY_DATA_KIND","applyOwnerStack","isClientHookDynamicError","isHangingPromiseRejectionError","makeClientHookHangingPromise","makeDevtoolsIOAwarePromise","makeDynamicHangingPromise","makeFallbackParamsHangingPromise","makePromiseFromTrigger","makeRuntimeHangingPromise","makeStageHangingPromise","makeUntrackedHangingPromise","trackFallbackParamsAccessed","trackIncompatibleShellContent","trackPromiseUsed","trackRuntimeDataAccessed","err","digest","HANGING_PROMISE_REJECTION","HangingPromiseRejectionError","Error","constructor","route","expression","CLIENT_HOOK_DYNAMIC","abortListenersBySignal","WeakMap","signal","makeHangingPromiseWithError","workUnitStore","trackRuntimeDataAccessedImpl","isFallbackParamAccess","type","runtimeDataAccessed","resolve","hintCell","shouldAttemptStaticPrefetch","isFallbackUpgradeable","current","hasIncompatibleShellContent","error","aborted","Promise","reject","hangingPromise","_","boundRejection","bind","currentListeners","get","push","listeners","set","addEventListener","i","length","once","catch","ignoreReject","trigger","value","promise","then","underlying","requestStore","stage","stagedRendering","delayUntilStage","undefined","setTimeout","onUse","methodCache","Proxy","target","prop","receiver","patchedMethod","originalMethod","ReflectAdapter","args","console","apply","sessionData","RenderStage","ShellRuntime","staticLinkData","Static","runtimeLinkData","Runtime","process","env","NODE_ENV","getClientReact","getServerReact","ownerStack","workUnitAsyncStorage","getStore","innerOwnerStack","captureOwnerStack","outerOwnerStack","stack","frames","frame","split","slice","includes","join","name","message"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAuCaA,sBAAsB;eAAtBA;;IAsXAC,0BAA0B;eAA1BA;;IAMGC,eAAe;eAAfA;;IA7WAC,wBAAwB;eAAxBA;;IA1CAC,8BAA8B;eAA9BA;;IA8RAC,4BAA4B;eAA5BA;;IA0DAC,0BAA0B;eAA1BA;;IAjRAC,yBAAyB;eAAzBA;;IAsFAC,gCAAgC;eAAhCA;;IAkLAC,sBAAsB;eAAtBA;;IAlNAC,yBAAyB;eAAzBA;;IA6DAC,uBAAuB;eAAvBA;;IAxGAC,2BAA2B;eAA3BA;;IAgJAC,2BAA2B;eAA3BA;;IAwDAC,6BAA6B;eAA7BA;;IAsFAC,gBAAgB;eAAhBA;;IA1JAC,wBAAwB;eAAxBA;;;iCA/NT;8CAK8B;uCACU;yBAChB;AAExB,SAASZ,+BACda,GAAY;IAEZ,IAAI,OAAOA,QAAQ,YAAYA,QAAQ,QAAQ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qCAAc,yBAAdA,oCAAAA,gBAAkBM,iBAAiB,qBAAnCN,uCAAAA,uBACAC,kBAAAA,IAAAA,qCAAc,yBAAdA,oCAAAA,gBAAkBK,iBAAiB,qBAAnCL,uCAAAA;QAEF,OAAQhE,iCAAAA,cAAeG,IAAI;YACzB,KAAK;YACL,KAAK;gBACH8D,aACE,AAACG,CAAAA,mBAAmB,EAAC,IAAMpE,CAAAA,cAAcsE,eAAe,IAAI,EAAC,KAC7D/B;gBACF;YACF,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAKA;gBACH0B,aAAaG;gBACb;YACF;gBACEpE;QACJ;QAEA,IAAIiE,YAAY;YACd,IAAIM,QAAQN;YAEZ,IAAItD,MAAM4D,KAAK,EAAE;gBACf,MAAMC,SAAmB,EAAE;gBAE3B,KAAK,MAAMC,SAAS9D,MAAM4D,KAAK,CAACG,KAAK,CAAC,MAAMC,KAAK,CAAC,GAAI;oBACpD,IAAIF,MAAMG,QAAQ,CAAC,6BAA6B;wBAC9C;oBACF;oBAEAJ,OAAOnD,IAAI,CAACoD;gBACd;gBAEAF,QAAQ,OAAOC,OAAOK,IAAI,CAAC,QAAQN;YACrC;YAEA5D,MAAM4D,KAAK,GAAG5D,MAAMmE,IAAI,GAAG,OAAOnE,MAAMoE,OAAO,GAAGR;QACpD;IACF;IAEA,OAAO5D;AACT","ignoreList":[0]} |
@@ -82,3 +82,3 @@ "use strict"; | ||
| const versionSuffix = logBundler ? ` (${(0, _bundler.bundlerName)((0, _bundler.getBundlerFromEnv)())})` : ''; | ||
| _log.bootstrap(`${(0, _picocolors.bold)((0, _picocolors.purple)(`${_log.prefixes.ready} Next.js ${"16.3.1-canary.10"}`))}${versionSuffix}`); | ||
| _log.bootstrap(`${(0, _picocolors.bold)((0, _picocolors.purple)(`${_log.prefixes.ready} Next.js ${"16.3.1-canary.11"}`))}${versionSuffix}`); | ||
| if (appUrl) { | ||
@@ -85,0 +85,0 @@ _log.bootstrap(`- Local: ${appUrl}`); |
@@ -14,3 +14,5 @@ "use strict"; | ||
| const _hotreloadertypes = require("../dev/hot-reloader-types"); | ||
| const _constants = require("./trace/constants"); | ||
| const _requestinsights = require("./trace/request-insights"); | ||
| const _tracer = require("./trace/tracer"); | ||
| class DevBundlerService { | ||
@@ -26,3 +28,5 @@ constructor(bundler, handler, requestInsightsEnabled){ | ||
| // TODO: remove after ensure is pulled out of server | ||
| return await this.bundler.hotReloader.ensurePage(definition); | ||
| return await (0, _tracer.getTracer)().trace(_constants.DevBundlerServiceSpan.ensurePage, { | ||
| spanName: 'compile route' | ||
| }, ()=>this.bundler.hotReloader.ensurePage(definition)); | ||
| }; | ||
@@ -29,0 +33,0 @@ this.logErrorWithOriginalStack = this.bundler.logErrorWithOriginalStack.bind(this.bundler); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/lib/dev-bundler-service.ts"],"sourcesContent":["import type { IncomingMessage } from 'http'\nimport type { DevBundler } from './router-utils/setup-dev-bundler'\nimport type { WorkerRequestHandler } from './types'\n\nimport { LRUCache } from './lru-cache'\nimport { createRequestResponseMocks } from './mock-request'\nimport {\n HMR_MESSAGE_SENT_TO_BROWSER,\n type HmrMessageSentToBrowser,\n type NextJsHotReloaderInterface,\n} from '../dev/hot-reloader-types'\nimport { subscribeRequestInsights } from './trace/request-insights'\n\n/**\n * The DevBundlerService provides an interface to perform tasks with the\n * bundler while in development.\n */\nexport class DevBundlerService {\n public appIsrManifestInner: InstanceType<typeof LRUCache<boolean>>\n public setCacheStatus: NextJsHotReloaderInterface['setCacheStatus']\n public setReactDebugChannel: NextJsHotReloaderInterface['setReactDebugChannel']\n public sendErrorsToBrowser: NextJsHotReloaderInterface['sendErrorsToBrowser']\n private unsubscribeRequestInsights?: () => void\n\n constructor(\n private readonly bundler: DevBundler,\n private readonly handler: WorkerRequestHandler,\n requestInsightsEnabled: boolean\n ) {\n this.appIsrManifestInner = new LRUCache(\n 8_000,\n\n function length() {\n return 16\n }\n )\n\n const { hotReloader } = bundler\n\n this.setCacheStatus = hotReloader.setCacheStatus.bind(hotReloader)\n this.setReactDebugChannel =\n hotReloader.setReactDebugChannel.bind(hotReloader)\n this.sendErrorsToBrowser = hotReloader.sendErrorsToBrowser.bind(hotReloader)\n\n if (requestInsightsEnabled) {\n this.unsubscribeRequestInsights = subscribeRequestInsights((insight) => {\n hotReloader.send({\n type: HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_INSIGHTS_UPDATE,\n insight,\n })\n })\n }\n }\n\n public close: NextJsHotReloaderInterface['close'] = () => {\n this.unsubscribeRequestInsights?.()\n this.bundler.hotReloader.close()\n }\n\n public ensurePage: typeof this.bundler.hotReloader.ensurePage = async (\n definition\n ) => {\n // TODO: remove after ensure is pulled out of server\n return await this.bundler.hotReloader.ensurePage(definition)\n }\n\n public getServerComponentsHmrRefreshHash(): string | undefined {\n return this.bundler.hotReloader.getServerComponentsHmrRefreshHash()\n }\n\n public logErrorWithOriginalStack =\n this.bundler.logErrorWithOriginalStack.bind(this.bundler)\n\n public async getFallbackErrorComponents(url?: string) {\n await this.bundler.hotReloader.buildFallbackError()\n // Build the error page to ensure the fallback is built too.\n // TODO: See if this can be moved into hotReloader or removed.\n await this.bundler.hotReloader.ensurePage({\n page: '/_error',\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n public async getCompilationError(page: string) {\n const errors = await this.bundler.hotReloader.getCompilationErrors(page)\n if (!errors) return\n\n // Return the very first error we found.\n return errors[0]\n }\n\n public async revalidate({\n urlPath,\n headers,\n opts: revalidateOpts,\n }: {\n urlPath: string\n headers: IncomingMessage['headers']\n opts: any\n }) {\n const mocked = createRequestResponseMocks({\n url: urlPath,\n headers,\n })\n\n await this.handler(mocked.req, mocked.res)\n await mocked.res.hasStreamed\n\n if (\n mocked.res.getHeader('x-nextjs-cache') !== 'REVALIDATED' &&\n mocked.res.statusCode !== 200 &&\n !(mocked.res.statusCode === 404 && revalidateOpts.unstable_onlyGenerated)\n ) {\n throw new Error(`Invalid response ${mocked.res.statusCode}`)\n }\n\n return {}\n }\n\n public get appIsrManifest() {\n const serializableManifest: Record<string, boolean> = {}\n\n for (const [key, value] of this.appIsrManifestInner) {\n serializableManifest[key] = value\n }\n\n return serializableManifest\n }\n\n public setIsrStatus(key: string, value: boolean | undefined) {\n if (value === undefined) {\n this.appIsrManifestInner.remove(key)\n } else {\n this.appIsrManifestInner.set(key, value)\n }\n\n // Only send the ISR manifest to legacy clients, i.e. Pages Router clients,\n // or App Router clients that have Cache Components disabled. The ISR\n // manifest is only used to inform the static indicator, which currently\n // does not provide useful information if Cache Components is enabled due to\n // its binary nature (i.e. it does not support showing info for partially\n // static pages).\n this.bundler?.hotReloader?.sendToLegacyClients({\n type: HMR_MESSAGE_SENT_TO_BROWSER.ISR_MANIFEST,\n data: this.appIsrManifest,\n })\n }\n\n public sendHmrMessage(message: HmrMessageSentToBrowser) {\n this.bundler.hotReloader.send(message)\n }\n}\n"],"names":["DevBundlerService","constructor","bundler","handler","requestInsightsEnabled","close","unsubscribeRequestInsights","hotReloader","ensurePage","definition","logErrorWithOriginalStack","bind","appIsrManifestInner","LRUCache","length","setCacheStatus","setReactDebugChannel","sendErrorsToBrowser","subscribeRequestInsights","insight","send","type","HMR_MESSAGE_SENT_TO_BROWSER","REQUEST_INSIGHTS_UPDATE","getServerComponentsHmrRefreshHash","getFallbackErrorComponents","url","buildFallbackError","page","clientOnly","undefined","getCompilationError","errors","getCompilationErrors","revalidate","urlPath","headers","opts","revalidateOpts","mocked","createRequestResponseMocks","req","res","hasStreamed","getHeader","statusCode","unstable_onlyGenerated","Error","appIsrManifest","serializableManifest","key","value","setIsrStatus","remove","set","sendToLegacyClients","ISR_MANIFEST","data","sendHmrMessage","message"],"mappings":";;;;+BAiBaA;;;eAAAA;;;0BAbY;6BACkB;kCAKpC;iCACkC;AAMlC,MAAMA;IAOXC,YACE,AAAiBC,OAAmB,EACp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C,mBAAmB,CAAC0C,GAAG,CAACJ,KAAKC;QACpC;SAQA,gBAAA,IAAI,CAACjD,OAAO,sBAAZ,4BAAA,cAAcK,WAAW,qBAAzB,0BAA2BgD,mBAAmB,CAAC;YAC7ClC,MAAMC,6CAA2B,CAACkC,YAAY;YAC9CC,MAAM,IAAI,CAACT,cAAc;QAC3B;IACF;IAEOU,eAAeC,OAAgC,EAAE;QACtD,IAAI,CAACzD,OAAO,CAACK,WAAW,CAACa,IAAI,CAACuC;IAChC;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/lib/dev-bundler-service.ts"],"sourcesContent":["import type { IncomingMessage } from 'http'\nimport type { DevBundler } from './router-utils/setup-dev-bundler'\nimport type { WorkerRequestHandler } from './types'\n\nimport { LRUCache } from './lru-cache'\nimport { createRequestResponseMocks } from './mock-request'\nimport {\n HMR_MESSAGE_SENT_TO_BROWSER,\n type HmrMessageSentToBrowser,\n type NextJsHotReloaderInterface,\n} from '../dev/hot-reloader-types'\nimport { DevBundlerServiceSpan } from './trace/constants'\nimport { subscribeRequestInsights } from './trace/request-insights'\nimport { getTracer } from './trace/tracer'\n\n/**\n * The DevBundlerService provides an interface to perform tasks with the\n * bundler while in development.\n */\nexport class DevBundlerService {\n public appIsrManifestInner: InstanceType<typeof LRUCache<boolean>>\n public setCacheStatus: NextJsHotReloaderInterface['setCacheStatus']\n public setReactDebugChannel: NextJsHotReloaderInterface['setReactDebugChannel']\n public sendErrorsToBrowser: NextJsHotReloaderInterface['sendErrorsToBrowser']\n private unsubscribeRequestInsights?: () => void\n\n constructor(\n private readonly bundler: DevBundler,\n private readonly handler: WorkerRequestHandler,\n requestInsightsEnabled: boolean\n ) {\n this.appIsrManifestInner = new LRUCache(\n 8_000,\n\n function length() {\n return 16\n }\n )\n\n const { hotReloader } = bundler\n\n this.setCacheStatus = hotReloader.setCacheStatus.bind(hotReloader)\n this.setReactDebugChannel =\n hotReloader.setReactDebugChannel.bind(hotReloader)\n this.sendErrorsToBrowser = hotReloader.sendErrorsToBrowser.bind(hotReloader)\n\n if (requestInsightsEnabled) {\n this.unsubscribeRequestInsights = subscribeRequestInsights((insight) => {\n hotReloader.send({\n type: HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_INSIGHTS_UPDATE,\n insight,\n })\n })\n }\n }\n\n public close: NextJsHotReloaderInterface['close'] = () => {\n this.unsubscribeRequestInsights?.()\n this.bundler.hotReloader.close()\n }\n\n public ensurePage: typeof this.bundler.hotReloader.ensurePage = async (\n definition\n ) => {\n // TODO: remove after ensure is pulled out of server\n return await getTracer().trace(\n DevBundlerServiceSpan.ensurePage,\n { spanName: 'compile route' },\n () => this.bundler.hotReloader.ensurePage(definition)\n )\n }\n\n public getServerComponentsHmrRefreshHash(): string | undefined {\n return this.bundler.hotReloader.getServerComponentsHmrRefreshHash()\n }\n\n public logErrorWithOriginalStack =\n this.bundler.logErrorWithOriginalStack.bind(this.bundler)\n\n public async getFallbackErrorComponents(url?: string) {\n await this.bundler.hotReloader.buildFallbackError()\n // Build the error page to ensure the fallback is built too.\n // TODO: See if this can be moved into hotReloader or removed.\n await this.bundler.hotReloader.ensurePage({\n page: '/_error',\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n public async getCompilationError(page: string) {\n const errors = await this.bundler.hotReloader.getCompilationErrors(page)\n if (!errors) return\n\n // Return the very first error we found.\n return errors[0]\n }\n\n public async revalidate({\n urlPath,\n headers,\n opts: revalidateOpts,\n }: {\n urlPath: string\n headers: IncomingMessage['headers']\n opts: any\n }) {\n const mocked = createRequestResponseMocks({\n url: urlPath,\n headers,\n })\n\n await this.handler(mocked.req, mocked.res)\n await mocked.res.hasStreamed\n\n if (\n mocked.res.getHeader('x-nextjs-cache') !== 'REVALIDATED' &&\n mocked.res.statusCode !== 200 &&\n !(mocked.res.statusCode === 404 && revalidateOpts.unstable_onlyGenerated)\n ) {\n throw new Error(`Invalid response ${mocked.res.statusCode}`)\n }\n\n return {}\n }\n\n public get appIsrManifest() {\n const serializableManifest: Record<string, boolean> = {}\n\n for (const [key, value] of this.appIsrManifestInner) {\n serializableManifest[key] = value\n }\n\n return serializableManifest\n }\n\n public setIsrStatus(key: string, value: boolean | undefined) {\n if (value === undefined) {\n this.appIsrManifestInner.remove(key)\n } else {\n this.appIsrManifestInner.set(key, value)\n }\n\n // Only send the ISR manifest to legacy clients, i.e. Pages Router clients,\n // or App Router clients that have Cache Components disabled. The ISR\n // manifest is only used to inform the static indicator, which currently\n // does not provide useful information if Cache Components is enabled due to\n // its binary nature (i.e. it does not support showing info for partially\n // static pages).\n this.bundler?.hotReloader?.sendToLegacyClients({\n type: HMR_MESSAGE_SENT_TO_BROWSER.ISR_MANIFEST,\n data: this.appIsrManifest,\n })\n }\n\n public sendHmrMessage(message: HmrMessageSentToBrowser) {\n this.bundler.hotReloader.send(message)\n }\n}\n"],"names":["DevBundlerService","constructor","bundler","handler","requestInsightsEnabled","close","unsubscribeRequestInsights","hotReloader","ensurePage","definition","getTracer","trace","DevBundlerServiceSpan","spanName","logErrorWithOriginalStack","bind","appIsrManifestInner","LRUCache","length","setCacheStatus","setReactDebugChannel","sendErrorsToBrowser","subscribeRequestInsights","insight","send","type","HMR_MESSAGE_SENT_TO_BROWSER","REQUEST_INSIGHTS_UPDATE","getServerComponentsHmrRefreshHash","getFallbackErrorComponents","url","buildFallbackError","page","clientOnly","undefined","getCompilationError","errors","getCompilationErrors","revalidate","urlPath","headers","opts","revalidateOpts","mocked","createRequestResponseMocks","req","res","hasStreamed","getHeader","statusCode","unstable_onlyGenerated","Error","appIsrManifest","serializableManifest","key","value","setIsrStatus","remove","set","sendToLegacyClients","ISR_MANIFEST","data","sendHmrMessage","message"],"mappings":";;;;+BAmBaA;;;eAAAA;;;0BAfY;6BACkB;kCAKpC;2BAC+B;iCACG;wBACf;AAMnB,MAAMA;IAOXC,YACE,AAAiBC,OAAmB,EACpC,AAAiBC,OAA6B,EAC9CC,sBAA+B,CAC/B;aAHiBF,UAAAA;aACAC,UAAAA;a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AACH;QAClC,OAAO;YACL,IAAI,CAACtC,mBAAmB,CAAC0C,GAAG,CAACJ,KAAKC;QACpC;SAQA,gBAAA,IAAI,CAACrD,OAAO,sBAAZ,4BAAA,cAAcK,WAAW,qBAAzB,0BAA2BoD,mBAAmB,CAAC;YAC7ClC,MAAMC,6CAA2B,CAACkC,YAAY;YAC9CC,MAAM,IAAI,CAACT,cAAc;QAC3B;IACF;IAEOU,eAAeC,OAAgC,EAAE;QACtD,IAAI,CAAC7D,OAAO,CAACK,WAAW,CAACiB,IAAI,CAACuC;IAChC;AACF","ignoreList":[0]} |
@@ -13,3 +13,3 @@ "use strict"; | ||
| const _handlers = require("../use-cache/handlers"); | ||
| const _encodecachetag = require("./encode-cache-tag"); | ||
| const _encodeheadersafe = require("./encode-header-safe"); | ||
| const _lazyresult = require("./lazy-result"); | ||
@@ -66,3 +66,3 @@ const getDerivedTags = (pathname)=>{ | ||
| for (let tag of derivedTags){ | ||
| tag = (0, _encodecachetag.encodeCacheTag)(`${_constants.NEXT_CACHE_IMPLICIT_TAG_ID}${tag}`); | ||
| tag = (0, _encodeheadersafe.encodeHeaderSafe)(`${_constants.NEXT_CACHE_IMPLICIT_TAG_ID}${tag}`); | ||
| tags.add(tag); | ||
@@ -73,3 +73,3 @@ } | ||
| if (pathname && (!fallbackRouteParams || fallbackRouteParams.size === 0)) { | ||
| const tag = (0, _encodecachetag.encodeCacheTag)(`${_constants.NEXT_CACHE_IMPLICIT_TAG_ID}${pathname}`); | ||
| const tag = (0, _encodeheadersafe.encodeHeaderSafe)(`${_constants.NEXT_CACHE_IMPLICIT_TAG_ID}${pathname}`); | ||
| tags.add(tag); | ||
@@ -76,0 +76,0 @@ } |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/lib/implicit-tags.ts"],"sourcesContent":["import { NEXT_CACHE_IMPLICIT_TAG_ID } from '../../lib/constants'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\nimport { getCacheHandlerEntries } from '../use-cache/handlers'\nimport { encodeCacheTag } from './encode-cache-tag'\nimport { createLazyResult, type LazyResult } from './lazy-result'\n\nexport interface ImplicitTags {\n /**\n * For legacy usage, the implicit tags are passed to the incremental cache\n * handler in `get` calls.\n */\n readonly tags: string[]\n\n /**\n * Modern cache handlers don't receive implicit tags. Instead, the implicit\n * tags' expirations are stored in the work unit store, and used to compare\n * with a cache entry's timestamp.\n *\n * Note: This map contains lazy results so that we can evaluate them when the\n * first cache entry is read. It allows us to skip fetching the expiration\n * values if no caches are read at all.\n */\n readonly expirationsByCacheKind: Map<string, LazyResult<number>>\n}\n\nconst getDerivedTags = (pathname: string): string[] => {\n const derivedTags: string[] = [`/layout`]\n\n // we automatically add the current path segments as tags\n // for revalidatePath handling\n if (pathname.startsWith('/')) {\n let end = pathname.indexOf('/', 1)\n\n while (true) {\n if (end === -1) {\n end = pathname.length\n }\n\n let curPathname = pathname.slice(0, end)\n if (curPathname) {\n // all derived tags other than the page are layout tags\n if (!curPathname.endsWith('/page') && !curPathname.endsWith('/route')) {\n curPathname = `${curPathname}${\n !curPathname.endsWith('/') ? '/' : ''\n }layout`\n }\n derivedTags.push(curPathname)\n }\n\n if (end === pathname.length) {\n break\n }\n end = pathname.indexOf('/', end + 1)\n }\n }\n return derivedTags\n}\n\n/**\n * Creates a map with lazy results that fetch the expiration value for the given\n * tags and respective cache kind when they're awaited for the first time.\n */\nfunction createTagsExpirationsByCacheKind(\n tags: string[]\n): Map<string, LazyResult<number>> {\n const expirationsByCacheKind = new Map<string, LazyResult<number>>()\n const cacheHandlers = getCacheHandlerEntries()\n\n if (cacheHandlers) {\n for (const [kind, cacheHandler] of cacheHandlers) {\n if ('getExpiration' in cacheHandler) {\n expirationsByCacheKind.set(\n kind,\n createLazyResult(async () => cacheHandler.getExpiration(tags))\n )\n }\n }\n }\n\n return expirationsByCacheKind\n}\n\nexport async function getImplicitTags(\n page: string,\n pathname: string,\n fallbackRouteParams: null | OpaqueFallbackRouteParams\n): Promise<ImplicitTags> {\n const tags = new Set<string>()\n\n // Add the derived tags from the page. Encode each tag so a non-ASCII\n // pathname doesn't trip header validation when written to\n // `x-next-cache-tags`. Idempotent on already-ASCII input.\n const derivedTags = getDerivedTags(page)\n for (let tag of derivedTags) {\n tag = encodeCacheTag(`${NEXT_CACHE_IMPLICIT_TAG_ID}${tag}`)\n tags.add(tag)\n }\n\n // Add the tags from the pathname. If the route has unknown params, we don't\n // want to add the pathname as a tag, as it will be invalid.\n if (pathname && (!fallbackRouteParams || fallbackRouteParams.size === 0)) {\n const tag = encodeCacheTag(`${NEXT_CACHE_IMPLICIT_TAG_ID}${pathname}`)\n tags.add(tag)\n }\n\n if (tags.has(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)) {\n tags.add(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)\n }\n\n if (tags.has(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)) {\n tags.add(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)\n }\n\n const tagsArray = Array.from(tags)\n return {\n tags: tagsArray,\n expirationsByCacheKind: createTagsExpirationsByCacheKind(tagsArray),\n }\n}\n"],"names":["getImplicitTags","getDerivedTags","pathname","derivedTags","startsWith","end","indexOf","length","curPathname","slice","endsWith","push","createTagsExpirationsByCacheKind","tags","expirationsByCacheKind","Map","cacheHandlers","getCacheHandlerEntries","kind","cacheHandler","set","createLazyResult","getExpiration","page","fallbackRouteParams","Set","tag","encodeCacheTag","NEXT_CACHE_IMPLICIT_TAG_ID","add","size","has","tagsArray","Array","from"],"mappings":";;;;+BAkFsBA;;;eAAAA;;;2BAlFqB;0BAEJ;gCACR;4BACmB;AAqBlD,MAAMC,iBAAiB,CAACC;IACtB,MAAMC,cAAwB;QAAC,CAAC,OAAO,CAAC;KAAC;IAEzC,yDAAyD;IACzD,8BAA8B;IAC9B,IAAID,SAASE,UAAU,CAAC,MAAM;QAC5B,IAAIC,MAAMH,SAASI,OAAO,CAAC,KAAK;QAEhC,MAAO,KAAM;YAC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C,GAAGC,qCAA0B,GAAG1B,UAAU;QACrEW,KAAKgB,GAAG,CAACH;IACX;IAEA,IAAIb,KAAKkB,GAAG,CAAC,GAAGH,qCAA0B,CAAC,CAAC,CAAC,GAAG;QAC9Cf,KAAKgB,GAAG,CAAC,GAAGD,qCAA0B,CAAC,MAAM,CAAC;IAChD;IAEA,IAAIf,KAAKkB,GAAG,CAAC,GAAGH,qCAA0B,CAAC,MAAM,CAAC,GAAG;QACnDf,KAAKgB,GAAG,CAAC,GAAGD,qCAA0B,CAAC,CAAC,CAAC;IAC3C;IAEA,MAAMI,YAAYC,MAAMC,IAAI,CAACrB;IAC7B,OAAO;QACLA,MAAMmB;QACNlB,wBAAwBF,iCAAiCoB;IAC3D;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/lib/implicit-tags.ts"],"sourcesContent":["import { NEXT_CACHE_IMPLICIT_TAG_ID } from '../../lib/constants'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\nimport { getCacheHandlerEntries } from '../use-cache/handlers'\nimport { encodeHeaderSafe } from './encode-header-safe'\nimport { createLazyResult, type LazyResult } from './lazy-result'\n\nexport interface ImplicitTags {\n /**\n * For legacy usage, the implicit tags are passed to the incremental cache\n * handler in `get` calls.\n */\n readonly tags: string[]\n\n /**\n * Modern cache handlers don't receive implicit tags. Instead, the implicit\n * tags' expirations are stored in the work unit store, and used to compare\n * with a cache entry's timestamp.\n *\n * Note: This map contains lazy results so that we can evaluate them when the\n * first cache entry is read. It allows us to skip fetching the expiration\n * values if no caches are read at all.\n */\n readonly expirationsByCacheKind: Map<string, LazyResult<number>>\n}\n\nconst getDerivedTags = (pathname: string): string[] => {\n const derivedTags: string[] = [`/layout`]\n\n // we automatically add the current path segments as tags\n // for revalidatePath handling\n if (pathname.startsWith('/')) {\n let end = pathname.indexOf('/', 1)\n\n while (true) {\n if (end === -1) {\n end = pathname.length\n }\n\n let curPathname = pathname.slice(0, end)\n if (curPathname) {\n // all derived tags other than the page are layout tags\n if (!curPathname.endsWith('/page') && !curPathname.endsWith('/route')) {\n curPathname = `${curPathname}${\n !curPathname.endsWith('/') ? '/' : ''\n }layout`\n }\n derivedTags.push(curPathname)\n }\n\n if (end === pathname.length) {\n break\n }\n end = pathname.indexOf('/', end + 1)\n }\n }\n return derivedTags\n}\n\n/**\n * Creates a map with lazy results that fetch the expiration value for the given\n * tags and respective cache kind when they're awaited for the first time.\n */\nfunction createTagsExpirationsByCacheKind(\n tags: string[]\n): Map<string, LazyResult<number>> {\n const expirationsByCacheKind = new Map<string, LazyResult<number>>()\n const cacheHandlers = getCacheHandlerEntries()\n\n if (cacheHandlers) {\n for (const [kind, cacheHandler] of cacheHandlers) {\n if ('getExpiration' in cacheHandler) {\n expirationsByCacheKind.set(\n kind,\n createLazyResult(async () => cacheHandler.getExpiration(tags))\n )\n }\n }\n }\n\n return expirationsByCacheKind\n}\n\nexport async function getImplicitTags(\n page: string,\n pathname: string,\n fallbackRouteParams: null | OpaqueFallbackRouteParams\n): Promise<ImplicitTags> {\n const tags = new Set<string>()\n\n // Add the derived tags from the page. Encode each tag so a non-ASCII\n // pathname doesn't trip header validation when written to\n // `x-next-cache-tags`. Idempotent on already-ASCII input.\n const derivedTags = getDerivedTags(page)\n for (let tag of derivedTags) {\n tag = encodeHeaderSafe(`${NEXT_CACHE_IMPLICIT_TAG_ID}${tag}`)\n tags.add(tag)\n }\n\n // Add the tags from the pathname. If the route has unknown params, we don't\n // want to add the pathname as a tag, as it will be invalid.\n if (pathname && (!fallbackRouteParams || fallbackRouteParams.size === 0)) {\n const tag = encodeHeaderSafe(`${NEXT_CACHE_IMPLICIT_TAG_ID}${pathname}`)\n tags.add(tag)\n }\n\n if (tags.has(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)) {\n tags.add(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)\n }\n\n if (tags.has(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)) {\n tags.add(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)\n }\n\n const tagsArray = Array.from(tags)\n return {\n tags: tagsArray,\n expirationsByCacheKind: createTagsExpirationsByCacheKind(tagsArray),\n }\n}\n"],"names":["getImplicitTags","getDerivedTags","pathname","derivedTags","startsWith","end","indexOf","length","curPathname","slice","endsWith","push","createTagsExpirationsByCacheKind","tags","expirationsByCacheKind","Map","cacheHandlers","getCacheHandlerEntries","kind","cacheHandler","set","createLazyResult","getExpiration","page","fallbackRouteParams","Set","tag","encodeHeaderSafe","NEXT_CACHE_IMPLICIT_TAG_ID","add","size","has","tagsArray","Array","from"],"mappings":";;;;+BAkFsBA;;;eAAAA;;;2BAlFqB;0BAEJ;kCACN;4BACiB;AAqBlD,MAAMC,iBAAiB,CAACC;IACtB,MAAMC,cAAwB;QAAC,CAAC,OAAO,CAAC;KAAC;IAEzC,yDAAyD;IACzD,8BAA8B;IAC9B,IAAID,SAASE,UAAU,CAAC,MAAM;QAC5B,IAAIC,MAAMH,SAASI,OAAO,CAAC,KAAK;QAEhC,MAAO,KAAM;YACX,IAAID,QAAQ,CAAC,GAAG;gBACdA,MAAMH,SAASK,MAAM;YACvB;YAEA,IAAIC,cAAcN,SAASO,KAAK,CAAC,GAAGJ;YACpC,IAAIG,aAAa;gBACf,uDAAuD;gBACvD,IAAI,CAACA,YAAYE,QAAQ,CAAC,YAAY,CAACF,YAAYE,QAAQ,CAAC,WAAW;oBACrEF,cAAc,GAAGA,cACf,CAACA,YAAYE,QAAQ,CAAC,OAAO,MAAM,GACpC,MAAM,CAAC;gBACV;gBACAP,YAAYQ,IAAI,CAACH;YACnB;YAEA,IAAIH,QAAQH,SAASK,MAAM,EAAE;gBAC3B;YACF;YACAF,MAAMH,SAASI,OAAO,CAAC,KAAKD,MAAM;QACpC;IACF;IACA,OAAOF;AACT;AAEA;;;CAGC,GACD,SAASS,iCACPC,IAAc;IAEd,MAAMC,yBAAyB,IAAIC;IACnC,MAAMC,gBAAgBC,IAAAA,gCAAsB;IAE5C,IAAID,eAAe;QACjB,KAAK,MAAM,CAACE,MAAMC,aAAa,IAAIH,cAAe;YAChD,IAAI,mBAAmBG,cAAc;gBACnCL,uBAAuBM,GAAG,CACxBF,MACAG,IAAAA,4BAAgB,EAAC,UAAYF,aAAaG,aAAa,CAACT;YAE5D;QACF;IACF;IAEA,OAAOC;AACT;AAEO,eAAed,gBACpBuB,IAAY,EACZrB,QAAgB,EAChBsB,mBAAqD;IAErD,MAAMX,OAAO,IAAIY;IAEjB,qEAAqE;IACrE,0DAA0D;IAC1D,0DAA0D;IAC1D,MAAMtB,cAAcF,eAAesB;IACnC,KAAK,IAAIG,OAAOvB,YAAa;QAC3BuB,MAAMC,IAAAA,kCAAgB,EAAC,GAAGC,qCAA0B,GAAGF,KAAK;QAC5Db,KAAKgB,GAAG,CAACH;IACX;IAEA,4EAA4E;IAC5E,4DAA4D;IAC5D,IAAIxB,YAAa,CAAA,CAACsB,uBAAuBA,oBAAoBM,IAAI,KAAK,CAAA,GAAI;QACxE,MAAMJ,MAAMC,IAAAA,kCAAgB,EAAC,GAAGC,qCAA0B,GAAG1B,UAAU;QACvEW,KAAKgB,GAAG,CAACH;IACX;IAEA,IAAIb,KAAKkB,GAAG,CAAC,GAAGH,qCAA0B,CAAC,CAAC,CAAC,GAAG;QAC9Cf,KAAKgB,GAAG,CAAC,GAAGD,qCAA0B,CAAC,MAAM,CAAC;IAChD;IAEA,IAAIf,KAAKkB,GAAG,CAAC,GAAGH,qCAA0B,CAAC,MAAM,CAAC,GAAG;QACnDf,KAAKgB,GAAG,CAAC,GAAGD,qCAA0B,CAAC,CAAC,CAAC;IAC3C;IAEA,MAAMI,YAAYC,MAAMC,IAAI,CAACrB;IAC7B,OAAO;QACLA,MAAMmB;QACNlB,wBAAwBF,iCAAiCoB;IAC3D;AACF","ignoreList":[0]} |
| import type { OpaqueFallbackRouteParams } from '../request/fallback-params'; | ||
| import type { Params } from '../request/params'; | ||
| export declare function hasNonRootStaticParams(params: Params, rootParams: Params, fallbackParams: OpaqueFallbackRouteParams | null | undefined): boolean; | ||
| export declare function allParamsAreRootParams(underlyingParams: Params, rootParams: Params): boolean; | ||
| export declare function isEmptyParams(params: Params): boolean; | ||
| export declare function hasFallbackRouteParams(underlyingParams: Params, fallbackParams: OpaqueFallbackRouteParams | null | undefined): boolean; |
@@ -8,3 +8,2 @@ "use strict"; | ||
| hasFallbackRouteParams: null, | ||
| hasNonRootStaticParams: null, | ||
| isEmptyParams: null | ||
@@ -25,5 +24,2 @@ }); | ||
| }, | ||
| hasNonRootStaticParams: function() { | ||
| return hasNonRootStaticParams; | ||
| }, | ||
| isEmptyParams: function() { | ||
@@ -33,16 +29,2 @@ return isEmptyParams; | ||
| }); | ||
| function hasNonRootStaticParams(params, rootParams, fallbackParams) { | ||
| for(const paramName in params){ | ||
| if (!Object.hasOwn(rootParams, paramName) && isStaticParam(paramName, fallbackParams)) { | ||
| return true; | ||
| } | ||
| } | ||
| return false; | ||
| } | ||
| function isStaticParam(paramName, fallbackParams) { | ||
| // NOTE: Assume that undefined fallback params mean that all of the params are static. | ||
| if (!fallbackParams) return true; | ||
| // If the param isn't a fallback param, it must be static. | ||
| return !fallbackParams.has(paramName); | ||
| } | ||
| function allParamsAreRootParams(underlyingParams, rootParams) { | ||
@@ -49,0 +31,0 @@ for(const paramName in underlyingParams){ |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/lib/params-utils.ts"],"sourcesContent":["import type { OpaqueFallbackRouteParams } from '../request/fallback-params'\nimport type { Params } from '../request/params'\n\nexport function hasNonRootStaticParams(\n params: Params,\n rootParams: Params,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined\n) {\n for (const paramName in params) {\n if (\n !Object.hasOwn(rootParams, paramName) &&\n isStaticParam(paramName, fallbackParams)\n ) {\n return true\n }\n }\n return false\n}\n\nfunction isStaticParam(\n paramName: string,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined\n) {\n // NOTE: Assume that undefined fallback params mean that all of the params are static.\n if (!fallbackParams) return true\n // If the param isn't a fallback param, it must be static.\n return !fallbackParams.has(paramName)\n}\n\nexport function allParamsAreRootParams(\n underlyingParams: Params,\n rootParams: Params\n) {\n for (const paramName in underlyingParams) {\n if (!Object.hasOwn(rootParams, paramName)) {\n return false\n }\n }\n return true\n}\n\nexport function isEmptyParams(params: Params): boolean {\n for (const _paramKey in params) {\n return false\n }\n return true\n}\n\nexport function hasFallbackRouteParams(\n underlyingParams: Params,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined\n): boolean {\n if (fallbackParams) {\n for (let key in underlyingParams) {\n if (fallbackParams.has(key)) {\n return true\n }\n }\n }\n return false\n}\n"],"names":["allParamsAreRootParams","hasFallbackRouteParams","hasNonRootStaticParams","isEmptyParams","params","rootParams","fallbackParams","paramName","Object","hasOwn","isStaticParam","has","underlyingParams","_paramKey","key"],"mappings":";;;;;;;;;;;;;;;;;IA6BgBA,sBAAsB;eAAtBA;;IAmBAC,sBAAsB;eAAtBA;;IA7CAC,sBAAsB;eAAtBA;;IAsCAC,aAAa;eAAbA;;;AAtCT,SAASD,uBACdE,MAAc,EACdC,UAAkB,EAClBC,cAA4D;IAE5D,IAAK,MAAMC,aAAaH,OAAQ;QAC9B,IACE,CAACI,OAAOC,MAAM,CAACJ,YAAYE,cAC3BG,cAAcH,WAAWD,iBACzB;YACA,OAAO;QACT;IACF;IACA,OAAO;AACT;AAEA,SAASI,cACPH,SAAiB,EACjBD,cAA4D;IAE5D,sFAAsF;IACtF,IAAI,CAACA,gBAAgB,OAAO;IAC5B,0DAA0D;IAC1D,OAAO,CAACA,eAAeK,GAAG,CAACJ;AAC7B;AAEO,SAASP,uBACdY,gBAAwB,EACxBP,UAAkB;IAElB,IAAK,MAAME,aAAaK,iBAAkB;QACxC,IAAI,CAACJ,OAAOC,MAAM,CAACJ,YAAYE,YAAY;YACzC,OAAO;QACT;IACF;IACA,OAAO;AACT;AAEO,SAASJ,cAAcC,MAAc;IAC1C,IAAK,MAAMS,aAAaT,OAAQ;QAC9B,OAAO;IACT;IACA,OAAO;AACT;AAEO,SAASH,uBACdW,gBAAwB,EACxBN,cAA4D;IAE5D,IAAIA,gBAAgB;QAClB,IAAK,IAAIQ,OAAOF,iBAAkB;YAChC,IAAIN,eAAeK,GAAG,CAACG,MAAM;gBAC3B,OAAO;YACT;QACF;IACF;IACA,OAAO;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/lib/params-utils.ts"],"sourcesContent":["import type { OpaqueFallbackRouteParams } from '../request/fallback-params'\nimport type { Params } from '../request/params'\n\nexport function allParamsAreRootParams(\n underlyingParams: Params,\n rootParams: Params\n) {\n for (const paramName in underlyingParams) {\n if (!Object.hasOwn(rootParams, paramName)) {\n return false\n }\n }\n return true\n}\n\nexport function isEmptyParams(params: Params): boolean {\n for (const _paramKey in params) {\n return false\n }\n return true\n}\n\nexport function hasFallbackRouteParams(\n underlyingParams: Params,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined\n): boolean {\n if (fallbackParams) {\n for (let key in underlyingParams) {\n if (fallbackParams.has(key)) {\n return true\n }\n }\n }\n return false\n}\n"],"names":["allParamsAreRootParams","hasFallbackRouteParams","isEmptyParams","underlyingParams","rootParams","paramName","Object","hasOwn","params","_paramKey","fallbackParams","key","has"],"mappings":";;;;;;;;;;;;;;;;IAGgBA,sBAAsB;eAAtBA;;IAmBAC,sBAAsB;eAAtBA;;IAPAC,aAAa;eAAbA;;;AAZT,SAASF,uBACdG,gBAAwB,EACxBC,UAAkB;IAElB,IAAK,MAAMC,aAAaF,iBAAkB;QACxC,IAAI,CAACG,OAAOC,MAAM,CAACH,YAAYC,YAAY;YACzC,OAAO;QACT;IACF;IACA,OAAO;AACT;AAEO,SAASH,cAAcM,MAAc;IAC1C,IAAK,MAAMC,aAAaD,OAAQ;QAC9B,OAAO;IACT;IACA,OAAO;AACT;AAEO,SAASP,uBACdE,gBAAwB,EACxBO,cAA4D;IAE5D,IAAIA,gBAAgB;QAClB,IAAK,IAAIC,OAAOR,iBAAkB;YAChC,IAAIO,eAAeE,GAAG,CAACD,MAAM;gBAC3B,OAAO;YACT;QACF;IACF;IACA,OAAO;AACT","ignoreList":[0]} |
@@ -47,3 +47,3 @@ "use strict"; | ||
| const _stagedrendering = require("../app-render/staged-rendering"); | ||
| const _encodecachetag = require("./encode-cache-tag"); | ||
| const _encodeheadersafe = require("./encode-header-safe"); | ||
| const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'; | ||
@@ -127,3 +127,3 @@ /** | ||
| // validation. Length is checked on the raw input above. | ||
| validTags.push((0, _encodecachetag.encodeCacheTag)(tag)); | ||
| validTags.push((0, _encodeheadersafe.encodeHeaderSafe)(tag)); | ||
| } | ||
@@ -130,0 +130,0 @@ if (validTags.length > _constants1.NEXT_CACHE_TAG_MAX_ITEMS) { |
@@ -180,3 +180,3 @@ // Start CPU profile if it wasn't already started. | ||
| let { port } = serverOptions; | ||
| process.title = `next-server (v${"16.3.1-canary.10"})`; | ||
| process.title = `next-server (v${"16.3.1-canary.11"})`; | ||
| let handlersReady = ()=>{}; | ||
@@ -183,0 +183,0 @@ let handlersError = ()=>{}; |
@@ -85,2 +85,9 @@ /** | ||
| } | ||
| declare enum DevRouteMatcherManagerSpan { | ||
| ensureRoute = "DevRouteMatcherManager.ensureRoute", | ||
| reloadMatchers = "DevRouteMatcherManager.reloadMatchers" | ||
| } | ||
| declare enum DevBundlerServiceSpan { | ||
| ensurePage = "DevBundlerService.ensurePage" | ||
| } | ||
| declare enum RouterSpan { | ||
@@ -102,6 +109,6 @@ executeRoute = "Router.executeRoute" | ||
| } | ||
| type SpanTypes = `${BaseServerSpan}` | `${LoadComponentsSpan}` | `${NextServerSpan}` | `${StartServerSpan}` | `${NextNodeServerSpan}` | `${RenderSpan}` | `${RouterSpan}` | `${AppRenderSpan}` | `${NodeSpan}` | `${AppRouteRouteHandlersSpan}` | `${ResolveMetadataSpan}` | `${MiddlewareSpan}`; | ||
| type SpanTypes = `${BaseServerSpan}` | `${LoadComponentsSpan}` | `${NextServerSpan}` | `${StartServerSpan}` | `${NextNodeServerSpan}` | `${RenderSpan}` | `${RouterSpan}` | `${AppRenderSpan}` | `${DevRouteMatcherManagerSpan}` | `${DevBundlerServiceSpan}` | `${NodeSpan}` | `${AppRouteRouteHandlersSpan}` | `${ResolveMetadataSpan}` | `${MiddlewareSpan}`; | ||
| export declare const NextVanillaSpanAllowlist: Set<BaseServerSpan | NextNodeServerSpan | RenderSpan | AppRenderSpan | NodeSpan | AppRouteRouteHandlersSpan | ResolveMetadataSpan | MiddlewareSpan>; | ||
| export declare const LogSpanAllowList: Set<NextNodeServerSpan>; | ||
| export { BaseServerSpan, LoadComponentsSpan, NextServerSpan, NextNodeServerSpan, StartServerSpan, RenderSpan, RouterSpan, AppRenderSpan, NodeSpan, AppRouteRouteHandlersSpan, ResolveMetadataSpan, MiddlewareSpan, }; | ||
| export { BaseServerSpan, LoadComponentsSpan, NextServerSpan, NextNodeServerSpan, StartServerSpan, RenderSpan, RouterSpan, AppRenderSpan, DevRouteMatcherManagerSpan, DevBundlerServiceSpan, NodeSpan, AppRouteRouteHandlersSpan, ResolveMetadataSpan, MiddlewareSpan, }; | ||
| export type { SpanTypes }; |
@@ -15,2 +15,4 @@ /** | ||
| BaseServerSpan: null, | ||
| DevBundlerServiceSpan: null, | ||
| DevRouteMatcherManagerSpan: null, | ||
| LoadComponentsSpan: null, | ||
@@ -44,2 +46,8 @@ LogSpanAllowList: null, | ||
| }, | ||
| DevBundlerServiceSpan: function() { | ||
| return DevBundlerServiceSpan; | ||
| }, | ||
| DevRouteMatcherManagerSpan: function() { | ||
| return DevRouteMatcherManagerSpan; | ||
| }, | ||
| LoadComponentsSpan: function() { | ||
@@ -165,2 +173,11 @@ return LoadComponentsSpan; | ||
| }(AppRenderSpan || {}); | ||
| var DevRouteMatcherManagerSpan = /*#__PURE__*/ function(DevRouteMatcherManagerSpan) { | ||
| DevRouteMatcherManagerSpan["ensureRoute"] = "DevRouteMatcherManager.ensureRoute"; | ||
| DevRouteMatcherManagerSpan["reloadMatchers"] = "DevRouteMatcherManager.reloadMatchers"; | ||
| return DevRouteMatcherManagerSpan; | ||
| }(DevRouteMatcherManagerSpan || {}); | ||
| var DevBundlerServiceSpan = /*#__PURE__*/ function(DevBundlerServiceSpan) { | ||
| DevBundlerServiceSpan["ensurePage"] = "DevBundlerService.ensurePage"; | ||
| return DevBundlerServiceSpan; | ||
| }(DevBundlerServiceSpan || {}); | ||
| var RouterSpan = /*#__PURE__*/ function(RouterSpan) { | ||
@@ -167,0 +184,0 @@ RouterSpan["executeRoute"] = "Router.executeRoute"; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/lib/trace/constants.ts"],"sourcesContent":["/**\n * Contains predefined constants for the trace span name in next/server.\n *\n * Currently, next/server/tracer is internal implementation only for tracking\n * next.js's implementation only with known span names defined here.\n **/\n\n// eslint typescript has a bug with TS enums\n\nenum BaseServerSpan {\n handleRequest = 'BaseServer.handleRequest',\n run = 'BaseServer.run',\n pipe = 'BaseServer.pipe',\n getStaticHTML = 'BaseServer.getStaticHTML',\n render = 'BaseServer.render',\n renderToResponseWithComponents = 'BaseServer.renderToResponseWithComponents',\n renderToResponse = 'BaseServer.renderToResponse',\n renderToHTML = 'BaseServer.renderToHTML',\n renderError = 'BaseServer.renderError',\n renderErrorToResponse = 'BaseServer.renderErrorToResponse',\n renderErrorToHTML = 'BaseServer.renderErrorToHTML',\n render404 = 'BaseServer.render404',\n}\n\nenum LoadComponentsSpan {\n loadDefaultErrorComponents = 'LoadComponents.loadDefaultErrorComponents',\n loadComponents = 'LoadComponents.loadComponents',\n}\n\nenum NextServerSpan {\n getRequestHandler = 'NextServer.getRequestHandler',\n getRequestHandlerWithMetadata = 'NextServer.getRequestHandlerWithMetadata',\n getServer = 'NextServer.getServer',\n getServerRequestHandler = 'NextServer.getServerRequestHandler',\n createServer = 'createServer.createServer',\n}\n\nenum NextNodeServerSpan {\n compression = 'NextNodeServer.compression',\n getBuildId = 'NextNodeServer.getBuildId',\n createComponentTree = 'NextNodeServer.createComponentTree',\n clientComponentLoading = 'NextNodeServer.clientComponentLoading',\n getLayoutOrPageModule = 'NextNodeServer.getLayoutOrPageModule',\n generateStaticRoutes = 'NextNodeServer.generateStaticRoutes',\n generateFsStaticRoutes = 'NextNodeServer.generateFsStaticRoutes',\n generatePublicRoutes = 'NextNodeServer.generatePublicRoutes',\n generateImageRoutes = 'NextNodeServer.generateImageRoutes.route',\n sendRenderResult = 'NextNodeServer.sendRenderResult',\n proxyRequest = 'NextNodeServer.proxyRequest',\n runApi = 'NextNodeServer.runApi',\n render = 'NextNodeServer.render',\n renderHTML = 'NextNodeServer.renderHTML',\n imageOptimizer = 'NextNodeServer.imageOptimizer',\n getPagePath = 'NextNodeServer.getPagePath',\n getRoutesManifest = 'NextNodeServer.getRoutesManifest',\n findPageComponents = 'NextNodeServer.findPageComponents',\n getFontManifest = 'NextNodeServer.getFontManifest',\n getServerComponentManifest = 'NextNodeServer.getServerComponentManifest',\n getRequestHandler = 'NextNodeServer.getRequestHandler',\n renderToHTML = 'NextNodeServer.renderToHTML',\n renderError = 'NextNodeServer.renderError',\n renderErrorToHTML = 'NextNodeServer.renderErrorToHTML',\n render404 = 'NextNodeServer.render404',\n startResponse = 'NextNodeServer.startResponse',\n\n // nested inner span, does not require parent scope name\n route = 'route',\n onProxyReq = 'onProxyReq',\n apiResolver = 'apiResolver',\n internalFetch = 'internalFetch',\n}\n\nenum StartServerSpan {\n startServer = 'startServer.startServer',\n}\n\nenum RenderSpan {\n getServerSideProps = 'Render.getServerSideProps',\n getStaticProps = 'Render.getStaticProps',\n renderToString = 'Render.renderToString',\n renderDocument = 'Render.renderDocument',\n createBodyResult = 'Render.createBodyResult',\n}\n\nenum AppRenderSpan {\n renderToString = 'AppRender.renderToString',\n renderToReadableStream = 'AppRender.renderToReadableStream',\n getBodyResult = 'AppRender.getBodyResult',\n fetch = 'AppRender.fetch',\n waitShellReady = 'AppRender.waitShellReady',\n renderToNodeFizzStream = 'AppRender.renderToNodeFizzStream',\n instantInsights = 'AppRender.instantInsights',\n instantInsightsPrepareValidation = 'AppRender.instantInsights.prepareValidation',\n instantInsightsRunValidation = 'AppRender.instantInsights.runValidation',\n}\n\nenum RouterSpan {\n executeRoute = 'Router.executeRoute',\n}\n\nenum NodeSpan {\n runHandler = 'Node.runHandler',\n}\n\nenum AppRouteRouteHandlersSpan {\n runHandler = 'AppRouteRouteHandlers.runHandler',\n}\n\nenum ResolveMetadataSpan {\n generateMetadata = 'ResolveMetadata.generateMetadata',\n generateViewport = 'ResolveMetadata.generateViewport',\n}\n\nenum MiddlewareSpan {\n execute = 'Middleware.execute',\n}\n\ntype SpanTypes =\n | `${BaseServerSpan}`\n | `${LoadComponentsSpan}`\n | `${NextServerSpan}`\n | `${StartServerSpan}`\n | `${NextNodeServerSpan}`\n | `${RenderSpan}`\n | `${RouterSpan}`\n | `${AppRenderSpan}`\n | `${NodeSpan}`\n | `${AppRouteRouteHandlersSpan}`\n | `${ResolveMetadataSpan}`\n | `${MiddlewareSpan}`\n\n// This list is used to filter out spans that are not relevant to the user\nexport const NextVanillaSpanAllowlist = new Set([\n MiddlewareSpan.execute,\n BaseServerSpan.handleRequest,\n RenderSpan.getServerSideProps,\n RenderSpan.getStaticProps,\n AppRenderSpan.fetch,\n AppRenderSpan.getBodyResult,\n RenderSpan.renderDocument,\n NodeSpan.runHandler,\n AppRouteRouteHandlersSpan.runHandler,\n ResolveMetadataSpan.generateMetadata,\n ResolveMetadataSpan.generateViewport,\n NextNodeServerSpan.createComponentTree,\n NextNodeServerSpan.findPageComponents,\n NextNodeServerSpan.getLayoutOrPageModule,\n NextNodeServerSpan.startResponse,\n NextNodeServerSpan.clientComponentLoading,\n])\n\n// These Spans are allowed to be always logged\n// when the otel log prefix env is set\nexport const LogSpanAllowList = new Set([\n NextNodeServerSpan.findPageComponents,\n NextNodeServerSpan.createComponentTree,\n NextNodeServerSpan.clientComponentLoading,\n])\n\nexport {\n BaseServerSpan,\n LoadComponentsSpan,\n NextServerSpan,\n NextNodeServerSpan,\n StartServerSpan,\n RenderSpan,\n RouterSpan,\n AppRenderSpan,\n NodeSpan,\n AppRouteRouteHandlersSpan,\n ResolveMetadataSpan,\n MiddlewareSpan,\n}\n\nexport type { SpanTypes }\n"],"names":["AppRenderSpan","AppRouteRouteHandlersSpan","BaseServerSpan","LoadComponentsSpan","LogSpanAllowList","MiddlewareSpan","NextNodeServerSpan","NextServerSpan","NextVanillaSpanAllowlist","NodeSpan","RenderSpan","ResolveMetadataSpan","RouterSpan","StartServerSpan","Set"],"mappings":"AAAA;;;;;EAKE,GAEF,4CAA4C;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAgK1CA,aAAa;eAAbA;;IAEAC,yBAAyB;eAAzBA;;IATAC,cAAc;eAAdA;;IACAC,kBAAkB;eAAlBA;;IARWC,gBAAgB;eAAhBA;;IAkBXC,cAAc;eAAdA;;IARAC,kBAAkB;eAAlBA;;IADAC,cAAc;eAAdA;;IA9BWC,wBAAwB;eAAxBA;;IAoCXC,QAAQ;eAARA;;IAHAC,UAAU;eAAVA;;IAKAC,mBAAmB;eAAnBA;;IAJAC,UAAU;eAAVA;;IAFAC,eAAe;eAAfA;;;AA3JF,IAAA,AAAKX,wCAAAA;;;;;;;;;;;;;WAAAA;EAAAA;AAeL,IAAA,AAAKC,4CAAAA;;;WAAAA;EAAAA;AAKL,IAAA,AAAKI,wCAAAA;;;;;;WAAAA;EAAAA;AAQL,IAAA,AAAKD,4CAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;IA4BH,wDAAwD;;;;;WA5BrDA;EAAAA;AAmCL,IAAA,AAAKO,yCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKH,oCAAAA;;;;;;WAAAA;EAAAA;AAQL,IAAA,AAAKV,uCAAAA;;;;;;;;;;WAAAA;EAAAA;AAYL,IAAA,AAAKY,oCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKH,kCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKR,mDAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKU,6CAAAA;;;WAAAA;EAAAA;AAKL,IAAA,AAAKN,wCAAAA;;WAAAA;EAAAA;AAmBE,MAAMG,2BAA2B,IAAIM,IAAI;;;;;;;;;;;;;;;;;CAiB/C;AAIM,MAAMV,mBAAmB,IAAIU,IAAI;;;;CAIvC","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/lib/trace/constants.ts"],"sourcesContent":["/**\n * Contains predefined constants for the trace span name in next/server.\n *\n * Currently, next/server/tracer is internal implementation only for tracking\n * next.js's implementation only with known span names defined here.\n **/\n\n// eslint typescript has a bug with TS enums\n\nenum BaseServerSpan {\n handleRequest = 'BaseServer.handleRequest',\n run = 'BaseServer.run',\n pipe = 'BaseServer.pipe',\n getStaticHTML = 'BaseServer.getStaticHTML',\n render = 'BaseServer.render',\n renderToResponseWithComponents = 'BaseServer.renderToResponseWithComponents',\n renderToResponse = 'BaseServer.renderToResponse',\n renderToHTML = 'BaseServer.renderToHTML',\n renderError = 'BaseServer.renderError',\n renderErrorToResponse = 'BaseServer.renderErrorToResponse',\n renderErrorToHTML = 'BaseServer.renderErrorToHTML',\n render404 = 'BaseServer.render404',\n}\n\nenum LoadComponentsSpan {\n loadDefaultErrorComponents = 'LoadComponents.loadDefaultErrorComponents',\n loadComponents = 'LoadComponents.loadComponents',\n}\n\nenum NextServerSpan {\n getRequestHandler = 'NextServer.getRequestHandler',\n getRequestHandlerWithMetadata = 'NextServer.getRequestHandlerWithMetadata',\n getServer = 'NextServer.getServer',\n getServerRequestHandler = 'NextServer.getServerRequestHandler',\n createServer = 'createServer.createServer',\n}\n\nenum NextNodeServerSpan {\n compression = 'NextNodeServer.compression',\n getBuildId = 'NextNodeServer.getBuildId',\n createComponentTree = 'NextNodeServer.createComponentTree',\n clientComponentLoading = 'NextNodeServer.clientComponentLoading',\n getLayoutOrPageModule = 'NextNodeServer.getLayoutOrPageModule',\n generateStaticRoutes = 'NextNodeServer.generateStaticRoutes',\n generateFsStaticRoutes = 'NextNodeServer.generateFsStaticRoutes',\n generatePublicRoutes = 'NextNodeServer.generatePublicRoutes',\n generateImageRoutes = 'NextNodeServer.generateImageRoutes.route',\n sendRenderResult = 'NextNodeServer.sendRenderResult',\n proxyRequest = 'NextNodeServer.proxyRequest',\n runApi = 'NextNodeServer.runApi',\n render = 'NextNodeServer.render',\n renderHTML = 'NextNodeServer.renderHTML',\n imageOptimizer = 'NextNodeServer.imageOptimizer',\n getPagePath = 'NextNodeServer.getPagePath',\n getRoutesManifest = 'NextNodeServer.getRoutesManifest',\n findPageComponents = 'NextNodeServer.findPageComponents',\n getFontManifest = 'NextNodeServer.getFontManifest',\n getServerComponentManifest = 'NextNodeServer.getServerComponentManifest',\n getRequestHandler = 'NextNodeServer.getRequestHandler',\n renderToHTML = 'NextNodeServer.renderToHTML',\n renderError = 'NextNodeServer.renderError',\n renderErrorToHTML = 'NextNodeServer.renderErrorToHTML',\n render404 = 'NextNodeServer.render404',\n startResponse = 'NextNodeServer.startResponse',\n\n // nested inner span, does not require parent scope name\n route = 'route',\n onProxyReq = 'onProxyReq',\n apiResolver = 'apiResolver',\n internalFetch = 'internalFetch',\n}\n\nenum StartServerSpan {\n startServer = 'startServer.startServer',\n}\n\nenum RenderSpan {\n getServerSideProps = 'Render.getServerSideProps',\n getStaticProps = 'Render.getStaticProps',\n renderToString = 'Render.renderToString',\n renderDocument = 'Render.renderDocument',\n createBodyResult = 'Render.createBodyResult',\n}\n\nenum AppRenderSpan {\n renderToString = 'AppRender.renderToString',\n renderToReadableStream = 'AppRender.renderToReadableStream',\n getBodyResult = 'AppRender.getBodyResult',\n fetch = 'AppRender.fetch',\n waitShellReady = 'AppRender.waitShellReady',\n renderToNodeFizzStream = 'AppRender.renderToNodeFizzStream',\n instantInsights = 'AppRender.instantInsights',\n instantInsightsPrepareValidation = 'AppRender.instantInsights.prepareValidation',\n instantInsightsRunValidation = 'AppRender.instantInsights.runValidation',\n}\n\nenum DevRouteMatcherManagerSpan {\n ensureRoute = 'DevRouteMatcherManager.ensureRoute',\n reloadMatchers = 'DevRouteMatcherManager.reloadMatchers',\n}\n\nenum DevBundlerServiceSpan {\n ensurePage = 'DevBundlerService.ensurePage',\n}\n\nenum RouterSpan {\n executeRoute = 'Router.executeRoute',\n}\n\nenum NodeSpan {\n runHandler = 'Node.runHandler',\n}\n\nenum AppRouteRouteHandlersSpan {\n runHandler = 'AppRouteRouteHandlers.runHandler',\n}\n\nenum ResolveMetadataSpan {\n generateMetadata = 'ResolveMetadata.generateMetadata',\n generateViewport = 'ResolveMetadata.generateViewport',\n}\n\nenum MiddlewareSpan {\n execute = 'Middleware.execute',\n}\n\ntype SpanTypes =\n | `${BaseServerSpan}`\n | `${LoadComponentsSpan}`\n | `${NextServerSpan}`\n | `${StartServerSpan}`\n | `${NextNodeServerSpan}`\n | `${RenderSpan}`\n | `${RouterSpan}`\n | `${AppRenderSpan}`\n | `${DevRouteMatcherManagerSpan}`\n | `${DevBundlerServiceSpan}`\n | `${NodeSpan}`\n | `${AppRouteRouteHandlersSpan}`\n | `${ResolveMetadataSpan}`\n | `${MiddlewareSpan}`\n\n// This list is used to filter out spans that are not relevant to the user\nexport const NextVanillaSpanAllowlist = new Set([\n MiddlewareSpan.execute,\n BaseServerSpan.handleRequest,\n RenderSpan.getServerSideProps,\n RenderSpan.getStaticProps,\n AppRenderSpan.fetch,\n AppRenderSpan.getBodyResult,\n RenderSpan.renderDocument,\n NodeSpan.runHandler,\n AppRouteRouteHandlersSpan.runHandler,\n ResolveMetadataSpan.generateMetadata,\n ResolveMetadataSpan.generateViewport,\n NextNodeServerSpan.createComponentTree,\n NextNodeServerSpan.findPageComponents,\n NextNodeServerSpan.getLayoutOrPageModule,\n NextNodeServerSpan.startResponse,\n NextNodeServerSpan.clientComponentLoading,\n])\n\n// These Spans are allowed to be always logged\n// when the otel log prefix env is set\nexport const LogSpanAllowList = new Set([\n NextNodeServerSpan.findPageComponents,\n NextNodeServerSpan.createComponentTree,\n NextNodeServerSpan.clientComponentLoading,\n])\n\nexport {\n BaseServerSpan,\n LoadComponentsSpan,\n NextServerSpan,\n NextNodeServerSpan,\n StartServerSpan,\n RenderSpan,\n RouterSpan,\n AppRenderSpan,\n DevRouteMatcherManagerSpan,\n DevBundlerServiceSpan,\n NodeSpan,\n AppRouteRouteHandlersSpan,\n ResolveMetadataSpan,\n MiddlewareSpan,\n}\n\nexport type { SpanTypes }\n"],"names":["AppRenderSpan","AppRouteRouteHandlersSpan","BaseServerSpan","DevBundlerServiceSpan","DevRouteMatcherManagerSpan","LoadComponentsSpan","LogSpanAllowList","MiddlewareSpan","NextNodeServerSpan","NextServerSpan","NextVanillaSpanAllowlist","NodeSpan","RenderSpan","ResolveMetadataSpan","RouterSpan","StartServerSpan","Set"],"mappings":"AAAA;;;;;EAKE,GAEF,4CAA4C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA2K1CA,aAAa;eAAbA;;IAIAC,yBAAyB;eAAzBA;;IAXAC,cAAc;eAAdA;;IASAC,qBAAqB;eAArBA;;IADAC,0BAA0B;eAA1BA;;IAPAC,kBAAkB;eAAlBA;;IARWC,gBAAgB;eAAhBA;;IAoBXC,cAAc;eAAdA;;IAVAC,kBAAkB;eAAlBA;;IADAC,cAAc;eAAdA;;IA9BWC,wBAAwB;eAAxBA;;IAsCXC,QAAQ;eAARA;;IALAC,UAAU;eAAVA;;IAOAC,mBAAmB;eAAnBA;;IANAC,UAAU;eAAVA;;IAFAC,eAAe;eAAfA;;;AAtKF,IAAA,AAAKb,wCAAAA;;;;;;;;;;;;;WAAAA;EAAAA;AAeL,IAAA,AAAKG,4CAAAA;;;WAAAA;EAAAA;AAKL,IAAA,AAAKI,wCAAAA;;;;;;WAAAA;EAAAA;AAQL,IAAA,AAAKD,4CAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;IA4BH,wDAAwD;;;;;WA5BrDA;EAAAA;AAmCL,IAAA,AAAKO,yCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKH,oCAAAA;;;;;;WAAAA;EAAAA;AAQL,IAAA,AAAKZ,uCAAAA;;;;;;;;;;WAAAA;EAAAA;AAYL,IAAA,AAAKI,oDAAAA;;;WAAAA;EAAAA;AAKL,IAAA,AAAKD,+CAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKW,oCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKH,kCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKV,mDAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKY,6CAAAA;;;WAAAA;EAAAA;AAKL,IAAA,AAAKN,wCAAAA;;WAAAA;EAAAA;AAqBE,MAAMG,2BAA2B,IAAIM,IAAI;;;;;;;;;;;;;;;;;CAiB/C;AAIM,MAAMV,mBAAmB,IAAIU,IAAI;;;;CAIvC","ignoreList":[0]} |
@@ -441,5 +441,11 @@ "use strict"; | ||
| // However, in dev we might need to recover a session shell for instant validation. | ||
| // This is indicated by `needsSessionShell`. | ||
| const staticParamsStage = workUnitStore.needsSessionShell ? _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.runtimeLinkData : _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.staticLinkData; | ||
| return stagedRendering.delayUntilStage(staticParamsStage, 'params', userspaceParams); | ||
| // This is indicated by `needsAppShell`. | ||
| const staticParamsStage = workUnitStore.needsAppShell ? _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.runtimeLinkData : _dynamicrenderingutils.RENDER_STAGES_BY_DATA_KIND.staticLinkData; | ||
| const promise = stagedRendering.delayUntilStage(staticParamsStage, 'params', userspaceParams); | ||
| if (process.env.__NEXT_DEV_SERVER) { | ||
| // If static params are accessed, we can recover a static shell or a session shell, but not both. | ||
| return (0, _dynamicrenderingutils.trackPromiseUsed)(promise, _dynamicrenderingutils.trackIncompatibleShellContent.bind(null, workUnitStore)); | ||
| } else { | ||
| return promise; | ||
| } | ||
| } | ||
@@ -446,0 +452,0 @@ return makeUntrackedParams(userspaceParams); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/request/params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { OpaqueFallbackRouteParams } from './fallback-params'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n throwToInterruptStaticGeneration,\n postponeWithTracking,\n} from '../app-render/dynamic-rendering'\n\nimport {\n workUnitAsyncStorage,\n type PrerenderStorePPR,\n type PrerenderStoreLegacy,\n type StaticPrerenderStoreModern,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type PrerenderStoreModernRuntime,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n describeStringPropertyAccess,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n makeDevtoolsIOAwarePromise,\n makeFallbackParamsHangingPromise,\n makePromiseFromTrigger,\n trackFallbackParamsAccessed,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\nimport {\n isEmptyParams,\n hasFallbackRouteParams,\n allParamsAreRootParams,\n} from '../lib/params-utils'\n\nexport type ParamValue = string | Array<string> | undefined\nexport type Params = Record<string, ParamValue>\n\nexport function createParamsFromClient(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n // Client params don't need additional vary tracking because by the\n // time they reach the client, the access would have already been\n // tracked by the server.\n const varyParamsAccumulator = null\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createParamsFromClient should not be called in cache contexts.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createParamsFromClient should not be called in a runtime prerender.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n return makeUntrackedParams(underlyingParams)\n }\n case 'request': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport type CreateServerParamsForMetadata = typeof createServerParamsForMetadata\nexport function createServerParamsForMetadata(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null\n): Promise<Params> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerParamsForServerSegment(\n underlyingParams,\n optionalCatchAllParamName,\n metadataVaryParamsAccumulator\n )\n}\n\n// routes always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerParamsForRoute(\n underlyingParams: Params,\n varyParamsAccumulator: VaryParamsAccumulator | null = null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in runtime prerenders.'\n )\n }\n case 'request':\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createServerParamsForServerSegment(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request': {\n return createRenderParamsForPage(\n workStore,\n workUnitStore,\n underlyingParams,\n optionalCatchAllParamName,\n varyParamsAccumulator\n )\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderParamsForClientSegment(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(\n 'Missing workStore in createPrerenderParamsForClientSegment'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n const fallbackParams = workUnitStore.fallbackRouteParams\n if (fallbackParams) {\n for (let key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeFallbackParamsHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`params`',\n workUnitStore\n )\n }\n }\n }\n break\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in validation contexts.'\n )\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n // We're prerendering in a mode that does not abort. We resolve the promise without\n // any tracking because we're just transporting a value from server to client where the tracking\n // will be applied.\n return Promise.resolve(underlyingParams)\n}\n\nfunction createStaticPrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n switch (prerenderStore.type) {\n case 'prerender': {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (hasFallbackRouteParams(underlyingParams, fallbackParams)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object dynamic.\n return makeHangingParams(underlyingParams, workStore, prerenderStore)\n }\n\n // All params are static.\n\n const { stagedRendering } = prerenderStore\n if (stagedRendering) {\n // Even if all params are static, we need to exclude them from the app shell\n // by delaying them to the static stage. However, root params are allowed in shells,\n // so if all the params are root params, they can be included as well.\n if (\n !allParamsAreRootParams(underlyingParams, prerenderStore.rootParams)\n ) {\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.staticLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n }\n }\n\n return makeUntrackedParams(userspaceParams)\n }\n case 'prerender-client': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeHangingParams(\n underlyingParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-ppr': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n return makeErroringParams(\n underlyingParams,\n fallbackParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRuntimePrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no staging, we're in a prospective runtime prerender.\n if (workUnitStore.isSessionShell) {\n // If we're warming up for a session shell, params should be hanging,\n // because they'll be a hanging input in the final prerender.\n return makeHangingParams(underlyingParams, workStore, workUnitStore)\n } else {\n return makeUntrackedParams(userspaceParams)\n }\n }\n\n // We don't have fallbackParams in runtime prerenders, so we don't know\n // when params are static. However, root params are static by definition,\n // so we can at least check for that.\n // Note that resolving them without a delay is valid because root params are\n // allowed in shells.\n if (allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // Semantically, we should resolve static params in the static stage.\n // But params are link data, and we need to recover a param-less session shell,\n // so we delay all params until the runtime stage instead.\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n}\n\nfunction createRenderParamsForPage(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n) {\n const { stagedRendering, asyncApiPromises, validationSamples } = workUnitStore\n\n // Distinguish the params that we expose to userspace (potentially wrapped in proxies)\n // and the underlying object containing params values. We do this because wrappers\n // like `instrumentParamsPromiseWithDevWarnings` need to be able to get the known param names\n // without triggering other wrapper proxies.\n let userspaceParams = underlyingParams\n if (validationSamples) {\n userspaceParams = createServerParamsProxyForInstantValidation(\n underlyingParams,\n workStore,\n validationSamples\n )\n }\n if (varyParamsAccumulator) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n userspaceParams,\n optionalCatchAllParamName\n )\n }\n\n if (stagedRendering && asyncApiPromises) {\n return createStagedRenderParams(\n workStore,\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(userspaceParams)\n }\n}\n\nfunction createStagedRenderParams(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n underlyingParams: Params,\n userspaceParams: Params\n) {\n const promise = createStagedRenderParamsImpl(\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n if (process.env.NODE_ENV === 'development') {\n return instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n } else {\n return promise\n }\n}\n\nfunction createStagedRenderParamsImpl(\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n /** The actual param values, without any instrumentation */\n underlyingParams: Params,\n /** The params object to return to userspace, possibly wrapped in a proxy */\n userspaceParams: Params\n) {\n // If the route has no params, they should resolve immediately.\n if (isEmptyParams(underlyingParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // If we have fallback params, then they should always resolve in the runtime link data stage.\n // We do this indirectly via the shared params parent for better debug info.\n if (hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)) {\n return createParamsPromiseFromTrigger(\n asyncApiPromises.sharedParamsParent,\n userspaceParams\n )\n }\n\n // All params are static.\n\n // If we're rendering with shells, even static params must be delayed to exclude them from the shell.\n // However, root params are allowed in shells, so if all the params are root params, they can be included as well.\n if (!allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n // For a dynamic request we generally want to recover a static shell,\n // so static params can resolve in the static stage, because session\n // shells are handled with a separate render.\n // However, in dev we might need to recover a session shell for instant validation.\n // This is indicated by `needsSessionShell`.\n const staticParamsStage = workUnitStore.needsSessionShell\n ? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n : RENDER_STAGES_BY_DATA_KIND.staticLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n }\n\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createParamsPromiseFromTrigger(\n trigger: Promise<any>,\n userspaceParams: Params\n) {\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of params in a `new Promise()`, which lets us show each\n // await a different set of values. This is important when all awaits\n // are in third party which would otherwise track all the way to the\n // internal params.\n const promise: Promise<Params> = new Promise((resolve, reject) => {\n trigger.then(() => resolve(userspaceParams), reject)\n })\n promise.catch(noop)\n // @ts-expect-error\n promise.displayName = 'params'\n return promise\n } else {\n return makePromiseFromTrigger(trigger, userspaceParams)\n }\n}\n\nfunction noop() {}\n\nfunction createServerParamsProxyForInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>\n): Params {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples.params ?? {}))\n return createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n}\n\nfunction createClientParamsInInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: ValidationStoreClient['validationSamples']\n): Promise<Params> {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples?.params ?? {}))\n const proxiedUnderlying = createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n return Promise.resolve(proxiedUnderlying)\n}\n\nfunction createRenderParamsInProd(userspaceParams: Params): Promise<Params> {\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRenderParamsInDev(\n underlyingParams: Params,\n userpaceParams: Params,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n return makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams,\n userpaceParams,\n hasFallbackRouteParams(underlyingParams, fallbackParams),\n workStore,\n requestStore\n )\n}\n\ninterface CacheLifetime {}\nconst CachedParams = new WeakMap<CacheLifetime, Promise<Params>>()\n\nconst fallbackParamsProxyHandler: ProxyHandler<Promise<Params>> = {\n get: function get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n\n return {\n [prop]: (...args: unknown[]) => {\n // Record against the store that's active at access time: the\n // hanging promise is cached by params object across prerender\n // stores, so the store that created it may not be the one that's\n // rendering when it's finally awaited.\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore !== undefined) {\n trackFallbackParamsAccessed(workUnitStore)\n }\n\n const store = dynamicAccessAsyncStorage.getStore()\n\n if (store) {\n store.abortController.abort(\n new Error(`Accessed fallback \\`params\\` during prerendering.`)\n )\n }\n\n return new Proxy(\n originalMethod.apply(target, args),\n fallbackParamsProxyHandler\n )\n },\n }[prop]\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n}\n\nfunction makeHangingParams(\n underlyingParams: Params,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = new Proxy(\n makeFallbackParamsHangingPromise<Params>(\n prerenderStore.renderSignal,\n workStore.route,\n '`params`',\n // This promise is created for every segment on a fallback route whether\n // or not it reads params, so recording the access at creation would mark\n // every render. The access is tracked in the proxy traps instead.\n null\n ),\n fallbackParamsProxyHandler\n )\n\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeErroringParams(\n underlyingParams: Params,\n fallbackParams: OpaqueFallbackRouteParams,\n workStore: WorkStore,\n prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const augmentedUnderlying = { ...underlyingParams }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = Promise.resolve(augmentedUnderlying)\n CachedParams.set(underlyingParams, promise)\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n if (fallbackParams.has(prop)) {\n Object.defineProperty(augmentedUnderlying, prop, {\n get() {\n const expression = describeStringPropertyAccess('params', prop)\n // In most dynamic APIs we also throw if `dynamic = \"error\"` however\n // for params is only dynamic when we're generating a fallback shell\n // and even when `dynamic = \"error\"` we still support generating dynamic\n // fallback shells\n // TODO remove this comment when cacheComponents is the default since there\n // will be no `dynamic = \"error\"`\n if (prerenderStore.type === 'prerender-ppr') {\n // PPR Prerender (no cacheComponents)\n postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n },\n enumerable: true,\n })\n }\n }\n })\n\n return promise\n}\n\nfunction makeUntrackedParams(underlyingParams: Params): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = Promise.resolve(underlyingParams)\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams: Params,\n userspaceParams: Params,\n hasFallbackParams: boolean,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = hasFallbackParams\n ? makeDevtoolsIOAwarePromise(\n userspaceParams,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n )\n : // We don't want to force an environment transition when this params is not part of the fallback params set\n Promise.resolve(userspaceParams)\n\n const proxiedPromise = instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n CachedParams.set(underlyingParams, proxiedPromise)\n return proxiedPromise\n}\n\nfunction instrumentParamsPromiseWithDevWarnings(\n underlyingParams: Params,\n promise: Promise<Params>,\n workStore: WorkStore\n): Promise<Params> {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (typeof prop === 'string') {\n if (\n // We are accessing a property that was proxied to the promise instance\n proxiedProperties.has(prop)\n ) {\n const expression = describeStringPropertyAccess('params', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return ReflectAdapter.set(target, prop, value, receiver)\n },\n ownKeys(target) {\n const expression = '`...params` or similar expression'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createParamsAccessError\n)\n\nfunction createParamsAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`params\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["createParamsFromClient","createPrerenderParamsForClientSegment","createServerParamsForMetadata","createServerParamsForRoute","createServerParamsForServerSegment","underlyingParams","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","type","varyParamsAccumulator","createStaticPrerenderParams","validationSamples","createClientParamsInInstantValidation","makeUntrackedParams","process","env","NODE_ENV","fallbackParams","userspaceParams","createRenderParamsInDev","createRenderParamsInProd","throwInvariantForMissingStore","optionalCatchAllParamName","metadataVaryParamsAccumulator","getMetadataVaryParamsAccumulator","createRuntimePrerenderParams","createRenderParamsForPage","fallbackRouteParams","key","has","makeFallbackParamsHangingPromise","renderSignal","route","Promise","resolve","prerenderStore","createVaryingParams","isEmptyParams","hasFallbackRouteParams","makeHangingParams","stagedRendering","allParamsAreRootParams","rootParams","staticParamsStage","RENDER_STAGES_BY_DATA_KIND","staticLinkData","delayUntilStage","makeErroringParams","isSessionShell","runtimeLinkData","asyncApiPromises","createServerParamsProxyForInstantValidation","createStagedRenderParams","promise","createStagedRenderParamsImpl","instrumentParamsPromiseWithDevWarnings","createParamsPromiseFromTrigger","sharedParamsParent","needsSessionShell","trigger","reject","then","catch","noop","displayName","makePromiseFromTrigger","createExhaustiveParamsProxy","require","declaredParams","Set","Object","keys","params","proxiedUnderlying","userpaceParams","requestStore","makeDynamicallyTrackedParamsWithDevWarnings","CachedParams","WeakMap","fallbackParamsProxyHandler","get","target","prop","receiver","originalMethod","ReflectAdapter","args","undefined","trackFallbackParamsAccessed","store","dynamicAccessAsyncStorage","abortController","abort","Error","Proxy","apply","cachedParams","set","augmentedUnderlying","forEach","wellKnownProperties","defineProperty","expression","describeStringPropertyAccess","postponeWithTracking","dynamicTracking","throwToInterruptStaticGeneration","enumerable","hasFallbackParams","makeDevtoolsIOAwarePromise","proxiedPromise","proxiedProperties","add","warnForSyncAccess","value","delete","ownKeys","Reflect","createDedupedByCallsiteServerErrorLoggerDev","createParamsAccessError","prefix"],"mappings":";;;;;;;;;;;;;;;;;;IAmDgBA,sBAAsB;eAAtBA;;IAwNAC,qCAAqC;eAArCA;;IAxIAC,6BAA6B;eAA7BA;;IAaAC,0BAA0B;eAA1BA;;IA8DAC,kCAAkC;eAAlCA;;;0CA3MT;4BAMA;yBAEwB;kCAIxB;8CAYA;gCACwB;8BAIxB;uCAOA;0DACqD;mDAClB;6BAKnC;AAKA,SAASJ,uBACdK,gBAAwB;IAExB,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,IAAI,CAACF,WAAW;QACd,MAAM,qBAA0D,CAA1D,IAAIG,8BAAc,CAAC,yCAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAyD;IACjE;IACA,MAAMC,gBAAgBC,kDAAoB,CAACH,QAAQ;IACnD,IAAIE,eAAe;QACjB,OAAQA,cAAcE,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH,mEAAmE;gBACnE,iEAAiE;gBACjE,yBAAyB;gBACzB,MAAMC,wBAAwB;gBAC9B,OAAOC,4BACLT,kBACA,MACAC,WACAI,eACAG;YAEJ,KAAK;YACL,KAAK;YACL,K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AC7C,OAAO,qBAIN,CAJM,IAAI6D,MACT,GAAG2B,OAAO,KAAK,EAAElB,WAAW,EAAE,CAAC,GAC7B,CAAC,iHAAiH,CAAC,GACnH,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/request/params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { OpaqueFallbackRouteParams } from './fallback-params'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n throwToInterruptStaticGeneration,\n postponeWithTracking,\n} from '../app-render/dynamic-rendering'\n\nimport {\n workUnitAsyncStorage,\n type PrerenderStorePPR,\n type PrerenderStoreLegacy,\n type StaticPrerenderStoreModern,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type PrerenderStoreModernRuntime,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n describeStringPropertyAccess,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n makeDevtoolsIOAwarePromise,\n makeFallbackParamsHangingPromise,\n makePromiseFromTrigger,\n trackFallbackParamsAccessed,\n RENDER_STAGES_BY_DATA_KIND,\n trackPromiseUsed,\n trackIncompatibleShellContent,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\nimport {\n isEmptyParams,\n hasFallbackRouteParams,\n allParamsAreRootParams,\n} from '../lib/params-utils'\n\nexport type ParamValue = string | Array<string> | undefined\nexport type Params = Record<string, ParamValue>\n\nexport function createParamsFromClient(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n // Client params don't need additional vary tracking because by the\n // time they reach the client, the access would have already been\n // tracked by the server.\n const varyParamsAccumulator = null\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createParamsFromClient should not be called in cache contexts.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createParamsFromClient should not be called in a runtime prerender.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n return makeUntrackedParams(underlyingParams)\n }\n case 'request': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport type CreateServerParamsForMetadata = typeof createServerParamsForMetadata\nexport function createServerParamsForMetadata(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null\n): Promise<Params> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerParamsForServerSegment(\n underlyingParams,\n optionalCatchAllParamName,\n metadataVaryParamsAccumulator\n )\n}\n\n// routes always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerParamsForRoute(\n underlyingParams: Params,\n varyParamsAccumulator: VaryParamsAccumulator | null = null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in runtime prerenders.'\n )\n }\n case 'request':\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createServerParamsForServerSegment(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request': {\n return createRenderParamsForPage(\n workStore,\n workUnitStore,\n underlyingParams,\n optionalCatchAllParamName,\n varyParamsAccumulator\n )\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderParamsForClientSegment(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(\n 'Missing workStore in createPrerenderParamsForClientSegment'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n const fallbackParams = workUnitStore.fallbackRouteParams\n if (fallbackParams) {\n for (let key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeFallbackParamsHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`params`',\n workUnitStore\n )\n }\n }\n }\n break\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in validation contexts.'\n )\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n // We're prerendering in a mode that does not abort. We resolve the promise without\n // any tracking because we're just transporting a value from server to client where the tracking\n // will be applied.\n return Promise.resolve(underlyingParams)\n}\n\nfunction createStaticPrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n switch (prerenderStore.type) {\n case 'prerender': {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (hasFallbackRouteParams(underlyingParams, fallbackParams)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object dynamic.\n return makeHangingParams(underlyingParams, workStore, prerenderStore)\n }\n\n // All params are static.\n\n const { stagedRendering } = prerenderStore\n if (stagedRendering) {\n // Even if all params are static, we need to exclude them from the app shell\n // by delaying them to the static stage. However, root params are allowed in shells,\n // so if all the params are root params, they can be included as well.\n if (\n !allParamsAreRootParams(underlyingParams, prerenderStore.rootParams)\n ) {\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.staticLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n }\n }\n\n return makeUntrackedParams(userspaceParams)\n }\n case 'prerender-client': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeHangingParams(\n underlyingParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-ppr': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n return makeErroringParams(\n underlyingParams,\n fallbackParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRuntimePrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no staging, we're in a prospective runtime prerender.\n if (workUnitStore.isSessionShell) {\n // If we're warming up for a session shell, params should be hanging,\n // because they'll be a hanging input in the final prerender.\n return makeHangingParams(underlyingParams, workStore, workUnitStore)\n } else {\n return makeUntrackedParams(userspaceParams)\n }\n }\n\n // We don't have fallbackParams in runtime prerenders, so we don't know\n // when params are static. However, root params are static by definition,\n // so we can at least check for that.\n // Note that resolving them without a delay is valid because root params are\n // allowed in shells.\n if (allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // Semantically, we should resolve static params in the static stage.\n // But params are link data, and we need to recover a param-less session shell,\n // so we delay all params until the runtime stage instead.\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n}\n\nfunction createRenderParamsForPage(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n) {\n const { stagedRendering, asyncApiPromises, validationSamples } = workUnitStore\n\n // Distinguish the params that we expose to userspace (potentially wrapped in proxies)\n // and the underlying object containing params values. We do this because wrappers\n // like `instrumentParamsPromiseWithDevWarnings` need to be able to get the known param names\n // without triggering other wrapper proxies.\n let userspaceParams = underlyingParams\n if (validationSamples) {\n userspaceParams = createServerParamsProxyForInstantValidation(\n underlyingParams,\n workStore,\n validationSamples\n )\n }\n if (varyParamsAccumulator) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n userspaceParams,\n optionalCatchAllParamName\n )\n }\n\n if (stagedRendering && asyncApiPromises) {\n return createStagedRenderParams(\n workStore,\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(userspaceParams)\n }\n}\n\nfunction createStagedRenderParams(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n underlyingParams: Params,\n userspaceParams: Params\n) {\n const promise = createStagedRenderParamsImpl(\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n if (process.env.NODE_ENV === 'development') {\n return instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n } else {\n return promise\n }\n}\n\nfunction createStagedRenderParamsImpl(\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n /** The actual param values, without any instrumentation */\n underlyingParams: Params,\n /** The params object to return to userspace, possibly wrapped in a proxy */\n userspaceParams: Params\n) {\n // If the route has no params, they should resolve immediately.\n if (isEmptyParams(underlyingParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // If we have fallback params, then they should always resolve in the runtime link data stage.\n // We do this indirectly via the shared params parent for better debug info.\n if (hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)) {\n return createParamsPromiseFromTrigger(\n asyncApiPromises.sharedParamsParent,\n userspaceParams\n )\n }\n\n // All params are static.\n\n // If we're rendering with shells, even static params must be delayed to exclude them from the shell.\n // However, root params are allowed in shells, so if all the params are root params, they can be included as well.\n if (!allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n // For a dynamic request we generally want to recover a static shell,\n // so static params can resolve in the static stage, because session\n // shells are handled with a separate render.\n // However, in dev we might need to recover a session shell for instant validation.\n // This is indicated by `needsAppShell`.\n const staticParamsStage = workUnitStore.needsAppShell\n ? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n : RENDER_STAGES_BY_DATA_KIND.staticLinkData\n\n const promise = stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n if (process.env.__NEXT_DEV_SERVER) {\n // If static params are accessed, we can recover a static shell or a session shell, but not both.\n return trackPromiseUsed(\n promise,\n trackIncompatibleShellContent.bind(null, workUnitStore)\n )\n } else {\n return promise\n }\n }\n\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createParamsPromiseFromTrigger(\n trigger: Promise<any>,\n userspaceParams: Params\n) {\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of params in a `new Promise()`, which lets us show each\n // await a different set of values. This is important when all awaits\n // are in third party which would otherwise track all the way to the\n // internal params.\n const promise: Promise<Params> = new Promise((resolve, reject) => {\n trigger.then(() => resolve(userspaceParams), reject)\n })\n promise.catch(noop)\n // @ts-expect-error\n promise.displayName = 'params'\n return promise\n } else {\n return makePromiseFromTrigger(trigger, userspaceParams)\n }\n}\n\nfunction noop() {}\n\nfunction createServerParamsProxyForInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>\n): Params {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples.params ?? {}))\n return createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n}\n\nfunction createClientParamsInInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: ValidationStoreClient['validationSamples']\n): Promise<Params> {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples?.params ?? {}))\n const proxiedUnderlying = createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n return Promise.resolve(proxiedUnderlying)\n}\n\nfunction createRenderParamsInProd(userspaceParams: Params): Promise<Params> {\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRenderParamsInDev(\n underlyingParams: Params,\n userpaceParams: Params,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n return makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams,\n userpaceParams,\n hasFallbackRouteParams(underlyingParams, fallbackParams),\n workStore,\n requestStore\n )\n}\n\ninterface CacheLifetime {}\nconst CachedParams = new WeakMap<CacheLifetime, Promise<Params>>()\n\nconst fallbackParamsProxyHandler: ProxyHandler<Promise<Params>> = {\n get: function get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n\n return {\n [prop]: (...args: unknown[]) => {\n // Record against the store that's active at access time: the\n // hanging promise is cached by params object across prerender\n // stores, so the store that created it may not be the one that's\n // rendering when it's finally awaited.\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore !== undefined) {\n trackFallbackParamsAccessed(workUnitStore)\n }\n\n const store = dynamicAccessAsyncStorage.getStore()\n\n if (store) {\n store.abortController.abort(\n new Error(`Accessed fallback \\`params\\` during prerendering.`)\n )\n }\n\n return new Proxy(\n originalMethod.apply(target, args),\n fallbackParamsProxyHandler\n )\n },\n }[prop]\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n}\n\nfunction makeHangingParams(\n underlyingParams: Params,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = new Proxy(\n makeFallbackParamsHangingPromise<Params>(\n prerenderStore.renderSignal,\n workStore.route,\n '`params`',\n // This promise is created for every segment on a fallback route whether\n // or not it reads params, so recording the access at creation would mark\n // every render. The access is tracked in the proxy traps instead.\n null\n ),\n fallbackParamsProxyHandler\n )\n\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeErroringParams(\n underlyingParams: Params,\n fallbackParams: OpaqueFallbackRouteParams,\n workStore: WorkStore,\n prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const augmentedUnderlying = { ...underlyingParams }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = Promise.resolve(augmentedUnderlying)\n CachedParams.set(underlyingParams, promise)\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n if (fallbackParams.has(prop)) {\n Object.defineProperty(augmentedUnderlying, prop, {\n get() {\n const expression = describeStringPropertyAccess('params', prop)\n // In most dynamic APIs we also throw if `dynamic = \"error\"` however\n // for params is only dynamic when we're generating a fallback shell\n // and even when `dynamic = \"error\"` we still support generating dynamic\n // fallback shells\n // TODO remove this comment when cacheComponents is the default since there\n // will be no `dynamic = \"error\"`\n if (prerenderStore.type === 'prerender-ppr') {\n // PPR Prerender (no cacheComponents)\n postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n },\n enumerable: true,\n })\n }\n }\n })\n\n return promise\n}\n\nfunction makeUntrackedParams(underlyingParams: Params): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = Promise.resolve(underlyingParams)\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams: Params,\n userspaceParams: Params,\n hasFallbackParams: boolean,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = hasFallbackParams\n ? makeDevtoolsIOAwarePromise(\n userspaceParams,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n )\n : // We don't want to force an environment transition when this params is not part of the fallback params set\n Promise.resolve(userspaceParams)\n\n const proxiedPromise = instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n CachedParams.set(underlyingParams, proxiedPromise)\n return proxiedPromise\n}\n\nfunction instrumentParamsPromiseWithDevWarnings(\n underlyingParams: Params,\n promise: Promise<Params>,\n workStore: WorkStore\n): Promise<Params> {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (typeof prop === 'string') {\n if (\n // We are accessing a property that was proxied to the promise instance\n proxiedProperties.has(prop)\n ) {\n const expression = describeStringPropertyAccess('params', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return ReflectAdapter.set(target, prop, value, receiver)\n },\n ownKeys(target) {\n const expression = '`...params` or similar expression'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createParamsAccessError\n)\n\nfunction createParamsAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`params\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["createParamsFromClient","createPrerenderParamsForClientSegment","createServerParamsForMetadata","createServerParamsForRoute","createServerParamsForServerSegment","underlyingParams","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","type","varyParamsAccumulator","createStaticPrerenderParams","validationSamples","createClientParamsInInstantValidation","makeUntrackedParams","process","env","NODE_ENV","fallbackParams","userspaceParams","createRenderParamsInDev","createRenderParamsInProd","throwInvariantForMissingStore","optionalCatchAllParamName","metadataVaryParamsAccumulator","getMetadataVaryParamsAccumulator","createRuntimePrerenderParams","createRenderParamsForPage","fallbackRouteParams","key","has","makeFallbackParamsHangingPromise","renderSignal","route","Promise","resolve","prerenderStore","createVaryingParams","isEmptyParams","hasFallbackRouteParams","makeHangingParams","stagedRendering","allParamsAreRootParams","rootParams","staticParamsStage","RENDER_STAGES_BY_DATA_KIND","staticLinkData","delayUntilStage","makeErroringParams","isSessionShell","runtimeLinkData","asyncApiPromises","createServerParamsProxyForInstantValidation","createStagedRenderParams","promise","createStagedRenderParamsImpl","instrumentParamsPromiseWithDevWarnings","createParamsPromiseFromTrigger","sharedParamsParent","needsAppShell","__NEXT_DEV_SERVER","trackPromiseUsed","trackIncompatibleShellContent","bind","trigger","reject","then","catch","noop","displayName","makePromiseFromTrigger","createExhaustiveParamsProxy","require","declaredParams","Set","Object","keys","params","proxiedUnderlying","userpaceParams","requestStore","makeDynamicallyTrackedParamsWithDevWarnings","CachedParams","WeakMap","fallbackParamsProxyHandler","get","target","prop","receiver","originalMethod","ReflectAdapter","args","undefined","trackFallbackParamsAccessed","store","dynamicAccessAsyncStorage","abortController","abort","Error","Proxy","apply","cachedParams","set","augmentedUnderlying","forEach","wellKnownProperties","defineProperty","expression","describeStringPropertyAccess","postponeWithTracking","dynamicTracking","throwToInterruptStaticGeneration","enumerable","hasFallbackParams","makeDevtoolsIOAwarePromise","proxiedPromise","proxiedProperties","add","warnForSyncAccess","value","delete","ownKeys","Reflect","createDedupedByCallsiteServerErrorLoggerDev","createParamsAccessError","prefix"],"mappings":";;;;;;;;;;;;;;;;;;IAqDgBA,sBAAsB;eAAtBA;;IAwNAC,qCAAqC;eAArCA;;IAxIAC,6BAA6B;eAA7BA;;IAaAC,0BAA0B;eAA1BA;;IA8DAC,kCAAkC;eAAlCA;;;0CA7MT;4BAMA;yBAEwB;kCAIxB;8CAYA;gCACwB;8BAIxB;uCASA;0DACqD;mDAClB;6BAKnC;AAKA,SAASJ,uBACdK,gBAAwB;IAExB,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,IAAI,CAACF,WAAW;QACd,MAAM,qBAA0D,C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ACL,GAAG,CAACC,QAAQC,MAAMC;QAC1C;QACAc,KAAIhB,MAAM,EAAEC,IAAI,EAAEgC,KAAK,EAAE/B,QAAQ;YAC/B,IAAI,OAAOD,SAAS,UAAU;gBAC5B6B,kBAAkBI,MAAM,CAACjC;YAC3B;YACA,OAAOG,uBAAc,CAACY,GAAG,CAAChB,QAAQC,MAAMgC,OAAO/B;QACjD;QACAiC,SAAQnC,MAAM;YACZ,MAAMqB,aAAa;YACnBW,kBAAkBnH,UAAU8B,KAAK,EAAE0E;YACnC,OAAOe,QAAQD,OAAO,CAACnC;QACzB;IACF;AACF;AAEA,MAAMgC,oBAAoBK,IAAAA,qFAA2C,EACnEC;AAGF,SAASA,wBACP3F,KAAyB,EACzB0E,UAAkB;IAElB,MAAMkB,SAAS5F,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAIiE,MACT,GAAG2B,OAAO,KAAK,EAAElB,WAAW,EAAE,CAAC,GAC7B,CAAC,iHAAiH,CAAC,GACnH,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]} |
@@ -16,2 +16,4 @@ "use strict"; | ||
| const _picocolors = require("../../lib/picocolors"); | ||
| const _constants = require("../lib/trace/constants"); | ||
| const _tracer = require("../lib/trace/tracer"); | ||
| function _interop_require_default(obj) { | ||
@@ -91,4 +93,8 @@ return obj && obj.__esModule ? obj : { | ||
| // should try to ensure it and recompile the production matcher. | ||
| await this.ensurer.ensure(developmentMatch, pathname); | ||
| await this.production.reload(); | ||
| await (0, _tracer.getTracer)().trace(_constants.DevRouteMatcherManagerSpan.ensureRoute, { | ||
| spanName: 'prepare route' | ||
| }, ()=>this.ensurer.ensure(developmentMatch, pathname)); | ||
| await (0, _tracer.getTracer)().trace(_constants.DevRouteMatcherManagerSpan.reloadMatchers, { | ||
| spanName: 'reload route matchers' | ||
| }, ()=>this.production.reload()); | ||
| // Iterate over the production matches again, this time we should be able | ||
@@ -95,0 +101,0 @@ // to match it against the production matcher unless there's an error. |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/route-matcher-managers/dev-route-matcher-manager.ts"],"sourcesContent":["import { RouteKind } from '../route-kind'\nimport type { RouteMatch } from '../route-matches/route-match'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport { DefaultRouteMatcherManager } from './default-route-matcher-manager'\nimport type { MatchOptions, RouteMatcherManager } from './route-matcher-manager'\nimport path from '../../shared/lib/isomorphic/path'\nimport * as Log from '../../build/output/log'\nimport { cyan } from '../../lib/picocolors'\nimport type { RouteMatcher } from '../route-matchers/route-matcher'\n\nexport interface RouteEnsurer {\n ensure(match: RouteMatch, pathname: string): Promise<void>\n}\n\nexport class DevRouteMatcherManager extends DefaultRouteMatcherManager {\n constructor(\n private readonly production: RouteMatcherManager,\n private readonly ensurer: RouteEnsurer,\n private readonly dir: string\n ) {\n super()\n }\n\n public async test(pathname: string, options: MatchOptions): Promise<boolean> {\n // Try to find a match within the developer routes.\n const match = await super.match(pathname, options)\n\n // Return if the match wasn't null. Unlike the implementation of `match`\n // which uses `matchAll` here, this does not call `ensure` on the match\n // found via the development matches.\n return match !== null\n }\n\n protected validate(\n pathname: string,\n matcher: RouteMatcher,\n options: MatchOptions\n ): RouteMatch | null {\n const match = super.validate(pathname, matcher, options)\n\n // If a match was found, check to see if there were any conflicting app or\n // pages files.\n // TODO: maybe expand this to _any_ duplicated routes instead?\n if (\n match &&\n matcher.duplicated &&\n matcher.duplicated.some(\n (duplicate) =>\n duplicate.definition.kind === RouteKind.APP_PAGE ||\n duplicate.definition.kind === RouteKind.APP_ROUTE\n ) &&\n matcher.duplicated.some(\n (duplicate) =>\n duplicate.definition.kind === RouteKind.PAGES ||\n duplicate.definition.kind === RouteKind.PAGES_API\n )\n ) {\n return null\n }\n\n return match\n }\n\n public async *matchAll(\n pathname: string,\n options: MatchOptions\n ): AsyncGenerator<RouteMatch<RouteDefinition<RouteKind>>, null, undefined> {\n // Iterate over the development matches to see if one of them match the\n // request path.\n for await (const developmentMatch of super.matchAll(pathname, options)) {\n // We're here, which means that we haven't seen this match yet, so we\n // should try to ensure it and recompile the production matcher.\n await this.ensurer.ensure(developmentMatch, pathname)\n await this.production.reload()\n\n // Iterate over the production matches again, this time we should be able\n // to match it against the production matcher unless there's an error.\n for await (const productionMatch of this.production.matchAll(\n pathname,\n options\n )) {\n yield productionMatch\n }\n }\n\n // We tried direct matching against the pathname and against all the dynamic\n // paths, so there was no match.\n return null\n }\n\n public async reload(): Promise<void> {\n // Compile the production routes again.\n await this.production.reload()\n\n // Compile the development routes.\n await super.reload()\n\n // Check for and warn of any duplicates.\n for (const [pathname, matchers] of Object.entries(\n this.matchers.duplicates\n )) {\n // We only want to warn about matchers resolving to the same path if their\n // identities are different.\n const identity = matchers[0].identity\n if (matchers.slice(1).some((matcher) => matcher.identity !== identity)) {\n continue\n }\n\n Log.warn(\n `Duplicate page detected. ${matchers\n .map((matcher) =>\n cyan(path.relative(this.dir, matcher.definition.filename))\n )\n .join(' and ')} resolve to ${cyan(pathname)}`\n )\n }\n }\n}\n"],"names":["DevRouteMatcherManager","DefaultRouteMatcherManager","constructor","production","ensurer","dir","test","pathname","options","match","validate","matcher","duplicated","some","duplicate","definition","kind","RouteKind","APP_PAGE","APP_ROUTE","PAGES","PAGES_API","matchAll","developmentMatch","ensure","reload","productionMatch","matchers","Object","entries","duplicates","identity","slice","Log","warn","map","cyan","path","relative","filename","join"],"mappings":";;;;+BAcaA;;;eAAAA;;;2BAda;4CAGiB;6DAE1B;6DACI;4BACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOd,MAAMA,+BAA+BC,sDAA0B;IACpEC,YACE,AAAiBC,UAA+B,EAChD,AAAiBC,OAAqB,EACtC,AAAiBC,GAAW,CAC5B;QACA,KAAK,SAJYF,aAAAA,iBACAC,UAAAA,cACAC,MAAAA;IAGnB;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,IAAI,CAACtB,UAAU,CAACsB,MAAM;QAE5B,kCAAkC;QAClC,MAAM,KAAK,CAACA;QAEZ,wCAAwC;QACxC,KAAK,MAAM,CAAClB,UAAUoB,SAAS,IAAIC,OAAOC,OAAO,CAC/C,IAAI,CAACF,QAAQ,CAACG,UAAU,EACvB;YACD,0EAA0E;YAC1E,4BAA4B;YAC5B,MAAMC,WAAWJ,QAAQ,CAAC,EAAE,CAACI,QAAQ;YACrC,IAAIJ,SAASK,KAAK,CAAC,GAAGnB,IAAI,CAAC,CAACF,UAAYA,QAAQoB,QAAQ,KAAKA,WAAW;gBACtE;YACF;YAEAE,KAAIC,IAAI,CACN,CAAC,yBAAyB,EAAEP,SACzBQ,GAAG,CAAC,CAACxB,UACJyB,IAAAA,gBAAI,EAACC,aAAI,CAACC,QAAQ,CAAC,IAAI,CAACjC,GAAG,EAAEM,QAAQI,UAAU,CAACwB,QAAQ,IAEzDC,IAAI,CAAC,SAAS,YAAY,EAAEJ,IAAAA,gBAAI,EAAC7B,WAAW;QAEnD;IACF;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/route-matcher-managers/dev-route-matcher-manager.ts"],"sourcesContent":["import { RouteKind } from '../route-kind'\nimport type { RouteMatch } from '../route-matches/route-match'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport { DefaultRouteMatcherManager } from './default-route-matcher-manager'\nimport type { MatchOptions, RouteMatcherManager } from './route-matcher-manager'\nimport path from '../../shared/lib/isomorphic/path'\nimport * as Log from '../../build/output/log'\nimport { cyan } from '../../lib/picocolors'\nimport type { RouteMatcher } from '../route-matchers/route-matcher'\nimport { DevRouteMatcherManagerSpan } from '../lib/trace/constants'\nimport { getTracer } from '../lib/trace/tracer'\n\nexport interface RouteEnsurer {\n ensure(match: RouteMatch, pathname: string): Promise<void>\n}\n\nexport class DevRouteMatcherManager extends DefaultRouteMatcherManager {\n constructor(\n private readonly production: RouteMatcherManager,\n private readonly ensurer: RouteEnsurer,\n private readonly dir: string\n ) {\n super()\n }\n\n public async test(pathname: string, options: MatchOptions): Promise<boolean> {\n // Try to find a match within the developer routes.\n const match = await super.match(pathname, options)\n\n // Return if the match wasn't null. Unlike the implementation of `match`\n // which uses `matchAll` here, this does not call `ensure` on the match\n // found via the development matches.\n return match !== null\n }\n\n protected validate(\n pathname: string,\n matcher: RouteMatcher,\n options: MatchOptions\n ): RouteMatch | null {\n const match = super.validate(pathname, matcher, options)\n\n // If a match was found, check to see if there were any conflicting app or\n // pages files.\n // TODO: maybe expand this to _any_ duplicated routes instead?\n if (\n match &&\n matcher.duplicated &&\n matcher.duplicated.some(\n (duplicate) =>\n duplicate.definition.kind === RouteKind.APP_PAGE ||\n duplicate.definition.kind === RouteKind.APP_ROUTE\n ) &&\n matcher.duplicated.some(\n (duplicate) =>\n duplicate.definition.kind === RouteKind.PAGES ||\n duplicate.definition.kind === RouteKind.PAGES_API\n )\n ) {\n return null\n }\n\n return match\n }\n\n public async *matchAll(\n pathname: string,\n options: MatchOptions\n ): AsyncGenerator<RouteMatch<RouteDefinition<RouteKind>>, null, undefined> {\n // Iterate over the development matches to see if one of them match the\n // request path.\n for await (const developmentMatch of super.matchAll(pathname, options)) {\n // We're here, which means that we haven't seen this match yet, so we\n // should try to ensure it and recompile the production matcher.\n await getTracer().trace(\n DevRouteMatcherManagerSpan.ensureRoute,\n {\n spanName: 'prepare route',\n },\n () => this.ensurer.ensure(developmentMatch, pathname)\n )\n await getTracer().trace(\n DevRouteMatcherManagerSpan.reloadMatchers,\n {\n spanName: 'reload route matchers',\n },\n () => this.production.reload()\n )\n\n // Iterate over the production matches again, this time we should be able\n // to match it against the production matcher unless there's an error.\n for await (const productionMatch of this.production.matchAll(\n pathname,\n options\n )) {\n yield productionMatch\n }\n }\n\n // We tried direct matching against the pathname and against all the dynamic\n // paths, so there was no match.\n return null\n }\n\n public async reload(): Promise<void> {\n // Compile the production routes again.\n await this.production.reload()\n\n // Compile the development routes.\n await super.reload()\n\n // Check for and warn of any duplicates.\n for (const [pathname, matchers] of Object.entries(\n this.matchers.duplicates\n )) {\n // We only want to warn about matchers resolving to the same path if their\n // identities are different.\n const identity = matchers[0].identity\n if (matchers.slice(1).some((matcher) => matcher.identity !== identity)) {\n continue\n }\n\n Log.warn(\n `Duplicate page detected. ${matchers\n .map((matcher) =>\n cyan(path.relative(this.dir, matcher.definition.filename))\n )\n .join(' and ')} resolve to ${cyan(pathname)}`\n )\n }\n }\n}\n"],"names":["DevRouteMatcherManager","DefaultRouteMatcherManager","constructor","production","ensurer","dir","test","pathname","options","match","validate","matcher","duplicated","some","duplicate","definition","kind","RouteKind","APP_PAGE","APP_ROUTE","PAGES","PAGES_API","matchAll","developmentMatch","getTracer","trace","DevRouteMatcherManagerSpan","ensureRoute","spanName","ensure","reloadMatchers","reload","productionMatch","matchers","Object","entries","duplicates","identity","slice","Log","warn","map","cyan","path","relative","filename","join"],"mappings":";;;;+BAgBaA;;;eAAAA;;;2BAhBa;4CAGiB;6DAE1B;6DACI;4BACA;2BAEsB;wBACjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMnB,MAAMA,+BAA+BC,sDAA0B;IACpEC,YACE,AAAiBC,UAA+B,EAChD,AAAiBC,OAAqB,EACtC,AAAiBC,GAAW,CAC5B;QACA,KAAK,SAJYF,aAAAA,iBACAC,UAAAA,cACAC,MAAAA;IAGnB;IAEA,MAAaC,KAAKC,QAAgB,EAAEC,OAAqB,EAAoB;QAC3E,mDAAmD;QACnD,MAAMC,QAAQ,MAAM,KAAK,CAACA,MAAMF,UAAUC;QAE1C,wEAAwE;QACxE,uEAAuE;QACvE,qCAAqC;QACrC,OAAOC,UAAU;IACnB;IAEUC,SACRH,QAAgB,EAChBI,OAAqB,EACrBH,OAAqB,EACF;QACnB,MAAMC,QAAQ,KAAK,CAACC,SAASH,UAAUI,SAASH;QAEhD,0EAA0E;QAC1E,eAAe;QACf,8DAA8D;QAC9D,IACEC,SACAE,QAAQC,UAAU,I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AACG,UAAU,EACvB;YACD,0EAA0E;YAC1E,4BAA4B;YAC5B,MAAMC,WAAWJ,QAAQ,CAAC,EAAE,CAACI,QAAQ;YACrC,IAAIJ,SAASK,KAAK,CAAC,GAAGzB,IAAI,CAAC,CAACF,UAAYA,QAAQ0B,QAAQ,KAAKA,WAAW;gBACtE;YACF;YAEAE,KAAIC,IAAI,CACN,CAAC,yBAAyB,EAAEP,SACzBQ,GAAG,CAAC,CAAC9B,UACJ+B,IAAAA,gBAAI,EAACC,aAAI,CAACC,QAAQ,CAAC,IAAI,CAACvC,GAAG,EAAEM,QAAQI,UAAU,CAAC8B,QAAQ,IAEzDC,IAAI,CAAC,SAAS,YAAY,EAAEJ,IAAAA,gBAAI,EAACnC,WAAW;QAEnD;IACF;AACF","ignoreList":[0]} |
@@ -40,3 +40,3 @@ "use strict"; | ||
| const _removetrailingslash = require("../../../shared/lib/router/utils/remove-trailing-slash"); | ||
| const _encodecachetag = require("../../lib/encode-cache-tag"); | ||
| const _encodeheadersafe = require("../../lib/encode-header-safe"); | ||
| const _cachelifeprofile = require("../../use-cache/cache-life-profile"); | ||
@@ -52,3 +52,3 @@ function revalidateTag(tag, profile) { | ||
| return revalidate([ | ||
| (0, _encodecachetag.encodeCacheTag)(tag) | ||
| (0, _encodeheadersafe.encodeHeaderSafe)(tag) | ||
| ], `revalidateTag ${tag}`, profile); | ||
@@ -69,3 +69,3 @@ } | ||
| return revalidate([ | ||
| (0, _encodecachetag.encodeCacheTag)(tag) | ||
| (0, _encodeheadersafe.encodeHeaderSafe)(tag) | ||
| ], `updateTag ${tag}`, undefined); | ||
@@ -94,3 +94,3 @@ } | ||
| } | ||
| let normalizedPath = `${_constants.NEXT_CACHE_IMPLICIT_TAG_ID}${(0, _encodecachetag.encodeCacheTag)((0, _removetrailingslash.removeTrailingSlash)(originalPath))}`; | ||
| let normalizedPath = `${_constants.NEXT_CACHE_IMPLICIT_TAG_ID}${(0, _encodeheadersafe.encodeHeaderSafe)((0, _removetrailingslash.removeTrailingSlash)(originalPath))}`; | ||
| if (type) { | ||
@@ -97,0 +97,0 @@ normalizedPath += `${normalizedPath.endsWith('/') ? '' : '/'}${type}`; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/web/spec-extension/revalidate.ts"],"sourcesContent":["import {\n abortAndThrowOnSynchronousRequestDataAccess,\n postponeWithTracking,\n} from '../../app-render/dynamic-rendering'\nimport { isDynamicRoute } from '../../../shared/lib/router/utils'\nimport {\n NEXT_CACHE_IMPLICIT_TAG_ID,\n NEXT_CACHE_SOFT_TAG_MAX_LENGTH,\n} from '../../../lib/constants'\nimport { workAsyncStorage } from '../../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.external'\nimport { DynamicServerError } from '../../../client/components/hooks-server-context'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport {\n ActionDidRevalidateDynamicOnly,\n ActionDidRevalidateStaticAndDynamic as ActionDidRevalidate,\n} from '../../../shared/lib/action-revalidation-kind'\nimport { removeTrailingSlash } from '../../../shared/lib/router/utils/remove-trailing-slash'\nimport { encodeCacheTag } from '../../lib/encode-cache-tag'\nimport { validateAndNormalizeCacheLifeProfile } from '../../use-cache/cache-life-profile'\n\ntype CacheLifeConfig = {\n expire?: number\n}\n\n/**\n * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.\n *\n * The second argument specifies a [`cacheLife`](https://nextjs.org/docs/app/api-reference/functions/cacheLife#reference) profile\n * (e.g. `\"max\"`), or a `{ expire }` object. For immediate expiration in Server Actions, use\n * [`updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag) instead.\n *\n * Read more: [Next.js Docs: `revalidateTag`](https://nextjs.org/docs/app/api-reference/functions/revalidateTag)\n */\nexport function revalidateTag(tag: string, profile: string | CacheLifeConfig) {\n if (!profile) {\n console.warn(\n '\"revalidateTag\" without the second argument is now deprecated, add second argument of \"max\" or use \"updateTag\". See more info here: https://nextjs.org/docs/messages/revalidate-tag-single-arg'\n )\n } else if (typeof profile === 'object') {\n profile = validateAndNormalizeCacheLifeProfile(profile, { kind: 'inline' })\n }\n return revalidate([encodeCacheTag(tag)], `revalidateTag ${tag}`, profile)\n}\n\n/**\n * This function allows you to update [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.\n * This can only be called from within a Server Action to enable read-your-own-writes semantics.\n *\n * Read more: [Next.js Docs: `updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag)\n */\nexport function updateTag(tag: string) {\n const workStore = workAsyncStorage.getStore()\n\n // TODO: change this after investigating why phase: 'action' is\n // set for route handlers\n if (!workStore || workStore.page.endsWith('/route')) {\n throw new Error(\n 'updateTag can only be called from within a Server Action. ' +\n 'To invalidate cache tags in Route Handlers or other contexts, use revalidateTag instead. ' +\n 'See more info here: https://nextjs.org/docs/app/api-reference/functions/updateTag'\n )\n }\n // updateTag uses immediate expiration (no profile) without deprecation warning\n return revalidate([encodeCacheTag(tag)], `updateTag ${tag}`, undefined)\n}\n\n/**\n * This function allows you to refresh client cache from server actions.\n * It's useful as dynamic data can be cached on the client which won't\n * be refreshed by updateTag\n */\nexport function refresh() {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (\n !workStore ||\n workStore.page.endsWith('/route') ||\n workUnitStore?.phase !== 'action'\n ) {\n throw new Error(\n 'refresh can only be called from within a Server Action. ' +\n 'See more info here: https://nextjs.org/docs/app/api-reference/functions/refresh'\n )\n }\n\n if (workStore) {\n // The Server Action version of refresh() only revalidates the dynamic data\n // on the client. It doesn't affect cached data.\n workStore.pathWasRevalidated = ActionDidRevalidateDynamicOnly\n }\n}\n\n/**\n * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific path.\n *\n * Read more: [Next.js Docs: `revalidatePath`](https://nextjs.org/docs/app/api-reference/functions/revalidatePath)\n */\nexport function revalidatePath(originalPath: string, type?: 'layout' | 'page') {\n if (originalPath.length > NEXT_CACHE_SOFT_TAG_MAX_LENGTH) {\n console.warn(\n `Warning: revalidatePath received \"${originalPath}\" which exceeded max length of ${NEXT_CACHE_SOFT_TAG_MAX_LENGTH}. See more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`\n )\n return\n }\n\n let normalizedPath = `${NEXT_CACHE_IMPLICIT_TAG_ID}${encodeCacheTag(removeTrailingSlash(originalPath))}`\n\n if (type) {\n normalizedPath += `${normalizedPath.endsWith('/') ? '' : '/'}${type}`\n } else if (isDynamicRoute(originalPath)) {\n console.warn(\n `Warning: a dynamic page path \"${originalPath}\" was passed to \"revalidatePath\", but the \"type\" parameter is missing. This has no effect by default, see more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`\n )\n }\n\n const tags = [normalizedPath]\n if (normalizedPath === `${NEXT_CACHE_IMPLICIT_TAG_ID}/`) {\n tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)\n } else if (normalizedPath === `${NEXT_CACHE_IMPLICIT_TAG_ID}/index`) {\n tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)\n }\n\n return revalidate(tags, `revalidatePath ${originalPath}`)\n}\n\nfunction revalidate(\n tags: string[],\n expression: string,\n profile?: string | CacheLifeConfig\n) {\n const store = workAsyncStorage.getStore()\n if (!store || !store.incrementalCache) {\n throw new Error(\n `Invariant: static generation store missing in ${expression}`\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n if (workUnitStore.phase === 'render') {\n throw new Error(\n `Route ${store.route} used \"${expression}\" during render which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside a \"use cache\" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'unstable-cache':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside a function cached with \"unstable_cache(...)\" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside \\`generateStaticParams\\` which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'prerender':\n case 'prerender-runtime':\n // cacheComponents Prerender\n const error = new Error(\n `Route ${store.route} used ${expression} without first calling \\`await connection()\\`.`\n )\n return abortAndThrowOnSynchronousRequestDataAccess(\n store.route,\n expression,\n error,\n workUnitStore\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n `${expression} must not be used within a client component. Next.js should be preventing ${expression} from being included in client components statically, but did not in this case.`\n )\n case 'prerender-ppr':\n return postponeWithTracking(\n store.route,\n expression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n workUnitStore.revalidate = 0\n\n const err = new DynamicServerError(\n `Route ${store.route} couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n )\n store.dynamicUsageDescription = expression\n store.dynamicUsageStack = err.stack\n\n throw err\n case 'request':\n if (process.env.NODE_ENV !== 'production') {\n // TODO: This is most likely incorrect. It would lead to the ISR\n // status being flipped when revalidating a static page with a server\n // action.\n workUnitStore.usedDynamic = true\n // TODO(restart-on-cache-miss): we should do a sync IO error here in dev\n // to match prerender behavior\n }\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (!store.pendingRevalidatedTags) {\n store.pendingRevalidatedTags = []\n }\n\n const revalidatedAt = performance.timeOrigin + performance.now()\n\n for (const tag of tags) {\n const existingIndex = store.pendingRevalidatedTags.findIndex((item) => {\n if (item.tag !== tag) return false\n // Compare profiles: both strings, both objects, or both undefined\n if (typeof item.profile === 'string' && typeof profile === 'string') {\n return item.profile === profile\n }\n if (typeof item.profile === 'object' && typeof profile === 'object') {\n return JSON.stringify(item.profile) === JSON.stringify(profile)\n }\n return item.profile === profile\n })\n if (existingIndex === -1) {\n store.pendingRevalidatedTags.push({\n tag,\n profile,\n revalidatedAt,\n })\n } else {\n // Revalidating a tag again invalidates everything produced up to now, so\n // the latest revalidation is the one that decides which entries are\n // stale.\n store.pendingRevalidatedTags[existingIndex].revalidatedAt = revalidatedAt\n }\n }\n\n // if profile is provided and this is a stale-while-revalidate\n // update we do not mark the path as revalidated so that server\n // actions don't pull their own writes\n const cacheLife =\n profile && typeof profile === 'object'\n ? profile\n : profile &&\n typeof profile === 'string' &&\n store?.cacheLifeProfiles[profile]\n ? store.cacheLifeProfiles[profile]\n : undefined\n\n if (!profile || cacheLife?.expire === 0) {\n // TODO: only revalidate if the path matches\n store.pathWasRevalidated = ActionDidRevalidate\n }\n}\n"],"names":["refresh","revalidatePath","revalidateTag","updateTag","tag","profile","console","warn","validateAndNormalizeCacheLifeProfile","kind","revalidate","encodeCacheTag","workStore","workAsyncStorage","getStore","page","endsWith","Error","undefined","workUnitStore","workUnitAsyncStorage","phase","pathWasRevalidated","ActionDidRevalidateDynamicOnly","originalPath","type","length","NEXT_CACHE_SOFT_TAG_MAX_LENGTH","normalizedPath","NEXT_CACHE_IMPLICIT_TAG_ID","removeTrailingSlash","isDynamicRoute","tags","push","expression","store","incrementalCache","route","error","abortAndThrowOnSynchronousRequestDataAccess","InvariantError","postponeWithTracking","dynamicTracking","err","DynamicServerError","dynamicUsageDescription","dynamicUsageStack","stack","process","env","NODE_ENV","usedDynamic","pendingRevalidatedTags","revalidatedAt","performance","timeOrigin","now","existingIndex","findIndex","item","JSON","stringify","cacheLife","cacheLifeProfiles","expire","ActionDidRevalidate"],"mappings":";;;;;;;;;;;;;;;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,oEAAoE;YACpE,SAAS;YACTlB,MAAMiB,sBAAsB,CAACK,cAAc,CAACJ,aAAa,GAAGA;QAC9D;IACF;IAEA,8DAA8D;IAC9D,+DAA+D;IAC/D,sCAAsC;IACtC,MAAMS,YACJzD,WAAW,OAAOA,YAAY,WAC1BA,UACAA,WACE,OAAOA,YAAY,aACnB8B,yBAAAA,MAAO4B,iBAAiB,CAAC1D,QAAQ,IACjC8B,MAAM4B,iBAAiB,CAAC1D,QAAQ,GAChCa;IAER,IAAI,CAACb,WAAWyD,CAAAA,6BAAAA,UAAWE,MAAM,MAAK,GAAG;QACvC,4CAA4C;QAC5C7B,MAAMb,kBAAkB,GAAG2C,2DAAmB;IAChD;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/web/spec-extension/revalidate.ts"],"sourcesContent":["import {\n abortAndThrowOnSynchronousRequestDataAccess,\n postponeWithTracking,\n} from '../../app-render/dynamic-rendering'\nimport { isDynamicRoute } from '../../../shared/lib/router/utils'\nimport {\n NEXT_CACHE_IMPLICIT_TAG_ID,\n NEXT_CACHE_SOFT_TAG_MAX_LENGTH,\n} from '../../../lib/constants'\nimport { workAsyncStorage } from '../../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.external'\nimport { DynamicServerError } from '../../../client/components/hooks-server-context'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport {\n ActionDidRevalidateDynamicOnly,\n ActionDidRevalidateStaticAndDynamic as ActionDidRevalidate,\n} from '../../../shared/lib/action-revalidation-kind'\nimport { removeTrailingSlash } from '../../../shared/lib/router/utils/remove-trailing-slash'\nimport { encodeHeaderSafe } from '../../lib/encode-header-safe'\nimport { validateAndNormalizeCacheLifeProfile } from '../../use-cache/cache-life-profile'\n\ntype CacheLifeConfig = {\n expire?: number\n}\n\n/**\n * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.\n *\n * The second argument specifies a [`cacheLife`](https://nextjs.org/docs/app/api-reference/functions/cacheLife#reference) profile\n * (e.g. `\"max\"`), or a `{ expire }` object. For immediate expiration in Server Actions, use\n * [`updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag) instead.\n *\n * Read more: [Next.js Docs: `revalidateTag`](https://nextjs.org/docs/app/api-reference/functions/revalidateTag)\n */\nexport function revalidateTag(tag: string, profile: string | CacheLifeConfig) {\n if (!profile) {\n console.warn(\n '\"revalidateTag\" without the second argument is now deprecated, add second argument of \"max\" or use \"updateTag\". See more info here: https://nextjs.org/docs/messages/revalidate-tag-single-arg'\n )\n } else if (typeof profile === 'object') {\n profile = validateAndNormalizeCacheLifeProfile(profile, { kind: 'inline' })\n }\n return revalidate([encodeHeaderSafe(tag)], `revalidateTag ${tag}`, profile)\n}\n\n/**\n * This function allows you to update [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.\n * This can only be called from within a Server Action to enable read-your-own-writes semantics.\n *\n * Read more: [Next.js Docs: `updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag)\n */\nexport function updateTag(tag: string) {\n const workStore = workAsyncStorage.getStore()\n\n // TODO: change this after investigating why phase: 'action' is\n // set for route handlers\n if (!workStore || workStore.page.endsWith('/route')) {\n throw new Error(\n 'updateTag can only be called from within a Server Action. ' +\n 'To invalidate cache tags in Route Handlers or other contexts, use revalidateTag instead. ' +\n 'See more info here: https://nextjs.org/docs/app/api-reference/functions/updateTag'\n )\n }\n // updateTag uses immediate expiration (no profile) without deprecation warning\n return revalidate([encodeHeaderSafe(tag)], `updateTag ${tag}`, undefined)\n}\n\n/**\n * This function allows you to refresh client cache from server actions.\n * It's useful as dynamic data can be cached on the client which won't\n * be refreshed by updateTag\n */\nexport function refresh() {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (\n !workStore ||\n workStore.page.endsWith('/route') ||\n workUnitStore?.phase !== 'action'\n ) {\n throw new Error(\n 'refresh can only be called from within a Server Action. ' +\n 'See more info here: https://nextjs.org/docs/app/api-reference/functions/refresh'\n )\n }\n\n if (workStore) {\n // The Server Action version of refresh() only revalidates the dynamic data\n // on the client. It doesn't affect cached data.\n workStore.pathWasRevalidated = ActionDidRevalidateDynamicOnly\n }\n}\n\n/**\n * This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific path.\n *\n * Read more: [Next.js Docs: `revalidatePath`](https://nextjs.org/docs/app/api-reference/functions/revalidatePath)\n */\nexport function revalidatePath(originalPath: string, type?: 'layout' | 'page') {\n if (originalPath.length > NEXT_CACHE_SOFT_TAG_MAX_LENGTH) {\n console.warn(\n `Warning: revalidatePath received \"${originalPath}\" which exceeded max length of ${NEXT_CACHE_SOFT_TAG_MAX_LENGTH}. See more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`\n )\n return\n }\n\n let normalizedPath = `${NEXT_CACHE_IMPLICIT_TAG_ID}${encodeHeaderSafe(removeTrailingSlash(originalPath))}`\n\n if (type) {\n normalizedPath += `${normalizedPath.endsWith('/') ? '' : '/'}${type}`\n } else if (isDynamicRoute(originalPath)) {\n console.warn(\n `Warning: a dynamic page path \"${originalPath}\" was passed to \"revalidatePath\", but the \"type\" parameter is missing. This has no effect by default, see more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`\n )\n }\n\n const tags = [normalizedPath]\n if (normalizedPath === `${NEXT_CACHE_IMPLICIT_TAG_ID}/`) {\n tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)\n } else if (normalizedPath === `${NEXT_CACHE_IMPLICIT_TAG_ID}/index`) {\n tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)\n }\n\n return revalidate(tags, `revalidatePath ${originalPath}`)\n}\n\nfunction revalidate(\n tags: string[],\n expression: string,\n profile?: string | CacheLifeConfig\n) {\n const store = workAsyncStorage.getStore()\n if (!store || !store.incrementalCache) {\n throw new Error(\n `Invariant: static generation store missing in ${expression}`\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n if (workUnitStore.phase === 'render') {\n throw new Error(\n `Route ${store.route} used \"${expression}\" during render which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside a \"use cache\" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'unstable-cache':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside a function cached with \"unstable_cache(...)\" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${store.route} used \"${expression}\" inside \\`generateStaticParams\\` which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n case 'prerender':\n case 'prerender-runtime':\n // cacheComponents Prerender\n const error = new Error(\n `Route ${store.route} used ${expression} without first calling \\`await connection()\\`.`\n )\n return abortAndThrowOnSynchronousRequestDataAccess(\n store.route,\n expression,\n error,\n workUnitStore\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n `${expression} must not be used within a client component. Next.js should be preventing ${expression} from being included in client components statically, but did not in this case.`\n )\n case 'prerender-ppr':\n return postponeWithTracking(\n store.route,\n expression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n workUnitStore.revalidate = 0\n\n const err = new DynamicServerError(\n `Route ${store.route} couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n )\n store.dynamicUsageDescription = expression\n store.dynamicUsageStack = err.stack\n\n throw err\n case 'request':\n if (process.env.NODE_ENV !== 'production') {\n // TODO: This is most likely incorrect. It would lead to the ISR\n // status being flipped when revalidating a static page with a server\n // action.\n workUnitStore.usedDynamic = true\n // TODO(restart-on-cache-miss): we should do a sync IO error here in dev\n // to match prerender behavior\n }\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (!store.pendingRevalidatedTags) {\n store.pendingRevalidatedTags = []\n }\n\n const revalidatedAt = performance.timeOrigin + performance.now()\n\n for (const tag of tags) {\n const existingIndex = store.pendingRevalidatedTags.findIndex((item) => {\n if (item.tag !== tag) return false\n // Compare profiles: both strings, both objects, or both undefined\n if (typeof item.profile === 'string' && typeof profile === 'string') {\n return item.profile === profile\n }\n if (typeof item.profile === 'object' && typeof profile === 'object') {\n return JSON.stringify(item.profile) === JSON.stringify(profile)\n }\n return item.profile === profile\n })\n if (existingIndex === -1) {\n store.pendingRevalidatedTags.push({\n tag,\n profile,\n revalidatedAt,\n })\n } else {\n // Revalidating a tag again invalidates everything produced up to now, so\n // the latest revalidation is the one that decides which entries are\n // stale.\n store.pendingRevalidatedTags[existingIndex].revalidatedAt = revalidatedAt\n }\n }\n\n // if profile is provided and this is a stale-while-revalidate\n // update we do not mark the path as revalidated so that server\n // actions don't pull their own writes\n const cacheLife =\n profile && typeof profile === 'object'\n ? profile\n : profile &&\n typeof profile === 'string' &&\n store?.cacheLifeProfiles[profile]\n ? store.cacheLifeProfiles[profile]\n : undefined\n\n if (!profile || cacheLife?.expire === 0) {\n // TODO: only revalidate if the path matches\n store.pathWasRevalidated = ActionDidRevalidate\n }\n}\n"],"names":["refresh","revalidatePath","revalidateTag","updateTag","tag","profile","console","warn","validateAndNormalizeCacheLifeProfile","kind","revalidate","encodeHeaderSafe","workStore","workAsyncStorage","getStore","page","endsWith","Error","undefined","workUnitStore","workUnitAsyncStorage","phase","pathWasRevalidated","ActionDidRevalidateDynamicOnly","originalPath","type","length","NEXT_CACHE_SOFT_TAG_MAX_LENGTH","normalizedPath","NEXT_CACHE_IMPLICIT_TAG_ID","removeTrailingSlash","isDynamicRoute","tags","push","expression","store","incrementalCache","route","error","abortAndThrowOnSynchronousRequestDataAccess","InvariantError","postponeWithTracking","dynamicTracking","err","DynamicServerError","dynamicUsageDescription","dynamicUsageStack","stack","process","env","NODE_ENV","usedDynamic","pendingRevalidatedTags","revalidatedAt","performance","timeOrigin","now","existingIndex","findIndex","item","JSON","stringify","cacheLife","cacheLifeProfiles","expire","ActionDidRevalidate"],"mappings":";;;;;;;;;;;;;;;;;IAwEgBA,OAAO;eAAPA;;IA2BAC,cAAc;eAAdA;;IAjEAC,aAAa;eAAbA;;IAiBAC,SAAS;eAATA;;;kCAhDT;uBACwB;2BAIxB;0CAC0B;8CACI;oCACF;gCACJ;wCAIxB;qCAC6B;kCACH;kCACoB;AAe9C,SAASD,cAAcE,GAAW,EAAEC,OAAiC;IAC1E,IAAI,CAACA,SAAS;QACZC,QAAQC,IAAI,CACV;IAEJ,OAAO,IAAI,OAAOF,YAAY,UAAU;QACtCA,UAAUG,IAAAA,sDAAoC,EAACH,SAAS;YAAEI,MAAM;QAAS;IAC3E;IACA,OAAOC,WAAW;QAACC,IAAAA,kCAAgB,EAACP;KAAK,EAAE,CAAC,cAAc,EAAEA,KAAK,EAAEC;AACrE;AAQO,SAASF,UAAUC,GAAW;IACnC,MAAMQ,YAAYC,0CAAgB,CAACC,QAAQ;IAE3C,+DAA+D;IAC/D,yBAAyB;IACzB,IAAI,CAACF,aAAaA,UAAUG,IAAI,CAACC,QAAQ,CAAC,WAAW;QACnD,MAAM,qBAIL,CAJK,IAAIC,MACR,+DACE,8FACA,sFAHE,qBAAA;mBAAA;wBAAA;0BAAA;QAIN;IACF;IACA,+EAA+E;IAC/E,OAAOP,WAAW;QAACC,IAAAA,kCAAgB,EAACP;KAAK,EAAE,CAAC,UAAU,EAAEA,KAAK,EAAEc;AACjE;AAOO,SAASlB;IACd,MAAMY,YAAYC,0CAAgB,CAACC,QAAQ;IA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;YAC1B;YACA,IAAI,OAAOsD,KAAKtD,OAAO,KAAK,YAAY,OAAOA,YAAY,UAAU;gBACnE,OAAOuD,KAAKC,SAAS,CAACF,KAAKtD,OAAO,MAAMuD,KAAKC,SAAS,CAACxD;YACzD;YACA,OAAOsD,KAAKtD,OAAO,KAAKA;QAC1B;QACA,IAAIoD,kBAAkB,CAAC,GAAG;YACxBtB,MAAMiB,sBAAsB,CAACnB,IAAI,CAAC;gBAChC7B;gBACAC;gBACAgD;YACF;QACF,OAAO;YACL,yEAAyE;YACzE,oEAAoE;YACpE,SAAS;YACTlB,MAAMiB,sBAAsB,CAACK,cAAc,CAACJ,aAAa,GAAGA;QAC9D;IACF;IAEA,8DAA8D;IAC9D,+DAA+D;IAC/D,sCAAsC;IACtC,MAAMS,YACJzD,WAAW,OAAOA,YAAY,WAC1BA,UACAA,WACE,OAAOA,YAAY,aACnB8B,yBAAAA,MAAO4B,iBAAiB,CAAC1D,QAAQ,IACjC8B,MAAM4B,iBAAiB,CAAC1D,QAAQ,GAChCa;IAER,IAAI,CAACb,WAAWyD,CAAAA,6BAAAA,UAAWE,MAAM,MAAK,GAAG;QACvC,4CAA4C;QAC5C7B,MAAMb,kBAAkB,GAAG2C,2DAAmB;IAChD;AACF","ignoreList":[0]} |
@@ -13,2 +13,3 @@ "use strict"; | ||
| const _patchfetch = require("../../lib/patch-fetch"); | ||
| const _encodeheadersafe = require("../../lib/encode-header-safe"); | ||
| const _workasyncstorageexternal = require("../../app-render/work-async-storage.external"); | ||
@@ -88,3 +89,14 @@ const _workunitasyncstorageexternal = require("../../app-render/work-unit-async-storage.external"); | ||
| // $urlWithPath,$sortedQueryStringKeys,$hashOfEveryThingElse | ||
| const fetchUrl = `unstable_cache ${fetchUrlPrefix} ${cb.name ? ` ${cb.name}` : cacheKey}`; | ||
| // | ||
| // A cache implementation may serialize this name into an HTTP request | ||
| // header, so it is encoded here. Both parts can carry a character above | ||
| // U+00FF: the search parameters are decoded, and a JavaScript identifier | ||
| // may hold one. The character class leaves the separating spaces and the | ||
| // URL punctuation untouched, so the shape above is preserved. | ||
| // | ||
| // `toWellFormed` replaces lone surrogates, which `cb.name` can hold and | ||
| // which `encodeURIComponent` rejects. The name identifies the call for | ||
| // debug metrics, so a replacement character is an acceptable trade for | ||
| // not failing the render. | ||
| const fetchUrl = (0, _encodeheadersafe.encodeHeaderSafe)(`unstable_cache ${fetchUrlPrefix} ${cb.name ? ` ${cb.name}` : cacheKey}`.toWellFormed()); | ||
| const fetchIdx = (workStore ? workStore.nextFetchId : noStoreFetchIdx) ?? 1; | ||
@@ -91,0 +103,0 @@ const implicitTags = workUnitStore == null ? void 0 : workUnitStore.implicitTags; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/web/spec-extension/unstable-cache.ts"],"sourcesContent":["import type { IncrementalCache } from '../../lib/incremental-cache'\n\nimport { CACHE_ONE_YEAR_SECONDS } from '../../../lib/constants'\nimport { validateRevalidate, validateTags } from '../../lib/patch-fetch'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../../app-render/work-async-storage.external'\nimport {\n getCacheSignal,\n getDraftModeProviderForCacheScope,\n willConsumerServerCache,\n workUnitAsyncStorage,\n} from '../../app-render/work-unit-async-storage.external'\nimport {\n CachedRouteKind,\n IncrementalCacheKind,\n type CachedFetchData,\n} from '../../response-cache'\nimport type {\n UnstableCacheStore,\n WorkUnitStore,\n} from '../../app-render/work-unit-async-storage.external'\n\ntype Callback = (...args: any[]) => Promise<any>\n\nlet noStoreFetchIdx = 0\n\nasync function cacheNewResult<T>(\n result: T,\n incrementalCache: IncrementalCache,\n cacheKey: string,\n tags: string[],\n revalidate: number | false | undefined,\n fetchIdx: number,\n fetchUrl: string\n): Promise<unknown> {\n await incrementalCache.set(\n cacheKey,\n {\n kind: CachedRouteKind.FETCH,\n data: {\n headers: {},\n // TODO: handle non-JSON values?\n body: JSON.stringify(result),\n status: 200,\n url: '',\n } satisfies CachedFetchData,\n revalidate:\n typeof revalidate !== 'number' ? CACHE_ONE_YEAR_SECONDS : revalidate,\n },\n { fetchCache: true, tags, fetchIdx, fetchUrl }\n )\n return\n}\n\n/**\n * This function allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests.\n *\n * Read more: [Next.js Docs: `unstable_cache`](https://nextjs.org/docs/app/api-reference/functions/unstable_cache)\n */\nexport function unstable_cache<T extends Callback>(\n cb: T,\n keyParts?: string[],\n options: {\n /**\n * The revalidation interval in seconds.\n */\n revalidate?: number | false\n tags?: string[]\n } = {}\n): T {\n if (options.revalidate === 0) {\n throw new Error(\n `Invariant revalidate: 0 can not be passed to unstable_cache(), must be \"false\" or \"> 0\" ${cb.toString()}`\n )\n }\n\n // Validate the tags provided are valid\n const tags = options.tags\n ? validateTags(options.tags, `unstable_cache ${cb.toString()}`)\n : []\n\n // Validate the revalidate option, and adopt the normalized value, which\n // maps `false` and `Infinity` to INFINITE_CACHE so that the stored value\n // survives JSON serialization.\n const revalidate = validateRevalidate(\n options.revalidate,\n `unstable_cache ${cb.name || cb.toString()}`\n )\n\n // Stash the fixed part of the key at construction time. The invocation key will combine\n // the fixed key with the arguments when actually called\n // @TODO if cb.toString() is long we should hash it\n // @TODO come up with a collision-free way to combine keyParts\n // @TODO consider validating the keyParts are all strings. TS can't provide runtime guarantees\n // and the error produced by accidentally using something that cannot be safely coerced is likely\n // hard to debug\n const fixedKey = `${cb.toString()}-${\n Array.isArray(keyParts) && keyParts.join(',')\n }`\n\n const cachedCb = async (...args: any[]) => {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // We must be able to find the incremental cache otherwise we throw\n const maybeIncrementalCache:\n | import('../../lib/incremental-cache').IncrementalCache\n | undefined =\n workStore?.incrementalCache || (globalThis as any).__incrementalCache\n\n if (!maybeIncrementalCache) {\n throw new Error(\n `Invariant: incrementalCache missing in unstable_cache ${cb.toString()}`\n )\n }\n const incrementalCache = maybeIncrementalCache\n\n const cacheSignal = workUnitStore ? getCacheSignal(workUnitStore) : null\n if (cacheSignal) {\n cacheSignal.beginRead()\n }\n try {\n // If there's no request store, we aren't in a request (or we're not in\n // app router) and if there's no static generation store, we aren't in app\n // router. Default to an empty pathname and search params when there's no\n // request store or static generation store available.\n const fetchUrlPrefix =\n workStore && workUnitStore\n ? getFetchUrlPrefix(workStore, workUnitStore)\n : ''\n\n // Construct the complete cache key for this function invocation\n // @TODO stringify is likely not safe here. We will coerce undefined to null which will make\n // the keyspace smaller than the execution space\n const invocationKey = `${fixedKey}-${JSON.stringify(args)}`\n const cacheKey =\n await incrementalCache.generateSimpleCacheKey(invocationKey)\n // $urlWithPath,$sortedQueryStringKeys,$hashOfEveryThingElse\n const fetchUrl = `unstable_cache ${fetchUrlPrefix} ${cb.name ? ` ${cb.name}` : cacheKey}`\n const fetchIdx =\n (workStore ? workStore.nextFetchId : noStoreFetchIdx) ?? 1\n\n const implicitTags = workUnitStore?.implicitTags\n\n const innerCacheStore: UnstableCacheStore = {\n type: 'unstable-cache',\n phase: 'render',\n consumerWillServerCache: true,\n implicitTags,\n draftMode:\n workUnitStore &&\n workStore &&\n getDraftModeProviderForCacheScope(workStore, workUnitStore),\n rootParams: undefined,\n }\n\n if (workStore) {\n workStore.nextFetchId = fetchIdx + 1\n\n // We are in an App Router context. We try to return the cached entry if it exists and is valid\n // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in\n // the background. If the entry is missing or invalid we generate a new entry and return it.\n\n let isNestedUnstableCache = false\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n // We update the store's revalidate property if the revalidate option is a higher precedence\n // revalidate === undefined doesn't affect timing.\n // revalidate === INFINITE_CACHE (from `false` or `Infinity`) doesn't shrink timing. it stays at the maximum.\n if (typeof revalidate === 'number') {\n if (workUnitStore.revalidate < revalidate) {\n // The store is already revalidating on a shorter time interval, leave it alone\n } else {\n workUnitStore.revalidate = revalidate\n }\n }\n\n // We need to accumulate the tags for this invocation within the store\n const collectedTags = workUnitStore.tags\n if (collectedTags === null) {\n workUnitStore.tags = tags.slice()\n } else {\n for (const tag of tags) {\n // @TODO refactor tags to be a set to avoid this O(n) lookup\n if (!collectedTags.includes(tag)) {\n collectedTags.push(tag)\n }\n }\n }\n break\n case 'unstable-cache':\n isNestedUnstableCache = true\n break\n case 'prerender-client':\n case 'validation-client':\n case 'request':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (\n // when we are nested inside of other unstable_cache's\n // we should bypass cache similar to fetches\n !isNestedUnstableCache &&\n workStore.fetchCache !== 'force-no-store' &&\n !workStore.isOnDemandRevalidate &&\n !incrementalCache.isOnDemandRevalidate &&\n !workStore.isDraftMode\n ) {\n // We attempt to get the current cache entry from the incremental cache.\n const cacheEntry = await incrementalCache.get(cacheKey, {\n kind: IncrementalCacheKind.FETCH,\n revalidate,\n tags,\n softTags: implicitTags?.tags,\n fetchIdx,\n fetchUrl,\n })\n\n if (cacheEntry && cacheEntry.value) {\n // The entry exists and has a value\n if (cacheEntry.value.kind !== CachedRouteKind.FETCH) {\n // The entry is invalid and we need a special warning\n // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced\n // so bugs can be reported\n // @TODO the invocation key can have sensitive data in it. we should not log this entire object\n console.error(\n `Invariant invalid cacheEntry returned for ${invocationKey}`\n )\n // will fall through to generating a new cache entry below\n } else {\n // We have a valid cache entry so we will be returning it. We also check to see if we need\n // to background revalidate it by checking if it is stale.\n const cachedResponse =\n cacheEntry.value.data.body !== undefined\n ? JSON.parse(cacheEntry.value.data.body)\n : undefined\n\n if (cacheEntry.isStale) {\n if (!workStore.pendingRevalidates) {\n workStore.pendingRevalidates = {}\n }\n\n // Check if there's already a pending revalidation to avoid duplicate work\n if (!workStore.pendingRevalidates[invocationKey]) {\n // Create the revalidation promise\n const revalidationPromise = workUnitAsyncStorage\n .run(innerCacheStore, cb, ...args)\n .then(async (result) => {\n await cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n return result\n })\n .catch((err) => {\n // @TODO This error handling seems wrong. We swallow the error?\n console.error(\n `revalidating cache with key: ${invocationKey}`,\n err\n )\n // Return the stale value on error for foreground revalidation\n return cachedResponse\n })\n\n // Attach the empty catch here so we don't get a \"unhandled promise\n // rejection\" warning. (Behavior is matched with patch-fetch)\n if (willConsumerServerCache(workUnitStore)) {\n revalidationPromise.catch(() => {})\n }\n\n workStore.pendingRevalidates[invocationKey] =\n revalidationPromise\n }\n\n // Check if we need to do foreground revalidation\n if (willConsumerServerCache(workUnitStore)) {\n // When the consumer will persist this result in a server\n // cache, wait for fresh data so it doesn't persist a stale\n // value. The `await` here also keeps `cacheSignal.endRead` (in\n // the outer `finally`) suspended until the recompute +\n // cacheNewResult actually complete, so a prospective\n // prerender's `cacheSignal` doesn't resolve `cacheReady`\n // prematurely.\n return await workStore.pendingRevalidates[invocationKey]\n }\n // Otherwise, we're doing background revalidation - return stale immediately\n }\n\n // We had a valid cache entry so we return it here\n return cachedResponse\n }\n }\n }\n\n // If we got this far then we had an invalid cache entry and need to generate a new one\n const result = await workUnitAsyncStorage.run(\n innerCacheStore,\n cb,\n ...args\n )\n\n if (!workStore.isDraftMode) {\n if (!workStore.pendingRevalidates) {\n workStore.pendingRevalidates = {}\n }\n\n // We need to push the cache result promise to pending\n // revalidates otherwise it won't be awaited and is just\n // dangling\n workStore.pendingRevalidates[invocationKey] = cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n }\n\n return result\n } else {\n noStoreFetchIdx += 1\n // We are in Pages Router or were called outside of a render. We don't have a store\n // so we just call the callback directly when it needs to run.\n // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in\n // the background. If the entry is missing or invalid we generate a new entry and return it.\n\n if (!incrementalCache.isOnDemandRevalidate) {\n // We aren't doing an on demand revalidation so we check use the cache if valid\n const cacheEntry = await incrementalCache.get(cacheKey, {\n kind: IncrementalCacheKind.FETCH,\n revalidate,\n tags,\n fetchIdx,\n fetchUrl,\n softTags: implicitTags?.tags,\n })\n\n if (cacheEntry && cacheEntry.value) {\n // The entry exists and has a value\n if (cacheEntry.value.kind !== CachedRouteKind.FETCH) {\n // The entry is invalid and we need a special warning\n // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced\n // so bugs can be reported\n console.error(\n `Invariant invalid cacheEntry returned for ${invocationKey}`\n )\n // will fall through to generating a new cache entry below\n } else if (!cacheEntry.isStale) {\n // We have a valid cache entry and it is fresh so we return it\n return cacheEntry.value.data.body !== undefined\n ? JSON.parse(cacheEntry.value.data.body)\n : undefined\n }\n }\n }\n\n // If we got this far then we had an invalid cache entry and need to generate a new one\n const result = await workUnitAsyncStorage.run(\n innerCacheStore,\n cb,\n ...args\n )\n\n // we need to wait setting the new cache result here as\n // we don't have pending revalidates on workStore to\n // push to and we can't have a dangling promise\n await cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n return result\n }\n } finally {\n if (cacheSignal) {\n cacheSignal.endRead()\n }\n }\n }\n // TODO: once AsyncLocalStorage.run() returns the correct types this override will no longer be necessary\n return cachedCb as unknown as T\n}\n\nfunction getFetchUrlPrefix(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): string {\n switch (workUnitStore.type) {\n case 'request':\n const pathname = workUnitStore.url.pathname\n const searchParams = new URLSearchParams(workUnitStore.url.search)\n\n const sortedSearch = [...searchParams.keys()]\n .sort((a, b) => a.localeCompare(b))\n .map((key) => `${key}=${searchParams.get(key)}`)\n .join('&')\n\n return `${pathname}${sortedSearch.length ? '?' : ''}${sortedSearch}`\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return workStore.route\n default:\n return workUnitStore satisfies never\n }\n}\n"],"names":["unstable_cache","noStoreFetchIdx","cacheNewResult","result","incrementalCache","cacheKey","tags","revalidate","fetchIdx","fetchUrl","set","kind","CachedRouteKind","FETCH","data","headers","body","JSON","stringify","status","url","CACHE_ONE_YEAR_SECONDS","fetchCache","cb","keyParts","options","Error","toString","validateTags","validateRevalidate","name","fixedKey","Array","isArray","join","cachedCb","args","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","maybeIncrementalCache","globalThis","__incrementalCache","cacheSignal","getCacheSignal","beginRead","fetchUrlPrefix","getFetchUrlPrefix","invocationKey","generateSimpleCacheKey","nextFetchId","implicitTags","innerCacheStore","type","phase","consumerWillServerCache","draftMode","getDraftModeProviderForCacheScope","rootParams","undefined","isNestedUnstableCache","collectedTags","slice","tag","includes","push","isOnDemandRevalidate","isDraftMode","cacheEntry","get","IncrementalCacheKind","softTags","value","console","error","cachedResponse","parse","isStale","pendingRevalidates","revalidationPromise","run","then","catch","err","willConsumerServerCache","endRead","pathname","searchParams","URLSearchParams","search","sortedSearch","keys","sort","a","b","localeCompare","map","key","length","route"],"mappings":";;;;+BA6DgBA;;;eAAAA;;;2BA3DuB;4BACU;0CAI1C;8CAMA;+BAKA;AAQP,IAAIC,kBAAkB;AAEtB,eAAeC,eACbC,MAAS,EACTC,gBAAkC,EAClCC,QAAgB,EAChBC,IAAc,EACdC,UAAsC,EACtCC,QAAgB,EAChBC,QAAgB;IAEhB,MAAML,iBAAiBM,GAAG,CACxBL,UACA;QACEM,MAAMC,8BAAe,CAACC,KAAK;QAC3BC,MAAM;YACJC,SAAS,CAAC;YACV,gCAAgC;YAChCC,MAAMC,KAAKC,SAAS,CAACf;YACrBgB,QAAQ;YACRC,KAAK;QACP;QACAb,YACE,OAAOA,eAAe,WAAWc,iCAAsB,GAAGd;IAC9D,GACA;QAAEe,YAAY;QAAMhB;QAAME;QAAUC;IAAS;IAE/C;AACF;AAOO,SAAST,eACdu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C,aAAa;gBACfA,YAAY0C,OAAO;YACrB;QACF;IACF;IACA,yGAAyG;IACzG,OAAOpD;AACT;AAEA,SAASc,kBACPZ,SAAoB,EACpBG,aAA4B;IAE5B,OAAQA,cAAce,IAAI;QACxB,KAAK;YACH,MAAMiC,WAAWhD,cAAcpB,GAAG,CAACoE,QAAQ;YAC3C,MAAMC,eAAe,IAAIC,gBAAgBlD,cAAcpB,GAAG,CAACuE,MAAM;YAEjE,MAAMC,eAAe;mBAAIH,aAAaI,IAAI;aAAG,CAC1CC,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAEE,aAAa,CAACD,IAC/BE,GAAG,CAAC,CAACC,MAAQ,GAAGA,IAAI,CAAC,EAAEV,aAAalB,GAAG,CAAC4B,MAAM,EAC9CjE,IAAI,CAAC;YAER,OAAO,GAAGsD,WAAWI,aAAaQ,MAAM,GAAG,MAAM,KAAKR,cAAc;QACtE,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOvD,UAAUgE,KAAK;QACxB;YACE,OAAO7D;IACX;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/web/spec-extension/unstable-cache.ts"],"sourcesContent":["import type { IncrementalCache } from '../../lib/incremental-cache'\n\nimport { CACHE_ONE_YEAR_SECONDS } from '../../../lib/constants'\nimport { validateRevalidate, validateTags } from '../../lib/patch-fetch'\nimport { encodeHeaderSafe } from '../../lib/encode-header-safe'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../../app-render/work-async-storage.external'\nimport {\n getCacheSignal,\n getDraftModeProviderForCacheScope,\n willConsumerServerCache,\n workUnitAsyncStorage,\n} from '../../app-render/work-unit-async-storage.external'\nimport {\n CachedRouteKind,\n IncrementalCacheKind,\n type CachedFetchData,\n} from '../../response-cache'\nimport type {\n UnstableCacheStore,\n WorkUnitStore,\n} from '../../app-render/work-unit-async-storage.external'\n\ntype Callback = (...args: any[]) => Promise<any>\n\nlet noStoreFetchIdx = 0\n\nasync function cacheNewResult<T>(\n result: T,\n incrementalCache: IncrementalCache,\n cacheKey: string,\n tags: string[],\n revalidate: number | false | undefined,\n fetchIdx: number,\n fetchUrl: string\n): Promise<unknown> {\n await incrementalCache.set(\n cacheKey,\n {\n kind: CachedRouteKind.FETCH,\n data: {\n headers: {},\n // TODO: handle non-JSON values?\n body: JSON.stringify(result),\n status: 200,\n url: '',\n } satisfies CachedFetchData,\n revalidate:\n typeof revalidate !== 'number' ? CACHE_ONE_YEAR_SECONDS : revalidate,\n },\n { fetchCache: true, tags, fetchIdx, fetchUrl }\n )\n return\n}\n\n/**\n * This function allows you to cache the results of expensive operations, like database queries, and reuse them across multiple requests.\n *\n * Read more: [Next.js Docs: `unstable_cache`](https://nextjs.org/docs/app/api-reference/functions/unstable_cache)\n */\nexport function unstable_cache<T extends Callback>(\n cb: T,\n keyParts?: string[],\n options: {\n /**\n * The revalidation interval in seconds.\n */\n revalidate?: number | false\n tags?: string[]\n } = {}\n): T {\n if (options.revalidate === 0) {\n throw new Error(\n `Invariant revalidate: 0 can not be passed to unstable_cache(), must be \"false\" or \"> 0\" ${cb.toString()}`\n )\n }\n\n // Validate the tags provided are valid\n const tags = options.tags\n ? validateTags(options.tags, `unstable_cache ${cb.toString()}`)\n : []\n\n // Validate the revalidate option, and adopt the normalized value, which\n // maps `false` and `Infinity` to INFINITE_CACHE so that the stored value\n // survives JSON serialization.\n const revalidate = validateRevalidate(\n options.revalidate,\n `unstable_cache ${cb.name || cb.toString()}`\n )\n\n // Stash the fixed part of the key at construction time. The invocation key will combine\n // the fixed key with the arguments when actually called\n // @TODO if cb.toString() is long we should hash it\n // @TODO come up with a collision-free way to combine keyParts\n // @TODO consider validating the keyParts are all strings. TS can't provide runtime guarantees\n // and the error produced by accidentally using something that cannot be safely coerced is likely\n // hard to debug\n const fixedKey = `${cb.toString()}-${\n Array.isArray(keyParts) && keyParts.join(',')\n }`\n\n const cachedCb = async (...args: any[]) => {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // We must be able to find the incremental cache otherwise we throw\n const maybeIncrementalCache:\n | import('../../lib/incremental-cache').IncrementalCache\n | undefined =\n workStore?.incrementalCache || (globalThis as any).__incrementalCache\n\n if (!maybeIncrementalCache) {\n throw new Error(\n `Invariant: incrementalCache missing in unstable_cache ${cb.toString()}`\n )\n }\n const incrementalCache = maybeIncrementalCache\n\n const cacheSignal = workUnitStore ? getCacheSignal(workUnitStore) : null\n if (cacheSignal) {\n cacheSignal.beginRead()\n }\n try {\n // If there's no request store, we aren't in a request (or we're not in\n // app router) and if there's no static generation store, we aren't in app\n // router. Default to an empty pathname and search params when there's no\n // request store or static generation store available.\n const fetchUrlPrefix =\n workStore && workUnitStore\n ? getFetchUrlPrefix(workStore, workUnitStore)\n : ''\n\n // Construct the complete cache key for this function invocation\n // @TODO stringify is likely not safe here. We will coerce undefined to null which will make\n // the keyspace smaller than the execution space\n const invocationKey = `${fixedKey}-${JSON.stringify(args)}`\n const cacheKey =\n await incrementalCache.generateSimpleCacheKey(invocationKey)\n // $urlWithPath,$sortedQueryStringKeys,$hashOfEveryThingElse\n //\n // A cache implementation may serialize this name into an HTTP request\n // header, so it is encoded here. Both parts can carry a character above\n // U+00FF: the search parameters are decoded, and a JavaScript identifier\n // may hold one. The character class leaves the separating spaces and the\n // URL punctuation untouched, so the shape above is preserved.\n //\n // `toWellFormed` replaces lone surrogates, which `cb.name` can hold and\n // which `encodeURIComponent` rejects. The name identifies the call for\n // debug metrics, so a replacement character is an acceptable trade for\n // not failing the render.\n const fetchUrl = encodeHeaderSafe(\n `unstable_cache ${fetchUrlPrefix} ${cb.name ? ` ${cb.name}` : cacheKey}`.toWellFormed()\n )\n const fetchIdx =\n (workStore ? workStore.nextFetchId : noStoreFetchIdx) ?? 1\n\n const implicitTags = workUnitStore?.implicitTags\n\n const innerCacheStore: UnstableCacheStore = {\n type: 'unstable-cache',\n phase: 'render',\n consumerWillServerCache: true,\n implicitTags,\n draftMode:\n workUnitStore &&\n workStore &&\n getDraftModeProviderForCacheScope(workStore, workUnitStore),\n rootParams: undefined,\n }\n\n if (workStore) {\n workStore.nextFetchId = fetchIdx + 1\n\n // We are in an App Router context. We try to return the cached entry if it exists and is valid\n // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in\n // the background. If the entry is missing or invalid we generate a new entry and return it.\n\n let isNestedUnstableCache = false\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n // We update the store's revalidate property if the revalidate option is a higher precedence\n // revalidate === undefined doesn't affect timing.\n // revalidate === INFINITE_CACHE (from `false` or `Infinity`) doesn't shrink timing. it stays at the maximum.\n if (typeof revalidate === 'number') {\n if (workUnitStore.revalidate < revalidate) {\n // The store is already revalidating on a shorter time interval, leave it alone\n } else {\n workUnitStore.revalidate = revalidate\n }\n }\n\n // We need to accumulate the tags for this invocation within the store\n const collectedTags = workUnitStore.tags\n if (collectedTags === null) {\n workUnitStore.tags = tags.slice()\n } else {\n for (const tag of tags) {\n // @TODO refactor tags to be a set to avoid this O(n) lookup\n if (!collectedTags.includes(tag)) {\n collectedTags.push(tag)\n }\n }\n }\n break\n case 'unstable-cache':\n isNestedUnstableCache = true\n break\n case 'prerender-client':\n case 'validation-client':\n case 'request':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (\n // when we are nested inside of other unstable_cache's\n // we should bypass cache similar to fetches\n !isNestedUnstableCache &&\n workStore.fetchCache !== 'force-no-store' &&\n !workStore.isOnDemandRevalidate &&\n !incrementalCache.isOnDemandRevalidate &&\n !workStore.isDraftMode\n ) {\n // We attempt to get the current cache entry from the incremental cache.\n const cacheEntry = await incrementalCache.get(cacheKey, {\n kind: IncrementalCacheKind.FETCH,\n revalidate,\n tags,\n softTags: implicitTags?.tags,\n fetchIdx,\n fetchUrl,\n })\n\n if (cacheEntry && cacheEntry.value) {\n // The entry exists and has a value\n if (cacheEntry.value.kind !== CachedRouteKind.FETCH) {\n // The entry is invalid and we need a special warning\n // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced\n // so bugs can be reported\n // @TODO the invocation key can have sensitive data in it. we should not log this entire object\n console.error(\n `Invariant invalid cacheEntry returned for ${invocationKey}`\n )\n // will fall through to generating a new cache entry below\n } else {\n // We have a valid cache entry so we will be returning it. We also check to see if we need\n // to background revalidate it by checking if it is stale.\n const cachedResponse =\n cacheEntry.value.data.body !== undefined\n ? JSON.parse(cacheEntry.value.data.body)\n : undefined\n\n if (cacheEntry.isStale) {\n if (!workStore.pendingRevalidates) {\n workStore.pendingRevalidates = {}\n }\n\n // Check if there's already a pending revalidation to avoid duplicate work\n if (!workStore.pendingRevalidates[invocationKey]) {\n // Create the revalidation promise\n const revalidationPromise = workUnitAsyncStorage\n .run(innerCacheStore, cb, ...args)\n .then(async (result) => {\n await cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n return result\n })\n .catch((err) => {\n // @TODO This error handling seems wrong. We swallow the error?\n console.error(\n `revalidating cache with key: ${invocationKey}`,\n err\n )\n // Return the stale value on error for foreground revalidation\n return cachedResponse\n })\n\n // Attach the empty catch here so we don't get a \"unhandled promise\n // rejection\" warning. (Behavior is matched with patch-fetch)\n if (willConsumerServerCache(workUnitStore)) {\n revalidationPromise.catch(() => {})\n }\n\n workStore.pendingRevalidates[invocationKey] =\n revalidationPromise\n }\n\n // Check if we need to do foreground revalidation\n if (willConsumerServerCache(workUnitStore)) {\n // When the consumer will persist this result in a server\n // cache, wait for fresh data so it doesn't persist a stale\n // value. The `await` here also keeps `cacheSignal.endRead` (in\n // the outer `finally`) suspended until the recompute +\n // cacheNewResult actually complete, so a prospective\n // prerender's `cacheSignal` doesn't resolve `cacheReady`\n // prematurely.\n return await workStore.pendingRevalidates[invocationKey]\n }\n // Otherwise, we're doing background revalidation - return stale immediately\n }\n\n // We had a valid cache entry so we return it here\n return cachedResponse\n }\n }\n }\n\n // If we got this far then we had an invalid cache entry and need to generate a new one\n const result = await workUnitAsyncStorage.run(\n innerCacheStore,\n cb,\n ...args\n )\n\n if (!workStore.isDraftMode) {\n if (!workStore.pendingRevalidates) {\n workStore.pendingRevalidates = {}\n }\n\n // We need to push the cache result promise to pending\n // revalidates otherwise it won't be awaited and is just\n // dangling\n workStore.pendingRevalidates[invocationKey] = cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n }\n\n return result\n } else {\n noStoreFetchIdx += 1\n // We are in Pages Router or were called outside of a render. We don't have a store\n // so we just call the callback directly when it needs to run.\n // If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in\n // the background. If the entry is missing or invalid we generate a new entry and return it.\n\n if (!incrementalCache.isOnDemandRevalidate) {\n // We aren't doing an on demand revalidation so we check use the cache if valid\n const cacheEntry = await incrementalCache.get(cacheKey, {\n kind: IncrementalCacheKind.FETCH,\n revalidate,\n tags,\n fetchIdx,\n fetchUrl,\n softTags: implicitTags?.tags,\n })\n\n if (cacheEntry && cacheEntry.value) {\n // The entry exists and has a value\n if (cacheEntry.value.kind !== CachedRouteKind.FETCH) {\n // The entry is invalid and we need a special warning\n // @TODO why do we warn this way? Should this just be an error? How are these errors surfaced\n // so bugs can be reported\n console.error(\n `Invariant invalid cacheEntry returned for ${invocationKey}`\n )\n // will fall through to generating a new cache entry below\n } else if (!cacheEntry.isStale) {\n // We have a valid cache entry and it is fresh so we return it\n return cacheEntry.value.data.body !== undefined\n ? JSON.parse(cacheEntry.value.data.body)\n : undefined\n }\n }\n }\n\n // If we got this far then we had an invalid cache entry and need to generate a new one\n const result = await workUnitAsyncStorage.run(\n innerCacheStore,\n cb,\n ...args\n )\n\n // we need to wait setting the new cache result here as\n // we don't have pending revalidates on workStore to\n // push to and we can't have a dangling promise\n await cacheNewResult(\n result,\n incrementalCache,\n cacheKey,\n tags,\n revalidate,\n fetchIdx,\n fetchUrl\n )\n return result\n }\n } finally {\n if (cacheSignal) {\n cacheSignal.endRead()\n }\n }\n }\n // TODO: once AsyncLocalStorage.run() returns the correct types this override will no longer be necessary\n return cachedCb as unknown as T\n}\n\nfunction getFetchUrlPrefix(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): string {\n switch (workUnitStore.type) {\n case 'request':\n const pathname = workUnitStore.url.pathname\n const searchParams = new URLSearchParams(workUnitStore.url.search)\n\n const sortedSearch = [...searchParams.keys()]\n .sort((a, b) => a.localeCompare(b))\n .map((key) => `${key}=${searchParams.get(key)}`)\n .join('&')\n\n return `${pathname}${sortedSearch.length ? '?' : ''}${sortedSearch}`\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return workStore.route\n default:\n return workUnitStore satisfies never\n }\n}\n"],"names":["unstable_cache","noStoreFetchIdx","cacheNewResult","result","incrementalCache","cacheKey","tags","revalidate","fetchIdx","fetchUrl","set","kind","CachedRouteKind","FETCH","data","headers","body","JSON","stringify","status","url","CACHE_ONE_YEAR_SECONDS","fetchCache","cb","keyParts","options","Error","toString","validateTags","validateRevalidate","name","fixedKey","Array","isArray","join","cachedCb","args","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","maybeIncrementalCache","globalThis","__incrementalCache","cacheSignal","getCacheSignal","beginRead","fetchUrlPrefix","getFetchUrlPrefix","invocationKey","generateSimpleCacheKey","encodeHeaderSafe","toWellFormed","nextFetchId","implicitTags","innerCacheStore","type","phase","consumerWillServerCache","draftMode","getDraftModeProviderForCacheScope","rootParams","undefined","isNestedUnstableCache","collectedTags","slice","tag","includes","push","isOnDemandRevalidate","isDraftMode","cacheEntry","get","IncrementalCacheKind","softTags","value","console","error","cachedResponse","parse","isStale","pendingRevalidates","revalidationPromise","run","then","catch","err","willConsumerServerCache","endRead","pathname","searchParams","URLSearchParams","search","sortedSearch","keys","sort","a","b","localeCompare","map","key","length","route"],"mappings":";;;;+BA8DgBA;;;eAAAA;;;2BA5DuB;4BACU;kCAChB;0CAI1B;8CAMA;+BAKA;AAQP,IAAIC,kBAAkB;AAEtB,eAAeC,eACbC,MAAS,EACTC,gBAAkC,EAClCC,QAAgB,EAChBC,IAAc,EACdC,UAAsC,EACtCC,QAAgB,EAChBC,QAAgB;IAEhB,MAAML,iBAAiBM,GAAG,CACxBL,UACA;QACEM,MAAMC,8BAAe,CAACC,KAAK;QAC3BC,MAAM;YACJC,SAAS,CAAC;YACV,gCAAgC;YAChCC,MAAMC,KAAKC,SAAS,CAACf;YACrBgB,QAAQ;YACRC,KAAK;QACP;QACAb,YACE,OAAOA,eAAe,WAAWc,iCAAsB,GAAGd;IAC9D,GACA;QAAEe,YAAY;QAAMhB;QAAME;QAAUC;IAAS;IAE/C;AACF;AAOO,SAAST,eACduB,EAAK,EACLC,QAAmB,EACnBC,UAMI,CAAC,CAAC;IAEN,IAAIA,QAAQlB,UAAU,KAAK,GAAG;QAC5B,MAAM,qBAEL,CAFK,IAAImB,MACR,CAAC,wFAAwF,EAAEH,GAAGI,QAAQ,IAAI,GADtG,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IAEA,uCAAuC;IACvC,MAAMrB,OAAOmB,QAAQnB,IAAI,GACrBsB,IAAAA,wBAAY,EAACH,QAAQnB,IAAI,EAAE,CAAC,eAAe,EAAEiB,GAAGI,QAAQ,IAAI,IAC5D,EAAE;IAEN,wEAAwE;IACxE,yEAAyE;IACzE,+BAA+B;IAC/B,MAAMpB,aAAasB,IAAAA,8BAAkB,EACnCJ,QAAQlB,UAAU,EAClB,CAAC,eAAe,EAAEgB,GAAGO,IAAI,IAAIP,GAAGI,QAAQ,IAAI;IAG9C,wFAAwF;IACxF,wDAAwD;IACxD,mDAAm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E,GAAG,CAAC,CAACC,MAAQ,GAAGA,IAAI,CAAC,EAAEV,aAAalB,GAAG,CAAC4B,MAAM,EAC9CnE,IAAI,CAAC;YAER,OAAO,GAAGwD,WAAWI,aAAaQ,MAAM,GAAG,MAAM,KAAKR,cAAc;QACtE,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOzD,UAAUkE,KAAK;QACxB;YACE,OAAO/D;IACX;AACF","ignoreList":[0]} |
@@ -1,2 +0,2 @@ | ||
| import type { FocusAndScrollRef, PrefetchKind } from '../../client/components/router-reducer/router-reducer-types'; | ||
| import type { ScrollHandlerRef, PrefetchKind } from '../../client/components/router-reducer/router-reducer-types'; | ||
| import type { Params } from '../../server/request/params'; | ||
@@ -86,3 +86,3 @@ import type { FlightRouterState, FlightSegmentPath, CacheNode, LoadingModuleData } from './app-router-types'; | ||
| tree: FlightRouterState; | ||
| focusAndScrollRef: FocusAndScrollRef; | ||
| scrollRef: ScrollHandlerRef; | ||
| nextUrl: string | null; | ||
@@ -89,0 +89,0 @@ previousNextUrl: string | null; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/shared/lib/app-router-context.shared-runtime.ts"],"sourcesContent":["'use client'\n\nimport type {\n FocusAndScrollRef,\n PrefetchKind,\n} from '../../client/components/router-reducer/router-reducer-types'\nimport type { Params } from '../../server/request/params'\nimport type {\n FlightRouterState,\n FlightSegmentPath,\n CacheNode,\n LoadingModuleData,\n} from './app-router-types'\nimport React from 'react'\n\nexport interface NavigateOptions {\n scroll?: boolean\n /**\n * Transition types to apply when navigating. These types are passed to\n * [`React.addTransitionType`](https://react.dev/reference/react/addTransitionType)\n * inside the navigation transition, enabling\n * [`<ViewTransition>`](https://react.dev/reference/react/ViewTransition) components\n * to apply different animations based on the type of navigation.\n */\n transitionTypes?: string[]\n}\n\nexport interface PrefetchOptions {\n kind: PrefetchKind\n onInvalidate?: () => void\n}\n\nexport interface AppRouterInstance {\n /**\n * Navigate to the previous history entry.\n */\n back(): void\n /**\n * Navigate to the next history entry.\n */\n forward(): void\n /**\n * Refresh the current page.\n */\n refresh(): void\n /**\n * Refresh the current page. Use in development only.\n * @internal\n */\n hmrRefresh(): void\n /**\n * Navigate to the provided href.\n * Pushes a new history entry.\n */\n push(href: string, options?: NavigateOptions): void\n /**\n * Navigate to the provided href.\n * Replaces the current history entry.\n */\n replace(href: string, options?: NavigateOptions): void\n /**\n * Prefetch the provided href.\n */\n prefetch(href: string, options?: PrefetchOptions): void\n /**\n * Perform a gesture navigation using prefetched data.\n * Only available when experimental.gestureTransition is enabled.\n * @experimental\n */\n experimental_gesturePush?(href: string, options?: NavigateOptions): void\n /**\n * An opaque string identifier scoped to the current route segment.\n *\n * Changes when the surrounding segment is freshly created by a push or\n * replace navigation. Stays the same for back/forward navigations,\n * `router.refresh()`, and search-param/hash-only changes.\n *\n * Intended to be passed to a React `key` to opt out of state preservation\n * on fresh navigations:\n *\n * ```tsx\n * <form key={useRouter().bfcacheId}>\n * ```\n *\n * In most cases, prefer resetting state explicitly in an event handler, or\n * deriving a key from your data (e.g. a draft id from the server). Use\n * `bfcacheId` only when those patterns aren't a fit.\n */\n bfcacheId: string\n}\n\nexport const AppRouterContext = React.createContext<AppRouterInstance | null>(\n null\n)\nexport const LayoutRouterContext = React.createContext<{\n parentTree: FlightRouterState\n parentCacheNode: CacheNode\n parentSegmentPath: FlightSegmentPath | null\n parentParams: Params\n parentLoadingData: LoadingModuleData | null\n debugNameContext: string\n url: string\n isActive: boolean\n} | null>(null)\n\nexport const GlobalLayoutRouterContext = React.createContext<{\n tree: FlightRouterState\n focusAndScrollRef: FocusAndScrollRef\n nextUrl: string | null\n previousNextUrl: string | null\n}>(null as any)\n\nexport const TemplateContext = React.createContext<React.ReactNode>(null as any)\n\nif (process.env.NODE_ENV !== 'production') {\n AppRouterContext.displayName = 'AppRouterContext'\n LayoutRouterContext.displayName = 'LayoutRouterContext'\n GlobalLayoutRouterContext.displayName = 'GlobalLayoutRouterContext'\n TemplateContext.displayName = 'TemplateContext'\n}\n\nexport const MissingSlotContext = React.createContext<Set<string>>(new Set())\n"],"names":["AppRouterContext","GlobalLayoutRouterContext","LayoutRouterContext","MissingSlotContext","TemplateContext","React","createContext","process","env","NODE_ENV","displayName","Set"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;IA2FaA,gBAAgB;eAAhBA;;IAcAC,yBAAyB;eAAzBA;;IAXAC,mBAAmB;eAAnBA;;IA2BAC,kBAAkB;eAAlBA;;IATAC,eAAe;eAAfA;;;;gEAnGK;AA8EX,MAAMJ,mBAAmBK,cAAK,CAACC,aAAa,CACjD;AAEK,MAAMJ,sBAAsBG,cAAK,CAACC,aAAa,CAS5C;AAEH,MAAML,4BAA4BI,cAAK,CAACC,aAAa,CAKzD;AAEI,MAAMF,kBAAkBC,cAAK,CAACC,aAAa,CAAkB;AAEpE,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;IACzCT,iBAAiBU,WAAW,GAAG;IAC/BR,oBAAoBQ,WAAW,GAAG;IAClCT,0BAA0BS,WAAW,GAAG;IACxCN,gBAAgBM,WAAW,GAAG;AAChC;AAEO,MAAMP,qBAAqBE,cAAK,CAACC,aAAa,CAAc,IAAIK","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/shared/lib/app-router-context.shared-runtime.ts"],"sourcesContent":["'use client'\n\nimport type {\n ScrollHandlerRef,\n PrefetchKind,\n} from '../../client/components/router-reducer/router-reducer-types'\nimport type { Params } from '../../server/request/params'\nimport type {\n FlightRouterState,\n FlightSegmentPath,\n CacheNode,\n LoadingModuleData,\n} from './app-router-types'\nimport React from 'react'\n\nexport interface NavigateOptions {\n scroll?: boolean\n /**\n * Transition types to apply when navigating. These types are passed to\n * [`React.addTransitionType`](https://react.dev/reference/react/addTransitionType)\n * inside the navigation transition, enabling\n * [`<ViewTransition>`](https://react.dev/reference/react/ViewTransition) components\n * to apply different animations based on the type of navigation.\n */\n transitionTypes?: string[]\n}\n\nexport interface PrefetchOptions {\n kind: PrefetchKind\n onInvalidate?: () => void\n}\n\nexport interface AppRouterInstance {\n /**\n * Navigate to the previous history entry.\n */\n back(): void\n /**\n * Navigate to the next history entry.\n */\n forward(): void\n /**\n * Refresh the current page.\n */\n refresh(): void\n /**\n * Refresh the current page. Use in development only.\n * @internal\n */\n hmrRefresh(): void\n /**\n * Navigate to the provided href.\n * Pushes a new history entry.\n */\n push(href: string, options?: NavigateOptions): void\n /**\n * Navigate to the provided href.\n * Replaces the current history entry.\n */\n replace(href: string, options?: NavigateOptions): void\n /**\n * Prefetch the provided href.\n */\n prefetch(href: string, options?: PrefetchOptions): void\n /**\n * Perform a gesture navigation using prefetched data.\n * Only available when experimental.gestureTransition is enabled.\n * @experimental\n */\n experimental_gesturePush?(href: string, options?: NavigateOptions): void\n /**\n * An opaque string identifier scoped to the current route segment.\n *\n * Changes when the surrounding segment is freshly created by a push or\n * replace navigation. Stays the same for back/forward navigations,\n * `router.refresh()`, and search-param/hash-only changes.\n *\n * Intended to be passed to a React `key` to opt out of state preservation\n * on fresh navigations:\n *\n * ```tsx\n * <form key={useRouter().bfcacheId}>\n * ```\n *\n * In most cases, prefer resetting state explicitly in an event handler, or\n * deriving a key from your data (e.g. a draft id from the server). Use\n * `bfcacheId` only when those patterns aren't a fit.\n */\n bfcacheId: string\n}\n\nexport const AppRouterContext = React.createContext<AppRouterInstance | null>(\n null\n)\nexport const LayoutRouterContext = React.createContext<{\n parentTree: FlightRouterState\n parentCacheNode: CacheNode\n parentSegmentPath: FlightSegmentPath | null\n parentParams: Params\n parentLoadingData: LoadingModuleData | null\n debugNameContext: string\n url: string\n isActive: boolean\n} | null>(null)\n\nexport const GlobalLayoutRouterContext = React.createContext<{\n tree: FlightRouterState\n scrollRef: ScrollHandlerRef\n nextUrl: string | null\n previousNextUrl: string | null\n}>(null as any)\n\nexport const TemplateContext = React.createContext<React.ReactNode>(null as any)\n\nif (process.env.NODE_ENV !== 'production') {\n AppRouterContext.displayName = 'AppRouterContext'\n LayoutRouterContext.displayName = 'LayoutRouterContext'\n GlobalLayoutRouterContext.displayName = 'GlobalLayoutRouterContext'\n TemplateContext.displayName = 'TemplateContext'\n}\n\nexport const MissingSlotContext = React.createContext<Set<string>>(new Set())\n"],"names":["AppRouterContext","GlobalLayoutRouterContext","LayoutRouterContext","MissingSlotContext","TemplateContext","React","createContext","process","env","NODE_ENV","displayName","Set"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;IA2FaA,gBAAgB;eAAhBA;;IAcAC,yBAAyB;eAAzBA;;IAXAC,mBAAmB;eAAnBA;;IA2BAC,kBAAkB;eAAlBA;;IATAC,eAAe;eAAfA;;;;gEAnGK;AA8EX,MAAMJ,mBAAmBK,cAAK,CAACC,aAAa,CACjD;AAEK,MAAMJ,sBAAsBG,cAAK,CAACC,aAAa,CAS5C;AAEH,MAAML,4BAA4BI,cAAK,CAACC,aAAa,CAKzD;AAEI,MAAMF,kBAAkBC,cAAK,CAACC,aAAa,CAAkB;AAEpE,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;IACzCT,iBAAiBU,WAAW,GAAG;IAC/BR,oBAAoBQ,WAAW,GAAG;IAClCT,0BAA0BS,WAAW,GAAG;IACxCN,gBAAgBM,WAAW,GAAG;AAChC;AAEO,MAAMP,qBAAqBE,cAAK,CAACC,aAAa,CAAc,IAAIK","ignoreList":[0]} |
@@ -24,3 +24,3 @@ "use strict"; | ||
| function isStableBuild() { | ||
| return !"16.3.1-canary.10"?.includes('canary') && !process.env.__NEXT_TEST_MODE && !process.env.NEXT_PRIVATE_LOCAL_DEV; | ||
| return !"16.3.1-canary.11"?.includes('canary') && !process.env.__NEXT_TEST_MODE && !process.env.NEXT_PRIVATE_LOCAL_DEV; | ||
| } | ||
@@ -27,0 +27,0 @@ class CanaryOnlyConfigError extends Error { |
@@ -466,3 +466,3 @@ "use strict"; | ||
| // Client middleware manifest This is only used in dev though, packages/next/src/build/index.ts | ||
| // writes the mainfest again for builds. | ||
| // writes the manifest again for builds. | ||
| const matchers = middlewareManifest?.middleware['/']?.matchers || []; | ||
@@ -469,0 +469,0 @@ const clientMiddlewareManifestJs = `self.__MIDDLEWARE_MATCHERS = ${JSON.stringify(matchers, null, 2)};self.__MIDDLEWARE_MATCHERS_CB && self.__MIDDLEWARE_MATCHERS_CB()`; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/shared/lib/turbopack/manifest-loader.ts"],"sourcesContent":["import type {\n EdgeFunctionDefinition,\n MiddlewareManifest,\n} from '../../../build/webpack/plugins/middleware-plugin'\nimport type { BuildManifest } from '../../../server/get-page-files'\nimport type { PagesManifest } from '../../../build/webpack/plugins/pages-manifest-plugin'\nimport type { ActionManifest } from '../../../build/webpack/plugins/flight-client-entry-plugin'\nimport type { NextFontManifest } from '../../../build/webpack/plugins/next-font-manifest-plugin'\nimport type { REACT_LOADABLE_MANIFEST } from '../constants'\nimport {\n APP_PATHS_MANIFEST,\n BUILD_MANIFEST,\n CLIENT_STATIC_FILES_PATH,\n INTERCEPTION_ROUTE_REWRITE_MANIFEST,\n MIDDLEWARE_BUILD_MANIFEST,\n MIDDLEWARE_MANIFEST,\n NEXT_FONT_MANIFEST,\n PAGES_MANIFEST,\n SERVER_REFERENCE_MANIFEST,\n SUBRESOURCE_INTEGRITY_MANIFEST,\n TURBOPACK_CLIENT_BUILD_MANIFEST,\n TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST,\n} from '../constants'\nimport { join, posix } from 'path'\nimport { readFileSync } from 'fs'\nimport type { SetupOpts } from '../../../server/lib/router-utils/setup-dev-bundler'\nimport { deleteCache } from '../../../server/dev/require-cache'\nimport { writeFileAtomic } from '../../../lib/fs/write-atomic'\nimport getAssetPathFromRoute from '../router/utils/get-asset-path-from-route'\nimport { getEntryKey, splitEntryKey, type EntryKey } from './entry-key'\nimport type { CustomRoutes } from '../../../lib/load-custom-routes'\nimport { getSortedRoutes } from '../router/utils'\nimport { existsSync } from 'fs'\nimport {\n addMetadataIdToRoute,\n addRouteSuffix,\n removeRouteSuffix,\n} from '../../../server/dev/turbopack-utils'\nimport { tryToParsePath } from '../../../lib/try-to-parse-path'\nimport { safePathToRegexp } from '../router/utils/route-match-utils'\nimport type { Entrypoints } from '../../../build/swc/types'\nimport {\n normalizeRewritesForBuildManifest,\n type ClientBuildManifest,\n srcEmptySsgManifest,\n processRoute,\n createEdgeRuntimeManifest,\n} from '../../../build/webpack/plugins/build-manifest-plugin-utils'\nimport type { SubresourceIntegrityManifest } from '../../../build'\n\ninterface InstrumentationDefinition {\n files: string[]\n name: 'instrumentation'\n}\n\ntype TurbopackMiddlewareManifest = MiddlewareManifest & {\n instrumentation?: InstrumentationDefinition\n}\n\ntype ManifestName =\n | typeof MIDDLEWARE_MANIFEST\n | typeof BUILD_MANIFEST\n | typeof PAGES_MANIFEST\n | typeof APP_PATHS_MANIFEST\n | `${typeof SERVER_REFERENCE_MANIFEST}.json`\n | `${typeof SUBRESOURCE_INTEGRITY_MANIFEST}.json`\n | `${typeof NEXT_FONT_MANIFEST}.json`\n | typeof REACT_LOADABLE_MANIFEST\n | typeof TURBOPACK_CLIENT_BUILD_MANIFEST\n\nconst getManifestPath = (\n page: string,\n distDir: string,\n name: ManifestName,\n type: string,\n firstCall: boolean\n) => {\n let manifestPath = posix.join(\n distDir,\n `server`,\n type,\n type === 'middleware' || type === 'instrumentation'\n ? ''\n : type === 'app'\n ? page\n : getAssetPathFromRoute(page),\n name\n )\n\n if (firstCall) {\n const isSitemapRoute = /[\\\\/]sitemap(.xml)?\\/route$/.test(page)\n // Check the ambiguity of /sitemap and /sitemap.xml\n if (isSitemapRoute && !existsSync(manifestPath)) {\n manifestPath = getManifestPath(\n page.replace(/\\/sitemap\\/route$/, '/sitemap.xml/route'),\n distDir,\n name,\n type,\n false\n )\n }\n // existsSync is faster than using the async version\n if (!existsSync(manifestPath) && page.endsWith('/route')) {\n // TODO: Improve implementation of metadata routes, currently it requires this extra check for the variants of the files that can be written.\n let basePage = removeRouteSuffix(page)\n // For sitemap.xml routes with generateSitemaps, the manifest is at\n // /sitemap/[__metadata_id__]/route (without .xml), because the route\n // handler serves at /sitemap/[id] not /sitemap.xml/[id]\n if (basePage.endsWith('/sitemap.xml')) {\n basePage = basePage.slice(0, -'.xml'.length)\n }\n let metadataPage = addRouteSuffix(addMetadataIdToRoute(basePage))\n manifestPath = getManifestPath(metadataPage, distDir, name, type, false)\n }\n }\n\n return manifestPath\n}\n\nfunction readPartialManifestContent(\n distDir: string,\n name: ManifestName,\n pageName: string,\n type: 'pages' | 'app' | 'middleware' | 'instrumentation' = 'pages'\n): string {\n const page = pageName\n const manifestPath = getManifestPath(page, distDir, name, type, true)\n return readFileSync(posix.join(manifestPath), 'utf-8')\n}\n\n/// Helper class that stores a map of manifests and tracks if they have changed\n/// since the last time they were written to disk. This is used to avoid\n/// unnecessary writes to disk.\nclass ManifestsMap<K, V> {\n private rawMap = new Map<K, string>()\n private map = new Map<K, V>()\n private extraInvalidationKey: string | undefined = undefined\n private changed = true\n\n set(key: K, value: string) {\n if (this.rawMap.get(key) === value) return\n this.changed = true\n this.rawMap.set(key, value)\n this.map.set(key, JSON.parse(value))\n }\n\n delete(key: K) {\n if (this.map.has(key)) {\n this.changed = true\n this.rawMap.delete(key)\n this.map.delete(key)\n }\n }\n\n get(key: K) {\n return this.map.get(key)\n }\n\n takeChanged(extraInvalidationKey?: any) {\n let changed = this.changed\n if (extraInvalidationKey !== undefined) {\n const stringified = JSON.stringify(extraInvalidationKey)\n if (this.extraInvalidationKey !== stringified) {\n this.extraInvalidationKey = stringified\n changed = true\n }\n }\n this.changed = false\n return changed\n }\n\n values() {\n return this.map.values()\n }\n\n entries() {\n return this.map.entries()\n }\n}\n\nexport class TurbopackManifestLoader {\n private actionManifests: ManifestsMap<EntryKey, ActionManifest> =\n new ManifestsMap()\n private appPathsManifests: ManifestsMap<EntryKey, PagesManifest> =\n new ManifestsMap()\n private buildManifests: ManifestsMap<EntryKey, BuildManifest> =\n new ManifestsMap()\n private clientBuildManifests: ManifestsMap<EntryKey, ClientBuildManifest> =\n new ManifestsMap()\n private fontManifests: ManifestsMap<EntryKey, NextFontManifest> =\n new ManifestsMap()\n private middlewareManifests: ManifestsMap<\n EntryKey,\n TurbopackMiddlewareManifest\n > = new ManifestsMap()\n private pagesManifests: ManifestsMap<string, PagesManifest> =\n new ManifestsMap()\n private sriManifests: ManifestsMap<EntryKey, SubresourceIntegrityManifest> =\n new ManifestsMap()\n private encryptionKey: string\n /// interceptionRewrites that have been written to disk\n /// This is used to avoid unnecessary writes if the rewrites haven't changed\n private cachedInterceptionRewrites: string | undefined = undefined\n private pendingCacheDeletes: string[] = []\n\n private readonly distDir: string\n private readonly buildId: string\n private readonly dev: boolean\n private readonly sriEnabled: boolean\n\n constructor({\n distDir,\n buildId,\n encryptionKey,\n dev,\n sriEnabled,\n }: {\n buildId: string\n distDir: string\n encryptionKey: string\n dev: boolean\n sriEnabled: boolean\n }) {\n this.distDir = distDir\n this.buildId = buildId\n this.encryptionKey = encryptionKey\n this.dev = dev\n this.sriEnabled = sriEnabled\n }\n\n delete(key: EntryKey) {\n this.actionManifests.delete(key)\n this.appPathsManifests.delete(key)\n this.buildManifests.delete(key)\n this.clientBuildManifests.delete(key)\n this.fontManifests.delete(key)\n this.middlewareManifests.delete(key)\n this.pagesManifests.delete(key)\n }\n\n loadActionManifest(pageName: string): void {\n this.actionManifests.set(\n getEntryKey('app', 'server', pageName),\n readPartialManifestContent(\n this.distDir,\n `${SERVER_REFERENCE_MANIFEST}.json`,\n pageName,\n 'app'\n )\n )\n }\n\n private mergeActionManifests(manifests: Iterable<ActionManifest>) {\n type ActionEntries = ActionManifest['edge' | 'node']\n const manifest: ActionManifest = {\n node: {},\n edge: {},\n encryptionKey: this.encryptionKey,\n }\n\n function mergeActionIds(\n actionEntries: ActionEntries,\n other: ActionEntries\n ): void {\n for (const key in other) {\n const action = (actionEntries[key] ??= {\n workers: {},\n })\n action.filename = other[key].filename\n action.exportedName = other[key].exportedName\n Object.assign(action.workers, other[key].workers)\n }\n }\n\n for (const m of manifests) {\n mergeActionIds(manifest.node, m.node)\n mergeActionIds(manifest.edge, m.edge)\n }\n for (const key in manifest.node) {\n const entry = manifest.node[key]\n entry.workers = sortObjectByKey(entry.workers)\n }\n for (const key in manifest.edge) {\n const entry = manifest.edge[key]\n entry.workers = sortObjectByKey(entry.workers)\n }\n\n return manifest\n }\n\n private writeActionManifest(): void {\n if (!this.actionManifests.takeChanged()) {\n return\n }\n const actionManifest = this.mergeActionManifests(\n this.actionManifests.values()\n )\n const actionManifestJsonPath = join(\n this.distDir,\n 'server',\n `${SERVER_REFERENCE_MANIFEST}.json`\n )\n const actionManifestJsPath = join(\n this.distDir,\n 'server',\n `${SERVER_REFERENCE_MANIFEST}.js`\n )\n const json = JSON.stringify(actionManifest, null, 2)\n this.pendingCacheDeletes.push(actionManifestJsonPath)\n this.pendingCacheDeletes.push(actionManifestJsPath)\n writeFileAtomic(actionManifestJsonPath, json)\n writeFileAtomic(\n actionManifestJsPath,\n `self.__RSC_SERVER_MANIFEST=${JSON.stringify(json)}`\n )\n }\n\n loadAppPathsManifest(pageName: string): void {\n this.appPathsManifests.set(\n getEntryKey('app', 'server', pageName),\n readPartialManifestContent(\n this.distDir,\n APP_PATHS_MANIFEST,\n pageName,\n 'app'\n )\n )\n }\n\n private writeAppPathsManifest(): void {\n if (!this.appPathsManifests.takeChanged()) {\n return\n }\n const appPathsManifest = this.mergePagesManifests(\n this.appPathsManifests.values()\n )\n const appPathsManifestPath = join(\n this.distDir,\n 'server',\n APP_PATHS_MANIFEST\n )\n this.pendingCacheDeletes.push(appPathsManifestPath)\n writeFileAtomic(\n appPathsManifestPath,\n JSON.stringify(appPathsManifest, null, 2)\n )\n }\n\n private writeSriManifest(): void {\n if (!this.sriEnabled || !this.sriManifests.takeChanged()) {\n return\n }\n const sriManifest = this.mergeSriManifests(this.sriManifests.values())\n const pathJson = join(\n this.distDir,\n 'server',\n `${SUBRESOURCE_INTEGRITY_MANIFEST}.json`\n )\n const pathJs = join(\n this.distDir,\n 'server',\n `${SUBRESOURCE_INTEGRITY_MANIFEST}.js`\n )\n this.pendingCacheDeletes.push(pathJson)\n this.pendingCacheDeletes.push(pathJs)\n writeFileAtomic(pathJson, JSON.stringify(sriManifest, null, 2))\n writeFileAtomic(\n pathJs,\n `self.__SUBRESOURCE_INTEGRITY_MANIFEST=${JSON.stringify(\n JSON.stringify(sriManifest)\n )}`\n )\n }\n\n loadBuildManifest(pageName: string, type: 'app' | 'pages' = 'pages'): void {\n this.buildManifests.set(\n getEntryKey(type, 'server', pageName),\n readPartialManifestContent(this.distDir, BUILD_MANIFEST, pageName, type)\n )\n }\n\n loadClientBuildManifest(\n pageName: string,\n type: 'app' | 'pages' = 'pages'\n ): void {\n this.clientBuildManifests.set(\n getEntryKey(type, 'server', pageName),\n readPartialManifestContent(\n this.distDir,\n TURBOPACK_CLIENT_BUILD_MANIFEST,\n pageName,\n type\n )\n )\n }\n\n loadSriManifest(pageName: string, type: 'app' | 'pages' = 'pages'): void {\n if (!this.sriEnabled) return\n this.sriManifests.set(\n getEntryKey(type, 'client', pageName),\n readPartialManifestContent(\n this.distDir,\n `${SUBRESOURCE_INTEGRITY_MANIFEST}.json`,\n pageName,\n type\n )\n )\n }\n\n private mergeBuildManifests(\n manifests: Iterable<BuildManifest>,\n lowPriorityFiles: string[]\n ) {\n const manifest: Partial<BuildManifest> & Pick<BuildManifest, 'pages'> = {\n pages: {\n '/_app': [],\n },\n // Something in next.js depends on these to exist even for app dir rendering\n devFiles: [],\n polyfillFiles: [],\n lowPriorityFiles,\n rootMainFiles: [],\n rootMainFilesTree: {},\n pagesChunkGroupBootstrapParams: {},\n }\n for (const m of manifests) {\n Object.assign(manifest.pages, m.pages)\n if (m.rootMainFiles.length) manifest.rootMainFiles = m.rootMainFiles\n // polyfillFiles should always be the same, so we can overwrite instead of actually merging\n if (m.polyfillFiles.length) manifest.polyfillFiles = m.polyfillFiles\n if (m.rootMainFilesTree) {\n Object.assign(manifest.rootMainFilesTree!, m.rootMainFilesTree)\n }\n if (m.pagesChunkGroupBootstrapParams) {\n Object.assign(\n manifest.pagesChunkGroupBootstrapParams!,\n m.pagesChunkGroupBootstrapParams\n )\n }\n if (m.chunkLoadingGlobal)\n manifest.chunkLoadingGlobal = m.chunkLoadingGlobal\n }\n manifest.pages = sortObjectByKey(manifest.pages) as BuildManifest['pages']\n return manifest\n }\n\n private mergeClientBuildManifests(\n manifests: Iterable<ClientBuildManifest>,\n rewrites: CustomRoutes['rewrites'],\n sortedPageKeys: string[]\n ): ClientBuildManifest {\n const manifest = {\n __rewrites: rewrites as any,\n sortedPages: sortedPageKeys,\n }\n for (const m of manifests) {\n Object.assign(manifest, m)\n }\n return sortObjectByKey(manifest)\n }\n\n private writeInterceptionRouteRewriteManifest(\n devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined,\n productionRewrites: CustomRoutes['rewrites'] | undefined\n ): void {\n const rewrites = productionRewrites ?? {\n ...devRewrites,\n beforeFiles: (devRewrites?.beforeFiles ?? []).map(processRoute),\n afterFiles: (devRewrites?.afterFiles ?? []).map(processRoute),\n fallback: (devRewrites?.fallback ?? []).map(processRoute),\n }\n\n const interceptionRewrites = JSON.stringify(\n rewrites.beforeFiles.filter(\n (\n require('../../../lib/is-interception-route-rewrite') as typeof import('../../../lib/is-interception-route-rewrite')\n ).isInterceptionRouteRewrite\n )\n )\n\n if (this.cachedInterceptionRewrites === interceptionRewrites) {\n return\n }\n this.cachedInterceptionRewrites = interceptionRewrites\n\n const interceptionRewriteManifestPath = join(\n this.distDir,\n 'server',\n `${INTERCEPTION_ROUTE_REWRITE_MANIFEST}.js`\n )\n this.pendingCacheDeletes.push(interceptionRewriteManifestPath)\n\n writeFileAtomic(\n interceptionRewriteManifestPath,\n `self.__INTERCEPTION_ROUTE_REWRITE_MANIFEST=${JSON.stringify(\n interceptionRewrites\n )};`\n )\n }\n\n private writeBuildManifest(lowPriorityFiles: string[]): void {\n if (!this.buildManifests.takeChanged()) {\n return\n }\n const buildManifest = this.mergeBuildManifests(\n this.buildManifests.values(),\n lowPriorityFiles\n )\n\n const buildManifestPath = join(this.distDir, BUILD_MANIFEST)\n const middlewareBuildManifestPath = join(\n this.distDir,\n 'server',\n `${MIDDLEWARE_BUILD_MANIFEST}.js`\n )\n\n this.pendingCacheDeletes.push(buildManifestPath)\n this.pendingCacheDeletes.push(middlewareBuildManifestPath)\n writeFileAtomic(buildManifestPath, JSON.stringify(buildManifest, null, 2))\n writeFileAtomic(\n middlewareBuildManifestPath,\n createEdgeRuntimeManifest(buildManifest)\n )\n\n // Write fallback build manifest\n const fallbackBuildManifest = this.mergeBuildManifests(\n [\n this.buildManifests.get(getEntryKey('pages', 'server', '_app')),\n this.buildManifests.get(getEntryKey('pages', 'server', '_error')),\n ].filter(Boolean) as BuildManifest[],\n lowPriorityFiles\n )\n const fallbackBuildManifestPath = join(\n this.distDir,\n `fallback-${BUILD_MANIFEST}`\n )\n this.pendingCacheDeletes.push(fallbackBuildManifestPath)\n writeFileAtomic(\n fallbackBuildManifestPath,\n JSON.stringify(fallbackBuildManifest, null, 2)\n )\n }\n\n private writeClientBuildManifest(\n entrypoints: Entrypoints,\n devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined,\n productionRewrites: CustomRoutes['rewrites'] | undefined\n ): string[] {\n const rewrites = normalizeRewritesForBuildManifest(\n productionRewrites ?? {\n ...devRewrites,\n beforeFiles: (devRewrites?.beforeFiles ?? []).map(processRoute),\n afterFiles: (devRewrites?.afterFiles ?? []).map(processRoute),\n fallback: (devRewrites?.fallback ?? []).map(processRoute),\n }\n )\n\n const pagesKeys = [...entrypoints.page.keys()]\n if (entrypoints.global.app) {\n pagesKeys.push('/_app')\n }\n if (entrypoints.global.error) {\n pagesKeys.push('/_error')\n }\n\n const sortedPageKeys = getSortedRoutes(pagesKeys)\n\n let buildManifestPath = posix.join(\n CLIENT_STATIC_FILES_PATH,\n this.buildId,\n '_buildManifest.js'\n )\n let ssgManifestPath = posix.join(\n CLIENT_STATIC_FILES_PATH,\n this.buildId,\n '_ssgManifest.js'\n )\n\n if (\n this.dev &&\n !this.clientBuildManifests.takeChanged({ rewrites, sortedPageKeys })\n ) {\n return [buildManifestPath, ssgManifestPath]\n }\n\n const clientBuildManifest = this.mergeClientBuildManifests(\n this.clientBuildManifests.values(),\n rewrites,\n sortedPageKeys\n )\n\n // Expose each route's bootstrap params and the chunk-loading global to the client\n // so `route-loader` can instantiate a navigated page's entry module. The server\n // stores params as raw JSON per route.\n const pageBootstrapParams: Record<string, unknown> = {}\n let chunkLoadingGlobal: string | undefined\n for (const [key, m] of this.buildManifests.entries()) {\n // Only the pages-router `route-loader` reads `__TURBOPACK_PAGE_BOOTSTRAP`. App routes\n // navigate via flight and never use it, so skip app entries to keep `_buildManifest.js`\n // (loaded on every page) small.\n if (splitEntryKey(key).type !== 'pages') continue\n if (m.chunkLoadingGlobal) chunkLoadingGlobal = m.chunkLoadingGlobal\n for (const [route, params] of Object.entries(\n m.pagesChunkGroupBootstrapParams ?? {}\n )) {\n pageBootstrapParams[route] = params\n }\n }\n\n // Only emit the bootstrap globals when a route actually inlined its bootstrap (shared runtime\n // enabled).\n const hasBootstrapParams = Object.keys(pageBootstrapParams).length > 0\n const clientBuildManifestJs =\n `self.__BUILD_MANIFEST = ${JSON.stringify(clientBuildManifest, null, 2)};` +\n (hasBootstrapParams\n ? `self.__TURBOPACK_PAGE_BOOTSTRAP = ${JSON.stringify(pageBootstrapParams)};` +\n (chunkLoadingGlobal\n ? `self.__TURBOPACK_CHUNK_LOADING_GLOBAL = ${JSON.stringify(\n chunkLoadingGlobal\n )};`\n : '')\n : '') +\n `self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()`\n\n writeFileAtomic(\n join(this.distDir, buildManifestPath),\n clientBuildManifestJs\n )\n // This is just an empty placeholder, the actual manifest is written after prerendering in\n // packages/next/src/build/index.ts\n writeFileAtomic(join(this.distDir, ssgManifestPath), srcEmptySsgManifest)\n\n return [buildManifestPath, ssgManifestPath]\n }\n\n loadFontManifest(pageName: string, type: 'app' | 'pages' = 'pages'): void {\n this.fontManifests.set(\n getEntryKey(type, 'server', pageName),\n readPartialManifestContent(\n this.distDir,\n `${NEXT_FONT_MANIFEST}.json`,\n pageName,\n type\n )\n )\n }\n\n private mergeFontManifests(manifests: Iterable<NextFontManifest>) {\n const manifest: NextFontManifest = {\n app: {},\n appUsingSizeAdjust: false,\n pages: {},\n pagesUsingSizeAdjust: false,\n }\n for (const m of manifests) {\n Object.assign(manifest.app, m.app)\n Object.assign(manifest.pages, m.pages)\n\n manifest.appUsingSizeAdjust =\n manifest.appUsingSizeAdjust || m.appUsingSizeAdjust\n manifest.pagesUsingSizeAdjust =\n manifest.pagesUsingSizeAdjust || m.pagesUsingSizeAdjust\n }\n manifest.app = sortObjectByKey(manifest.app)\n manifest.pages = sortObjectByKey(manifest.pages)\n return manifest\n }\n\n private async writeNextFontManifest(): Promise<void> {\n if (!this.fontManifests.takeChanged()) {\n return\n }\n const fontManifest = this.mergeFontManifests(this.fontManifests.values())\n const json = JSON.stringify(fontManifest, null, 2)\n\n const fontManifestJsonPath = join(\n this.distDir,\n 'server',\n `${NEXT_FONT_MANIFEST}.json`\n )\n const fontManifestJsPath = join(\n this.distDir,\n 'server',\n `${NEXT_FONT_MANIFEST}.js`\n )\n this.pendingCacheDeletes.push(fontManifestJsonPath)\n this.pendingCacheDeletes.push(fontManifestJsPath)\n writeFileAtomic(fontManifestJsonPath, json)\n writeFileAtomic(\n fontManifestJsPath,\n `self.__NEXT_FONT_MANIFEST=${JSON.stringify(json)}`\n )\n }\n\n /**\n * @returns If the manifest was written or not\n */\n loadMiddlewareManifest(\n pageName: string,\n type: 'pages' | 'app' | 'middleware' | 'instrumentation'\n ): boolean {\n const middlewareManifestPath = getManifestPath(\n pageName,\n this.distDir,\n MIDDLEWARE_MANIFEST,\n type,\n true\n )\n\n // middlewareManifest is actually \"edge manifest\" and not all routes are edge runtime. If it is not written we skip it.\n if (!existsSync(middlewareManifestPath)) {\n return false\n }\n\n this.middlewareManifests.set(\n getEntryKey(\n type === 'middleware' || type === 'instrumentation' ? 'root' : type,\n 'server',\n pageName\n ),\n readPartialManifestContent(\n this.distDir,\n MIDDLEWARE_MANIFEST,\n pageName,\n type\n )\n )\n\n return true\n }\n\n getMiddlewareManifest(key: EntryKey) {\n return this.middlewareManifests.get(key)\n }\n\n deleteMiddlewareManifest(key: EntryKey) {\n return this.middlewareManifests.delete(key)\n }\n\n private mergeMiddlewareManifests(\n manifests: Iterable<TurbopackMiddlewareManifest>\n ): MiddlewareManifest {\n const manifest: MiddlewareManifest = {\n version: 3,\n middleware: {},\n sortedMiddleware: [],\n functions: {},\n }\n let instrumentation: InstrumentationDefinition | undefined = undefined\n for (const m of manifests) {\n Object.assign(manifest.functions, m.functions)\n Object.assign(manifest.middleware, m.middleware)\n if (m.instrumentation) {\n instrumentation = m.instrumentation\n }\n }\n manifest.functions = sortObjectByKey(manifest.functions)\n manifest.middleware = sortObjectByKey(manifest.middleware)\n const updateFunctionDefinition = (\n fun: EdgeFunctionDefinition\n ): EdgeFunctionDefinition => {\n return {\n ...fun,\n files: [...(instrumentation?.files ?? []), ...fun.files],\n }\n }\n for (const key of Object.keys(manifest.middleware)) {\n const value = manifest.middleware[key]\n manifest.middleware[key] = updateFunctionDefinition(value)\n }\n for (const key of Object.keys(manifest.functions)) {\n const value = manifest.functions[key]\n manifest.functions[key] = updateFunctionDefinition(value)\n }\n for (const fun of Object.values(manifest.functions).concat(\n Object.values(manifest.middleware)\n )) {\n for (const matcher of fun.matchers) {\n if (!matcher.regexp) {\n matcher.regexp = safePathToRegexp(matcher.originalSource, [], {\n delimiter: '/',\n sensitive: false,\n strict: true,\n }).source.replaceAll('\\\\/', '/')\n }\n }\n }\n manifest.sortedMiddleware = Object.keys(manifest.middleware)\n\n return manifest\n }\n\n private writeMiddlewareManifest(): {\n clientMiddlewareManifestPath: string\n } {\n let clientMiddlewareManifestPath = posix.join(\n CLIENT_STATIC_FILES_PATH,\n this.buildId,\n TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST\n )\n\n if (this.dev && !this.middlewareManifests.takeChanged()) {\n return {\n clientMiddlewareManifestPath,\n }\n }\n const middlewareManifest = this.mergeMiddlewareManifests(\n this.middlewareManifests.values()\n )\n\n // Server middleware manifest\n\n // Normalize regexes as it uses path-to-regexp\n for (const key in middlewareManifest.middleware) {\n middlewareManifest.middleware[key].matchers.forEach((matcher) => {\n if (!matcher.regexp.startsWith('^')) {\n const parsedPage = tryToParsePath(matcher.regexp)\n if (parsedPage.error || !parsedPage.regexStr) {\n throw new Error(`Invalid source: ${matcher.regexp}`)\n }\n matcher.regexp = parsedPage.regexStr\n }\n })\n }\n\n const middlewareManifestPath = join(\n this.distDir,\n 'server',\n MIDDLEWARE_MANIFEST\n )\n this.pendingCacheDeletes.push(middlewareManifestPath)\n writeFileAtomic(\n middlewareManifestPath,\n JSON.stringify(middlewareManifest, null, 2)\n )\n\n // Client middleware manifest This is only used in dev though, packages/next/src/build/index.ts\n // writes the mainfest again for builds.\n const matchers = middlewareManifest?.middleware['/']?.matchers || []\n\n const clientMiddlewareManifestJs = `self.__MIDDLEWARE_MATCHERS = ${JSON.stringify(\n matchers,\n null,\n 2\n )};self.__MIDDLEWARE_MATCHERS_CB && self.__MIDDLEWARE_MATCHERS_CB()`\n\n this.pendingCacheDeletes.push(clientMiddlewareManifestPath)\n writeFileAtomic(\n join(this.distDir, clientMiddlewareManifestPath),\n clientMiddlewareManifestJs\n )\n\n return {\n clientMiddlewareManifestPath,\n }\n }\n\n loadPagesManifest(pageName: string): void {\n this.pagesManifests.set(\n getEntryKey('pages', 'server', pageName),\n readPartialManifestContent(this.distDir, PAGES_MANIFEST, pageName)\n )\n }\n\n private mergePagesManifests(manifests: Iterable<PagesManifest>) {\n const manifest: PagesManifest = {}\n for (const m of manifests) {\n Object.assign(manifest, m)\n }\n return sortObjectByKey(manifest)\n }\n\n private mergeSriManifests(manifests: Iterable<SubresourceIntegrityManifest>) {\n const manifest: SubresourceIntegrityManifest = {}\n for (const m of manifests) {\n Object.assign(manifest, m)\n }\n return sortObjectByKey(manifest)\n }\n\n private writePagesManifest(): void {\n if (!this.pagesManifests.takeChanged()) {\n return\n }\n const pagesManifest = this.mergePagesManifests(this.pagesManifests.values())\n const pagesManifestPath = join(this.distDir, 'server', PAGES_MANIFEST)\n this.pendingCacheDeletes.push(pagesManifestPath)\n writeFileAtomic(pagesManifestPath, JSON.stringify(pagesManifest, null, 2))\n }\n\n writeManifests({\n devRewrites,\n productionRewrites,\n entrypoints,\n }: {\n devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined\n productionRewrites: CustomRoutes['rewrites'] | undefined\n entrypoints: Entrypoints\n }): void {\n this.writeActionManifest()\n this.writeAppPathsManifest()\n const lowPriorityFiles = this.writeClientBuildManifest(\n entrypoints,\n devRewrites,\n productionRewrites\n )\n const { clientMiddlewareManifestPath } = this.writeMiddlewareManifest()\n this.writeBuildManifest([...lowPriorityFiles, clientMiddlewareManifestPath])\n this.writeInterceptionRouteRewriteManifest(devRewrites, productionRewrites)\n this.writeNextFontManifest()\n this.writePagesManifest()\n\n this.writeSriManifest()\n\n // Flush all queued cache deletions in a single require.cache scan\n if (this.pendingCacheDeletes.length > 0) {\n deleteCache(this.pendingCacheDeletes)\n this.pendingCacheDeletes = []\n }\n }\n}\n\nfunction sortObjectByKey(obj: Record<string, any>) {\n return Object.keys(obj)\n .sort()\n .reduce(\n (acc, key) => {\n acc[key] = obj[key]\n return acc\n },\n {} as Record<string, any>\n )\n}\n"],"names":["TurbopackManifestLoader","getManifestPath","page","distDir","name","type","firstCall","manifestPath","posix","join","getAssetPathFromRoute","isSitemapRoute","test","existsSync","replace","endsWith","basePage","removeRouteSuffix","slice","length","metadataPage","addRouteSuffix","addMetadataIdToRoute","readPartialManifestContent","pageName","readFileSync","ManifestsMap","set","key","value","rawMap","get","changed","map","JSON","parse","delete","has","takeChanged","extraInvalidationKey","undefined","stringified","stringify","values","entries","Map","constructor","buildId","encryptionKey","dev","sriEnabled","actionManifests","appPathsManifests","buildManifests","clientBuildManifests","fontManifests","middlewareManifests","pagesManifests","sriManifests","cachedInterceptionRewrites","pendingCacheDeletes","loadActionManifest","getEntryKey","SERVER_REFERENCE_MANIFEST","mergeActionManifests","manifests","manifest","node","edge","mergeActionIds","actionEntries","other","action","workers","filename","exportedName","Object","assign","m","entry","sortObjectByKey","writeActionManifest","actionManifest","actionManifestJsonPath","actionManifestJsPath","json","push","writeFileAtomic","loadAppPathsManifest","APP_PATHS_MANIFEST","writeAppPathsManifest","appPathsManifest","mergePagesManifests","appPathsManifestPath","writeSriManifest","sriManifest","mergeSriManifests","pathJson","SUBRESOURCE_INTEGRITY_MANIFEST","pathJs","loadBuildManifest","BUILD_MANIFEST","loadClientBuildManifest","TURBOPACK_CLIENT_BUILD_MANIFEST","loadSriManifest","mergeBuildManifests","lowPriorityFiles","pages","devFiles","polyfillFiles","rootMainFiles","rootMainFilesTree","pagesChunkGroupBootstrapParams","chunkLoadingGlobal","mergeClientBuildManifests","rewrites","sortedPageKeys","__rewrites","sortedPages","writeInterceptionRouteRewriteManifest","devRewrites","productionRewrites","beforeFiles","processRoute","afterFiles","fallback","interceptionRewrites","filter","require","isInterceptionRouteRewrite","interceptionRewriteManifestPath","INTERCEPTION_ROUTE_REWRITE_MANIFEST","writeBuildManifest","buildManifest","buildManifestPath","middlewareBuildManifestPath","MIDDLEWARE_BUILD_MANIFEST","createEdgeRuntimeManifest","fallbackBuildManifest","Boolean","fallbackBuildManifestPath","writeClientBuildManifest","entrypoints","normalizeRewritesForBuildManifest","pagesKeys","keys","global","app","error","getSortedRoutes","CLIENT_STATIC_FILES_PATH","ssgManifestPath","clientBuildManifest","pageBootstrapParams","splitEntryKey","route","params","hasBootstrapParams","clientBuildManifestJs","srcEmptySsgManifest","loadFontManifest","NEXT_FONT_MANIFEST","mergeFontManifests","appUsingSizeAdjust","pagesUsingSizeAdjust","writeNextFontManifest","fontManifest","fontManifestJsonPath","fontManifestJsPath","loadMiddlewareManifest","middlewareManifestPath","MIDDLEWARE_MANIFEST","getMiddlewareManifest","deleteMiddlewareManifest","mergeMiddlewareManifests","version","middleware","sortedMiddleware","functions","instrumentation","updateFunctionDefinition","fun","files","concat","matcher","matchers","regexp","safePathToRegexp","originalSource","delimiter","sensitive","strict","source","replaceAll","writeMiddlewareManifest","clientMiddlewareManifestPath","TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST","middlewareManifest","forEach","startsWith","parsedPage","tryToParsePath","regexStr","Error","clientMiddlewareManifestJs","loadPagesManifest","PAGES_MANIFEST","writePagesManifest","pagesManifest","pagesManifestPath","writeManifests","deleteCache","obj","sort","reduce","acc"],"mappings":";;;;+BAoLaA;;;eAAAA;;;;2BA9JN;sBACqB;oBACC;8BAED;6BACI;gFACE;0BACwB;uBAE1B;gCAMzB;gCACwB;iCACE;0CAQ1B;AAuBP,MAAMC,kBAAkB,CACtBC,MACAC,SACAC,MACAC,MACAC;IAEA,IAAIC,eAAeC,WAAK,CAACC,IAAI,CAC3BN,SACA,CAAC,MAAM,CAAC,EACRE,MACAA,SAAS,gBAAgBA,SAAS,oBAC9B,KACAA,SAAS,QACPH,OACAQ,IAAAA,8BAAqB,EAACR,OAC5BE;IAGF,IAAIE,WAAW;QACb,MAAMK,iBAAiB,8BAA8BC,IAAI,CAACV;QAC1D,mDAAmD;QACnD,IAAIS,kBAAkB,CAACE,IAAAA,cAAU,EAACN,eAAe;YAC/CA,eAAeN,gBACbC,KAAKY,OAAO,CAAC,qBAAqB,uBAClCX,SACAC,MACAC,MACA;QAEJ;QACA,oDAAoD;QACpD,IAAI,CAACQ,IAAAA,cAAU,EAACN,iBAAiBL,KAAKa,QAAQ,CAAC,WAAW;YACxD,6IAA6I;YAC7I,IAAIC,WAAWC,IAAAA,iCAAiB,EAACf;YACj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tC;QACF;QACA,MAAM0K,gBAAgB,IAAI,CAACpH,mBAAmB,CAAC,IAAI,CAACnC,cAAc,CAACd,MAAM;QACzE,MAAMsK,oBAAoBxM,IAAAA,UAAI,EAAC,IAAI,CAACN,OAAO,EAAE,UAAU2M,yBAAc;QACrE,IAAI,CAAClJ,mBAAmB,CAAC0B,IAAI,CAAC2H;QAC9B1H,IAAAA,4BAAe,EAAC0H,mBAAmB/K,KAAKQ,SAAS,CAACsK,eAAe,MAAM;IACzE;IAEAE,eAAe,EACb1F,WAAW,EACXC,kBAAkB,EAClBqB,WAAW,EAKZ,EAAQ;QACP,IAAI,CAAC7D,mBAAmB;QACxB,IAAI,CAACS,qBAAqB;QAC1B,MAAMgB,mBAAmB,IAAI,CAACmC,wBAAwB,CACpDC,aACAtB,aACAC;QAEF,MAAM,EAAE0E,4BAA4B,EAAE,GAAG,IAAI,CAACD,uBAAuB;QACrE,IAAI,CAAC9D,kBAAkB,CAAC;eAAI1B;YAAkByF;SAA6B;QAC3E,IAAI,CAAC5E,qCAAqC,CAACC,aAAaC;QACxD,IAAI,CAAC4C,qBAAqB;QAC1B,IAAI,CAAC0C,kBAAkB;QAEvB,IAAI,CAACjH,gBAAgB;QAErB,kEAAkE;QAClE,IAAI,IAAI,CAAClC,mBAAmB,CAACzC,MAAM,GAAG,GAAG;YACvCgM,IAAAA,yBAAW,EAAC,IAAI,CAACvJ,mBAAmB;YACpC,IAAI,CAACA,mBAAmB,GAAG,EAAE;QAC/B;IACF;AACF;AAEA,SAASoB,gBAAgBoI,GAAwB;IAC/C,OAAOxI,OAAOqE,IAAI,CAACmE,KAChBC,IAAI,GACJC,MAAM,CACL,CAACC,KAAK3L;QACJ2L,GAAG,CAAC3L,IAAI,GAAGwL,GAAG,CAACxL,IAAI;QACnB,OAAO2L;IACT,GACA,CAAC;AAEP","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/shared/lib/turbopack/manifest-loader.ts"],"sourcesContent":["import type {\n EdgeFunctionDefinition,\n MiddlewareManifest,\n} from '../../../build/webpack/plugins/middleware-plugin'\nimport type { BuildManifest } from '../../../server/get-page-files'\nimport type { PagesManifest } from '../../../build/webpack/plugins/pages-manifest-plugin'\nimport type { ActionManifest } from '../../../build/webpack/plugins/flight-client-entry-plugin'\nimport type { NextFontManifest } from '../../../build/webpack/plugins/next-font-manifest-plugin'\nimport type { REACT_LOADABLE_MANIFEST } from '../constants'\nimport {\n APP_PATHS_MANIFEST,\n BUILD_MANIFEST,\n CLIENT_STATIC_FILES_PATH,\n INTERCEPTION_ROUTE_REWRITE_MANIFEST,\n MIDDLEWARE_BUILD_MANIFEST,\n MIDDLEWARE_MANIFEST,\n NEXT_FONT_MANIFEST,\n PAGES_MANIFEST,\n SERVER_REFERENCE_MANIFEST,\n SUBRESOURCE_INTEGRITY_MANIFEST,\n TURBOPACK_CLIENT_BUILD_MANIFEST,\n TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST,\n} from '../constants'\nimport { join, posix } from 'path'\nimport { readFileSync } from 'fs'\nimport type { SetupOpts } from '../../../server/lib/router-utils/setup-dev-bundler'\nimport { deleteCache } from '../../../server/dev/require-cache'\nimport { writeFileAtomic } from '../../../lib/fs/write-atomic'\nimport getAssetPathFromRoute from '../router/utils/get-asset-path-from-route'\nimport { getEntryKey, splitEntryKey, type EntryKey } from './entry-key'\nimport type { CustomRoutes } from '../../../lib/load-custom-routes'\nimport { getSortedRoutes } from '../router/utils'\nimport { existsSync } from 'fs'\nimport {\n addMetadataIdToRoute,\n addRouteSuffix,\n removeRouteSuffix,\n} from '../../../server/dev/turbopack-utils'\nimport { tryToParsePath } from '../../../lib/try-to-parse-path'\nimport { safePathToRegexp } from '../router/utils/route-match-utils'\nimport type { Entrypoints } from '../../../build/swc/types'\nimport {\n normalizeRewritesForBuildManifest,\n type ClientBuildManifest,\n srcEmptySsgManifest,\n processRoute,\n createEdgeRuntimeManifest,\n} from '../../../build/webpack/plugins/build-manifest-plugin-utils'\nimport type { SubresourceIntegrityManifest } from '../../../build'\n\ninterface InstrumentationDefinition {\n files: string[]\n name: 'instrumentation'\n}\n\ntype TurbopackMiddlewareManifest = MiddlewareManifest & {\n instrumentation?: InstrumentationDefinition\n}\n\ntype ManifestName =\n | typeof MIDDLEWARE_MANIFEST\n | typeof BUILD_MANIFEST\n | typeof PAGES_MANIFEST\n | typeof APP_PATHS_MANIFEST\n | `${typeof SERVER_REFERENCE_MANIFEST}.json`\n | `${typeof SUBRESOURCE_INTEGRITY_MANIFEST}.json`\n | `${typeof NEXT_FONT_MANIFEST}.json`\n | typeof REACT_LOADABLE_MANIFEST\n | typeof TURBOPACK_CLIENT_BUILD_MANIFEST\n\nconst getManifestPath = (\n page: string,\n distDir: string,\n name: ManifestName,\n type: string,\n firstCall: boolean\n) => {\n let manifestPath = posix.join(\n distDir,\n `server`,\n type,\n type === 'middleware' || type === 'instrumentation'\n ? ''\n : type === 'app'\n ? page\n : getAssetPathFromRoute(page),\n name\n )\n\n if (firstCall) {\n const isSitemapRoute = /[\\\\/]sitemap(.xml)?\\/route$/.test(page)\n // Check the ambiguity of /sitemap and /sitemap.xml\n if (isSitemapRoute && !existsSync(manifestPath)) {\n manifestPath = getManifestPath(\n page.replace(/\\/sitemap\\/route$/, '/sitemap.xml/route'),\n distDir,\n name,\n type,\n false\n )\n }\n // existsSync is faster than using the async version\n if (!existsSync(manifestPath) && page.endsWith('/route')) {\n // TODO: Improve implementation of metadata routes, currently it requires this extra check for the variants of the files that can be written.\n let basePage = removeRouteSuffix(page)\n // For sitemap.xml routes with generateSitemaps, the manifest is at\n // /sitemap/[__metadata_id__]/route (without .xml), because the route\n // handler serves at /sitemap/[id] not /sitemap.xml/[id]\n if (basePage.endsWith('/sitemap.xml')) {\n basePage = basePage.slice(0, -'.xml'.length)\n }\n let metadataPage = addRouteSuffix(addMetadataIdToRoute(basePage))\n manifestPath = getManifestPath(metadataPage, distDir, name, type, false)\n }\n }\n\n return manifestPath\n}\n\nfunction readPartialManifestContent(\n distDir: string,\n name: ManifestName,\n pageName: string,\n type: 'pages' | 'app' | 'middleware' | 'instrumentation' = 'pages'\n): string {\n const page = pageName\n const manifestPath = getManifestPath(page, distDir, name, type, true)\n return readFileSync(posix.join(manifestPath), 'utf-8')\n}\n\n/// Helper class that stores a map of manifests and tracks if they have changed\n/// since the last time they were written to disk. This is used to avoid\n/// unnecessary writes to disk.\nclass ManifestsMap<K, V> {\n private rawMap = new Map<K, string>()\n private map = new Map<K, V>()\n private extraInvalidationKey: string | undefined = undefined\n private changed = true\n\n set(key: K, value: string) {\n if (this.rawMap.get(key) === value) return\n this.changed = true\n this.rawMap.set(key, value)\n this.map.set(key, JSON.parse(value))\n }\n\n delete(key: K) {\n if (this.map.has(key)) {\n this.changed = true\n this.rawMap.delete(key)\n this.map.delete(key)\n }\n }\n\n get(key: K) {\n return this.map.get(key)\n }\n\n takeChanged(extraInvalidationKey?: any) {\n let changed = this.changed\n if (extraInvalidationKey !== undefined) {\n const stringified = JSON.stringify(extraInvalidationKey)\n if (this.extraInvalidationKey !== stringified) {\n this.extraInvalidationKey = stringified\n changed = true\n }\n }\n this.changed = false\n return changed\n }\n\n values() {\n return this.map.values()\n }\n\n entries() {\n return this.map.entries()\n }\n}\n\nexport class TurbopackManifestLoader {\n private actionManifests: ManifestsMap<EntryKey, ActionManifest> =\n new ManifestsMap()\n private appPathsManifests: ManifestsMap<EntryKey, PagesManifest> =\n new ManifestsMap()\n private buildManifests: ManifestsMap<EntryKey, BuildManifest> =\n new ManifestsMap()\n private clientBuildManifests: ManifestsMap<EntryKey, ClientBuildManifest> =\n new ManifestsMap()\n private fontManifests: ManifestsMap<EntryKey, NextFontManifest> =\n new ManifestsMap()\n private middlewareManifests: ManifestsMap<\n EntryKey,\n TurbopackMiddlewareManifest\n > = new ManifestsMap()\n private pagesManifests: ManifestsMap<string, PagesManifest> =\n new ManifestsMap()\n private sriManifests: ManifestsMap<EntryKey, SubresourceIntegrityManifest> =\n new ManifestsMap()\n private encryptionKey: string\n /// interceptionRewrites that have been written to disk\n /// This is used to avoid unnecessary writes if the rewrites haven't changed\n private cachedInterceptionRewrites: string | undefined = undefined\n private pendingCacheDeletes: string[] = []\n\n private readonly distDir: string\n private readonly buildId: string\n private readonly dev: boolean\n private readonly sriEnabled: boolean\n\n constructor({\n distDir,\n buildId,\n encryptionKey,\n dev,\n sriEnabled,\n }: {\n buildId: string\n distDir: string\n encryptionKey: string\n dev: boolean\n sriEnabled: boolean\n }) {\n this.distDir = distDir\n this.buildId = buildId\n this.encryptionKey = encryptionKey\n this.dev = dev\n this.sriEnabled = sriEnabled\n }\n\n delete(key: EntryKey) {\n this.actionManifests.delete(key)\n this.appPathsManifests.delete(key)\n this.buildManifests.delete(key)\n this.clientBuildManifests.delete(key)\n this.fontManifests.delete(key)\n this.middlewareManifests.delete(key)\n this.pagesManifests.delete(key)\n }\n\n loadActionManifest(pageName: string): void {\n this.actionManifests.set(\n getEntryKey('app', 'server', pageName),\n readPartialManifestContent(\n this.distDir,\n `${SERVER_REFERENCE_MANIFEST}.json`,\n pageName,\n 'app'\n )\n )\n }\n\n private mergeActionManifests(manifests: Iterable<ActionManifest>) {\n type ActionEntries = ActionManifest['edge' | 'node']\n const manifest: ActionManifest = {\n node: {},\n edge: {},\n encryptionKey: this.encryptionKey,\n }\n\n function mergeActionIds(\n actionEntries: ActionEntries,\n other: ActionEntries\n ): void {\n for (const key in other) {\n const action = (actionEntries[key] ??= {\n workers: {},\n })\n action.filename = other[key].filename\n action.exportedName = other[key].exportedName\n Object.assign(action.workers, other[key].workers)\n }\n }\n\n for (const m of manifests) {\n mergeActionIds(manifest.node, m.node)\n mergeActionIds(manifest.edge, m.edge)\n }\n for (const key in manifest.node) {\n const entry = manifest.node[key]\n entry.workers = sortObjectByKey(entry.workers)\n }\n for (const key in manifest.edge) {\n const entry = manifest.edge[key]\n entry.workers = sortObjectByKey(entry.workers)\n }\n\n return manifest\n }\n\n private writeActionManifest(): void {\n if (!this.actionManifests.takeChanged()) {\n return\n }\n const actionManifest = this.mergeActionManifests(\n this.actionManifests.values()\n )\n const actionManifestJsonPath = join(\n this.distDir,\n 'server',\n `${SERVER_REFERENCE_MANIFEST}.json`\n )\n const actionManifestJsPath = join(\n this.distDir,\n 'server',\n `${SERVER_REFERENCE_MANIFEST}.js`\n )\n const json = JSON.stringify(actionManifest, null, 2)\n this.pendingCacheDeletes.push(actionManifestJsonPath)\n this.pendingCacheDeletes.push(actionManifestJsPath)\n writeFileAtomic(actionManifestJsonPath, json)\n writeFileAtomic(\n actionManifestJsPath,\n `self.__RSC_SERVER_MANIFEST=${JSON.stringify(json)}`\n )\n }\n\n loadAppPathsManifest(pageName: string): void {\n this.appPathsManifests.set(\n getEntryKey('app', 'server', pageName),\n readPartialManifestContent(\n this.distDir,\n APP_PATHS_MANIFEST,\n pageName,\n 'app'\n )\n )\n }\n\n private writeAppPathsManifest(): void {\n if (!this.appPathsManifests.takeChanged()) {\n return\n }\n const appPathsManifest = this.mergePagesManifests(\n this.appPathsManifests.values()\n )\n const appPathsManifestPath = join(\n this.distDir,\n 'server',\n APP_PATHS_MANIFEST\n )\n this.pendingCacheDeletes.push(appPathsManifestPath)\n writeFileAtomic(\n appPathsManifestPath,\n JSON.stringify(appPathsManifest, null, 2)\n )\n }\n\n private writeSriManifest(): void {\n if (!this.sriEnabled || !this.sriManifests.takeChanged()) {\n return\n }\n const sriManifest = this.mergeSriManifests(this.sriManifests.values())\n const pathJson = join(\n this.distDir,\n 'server',\n `${SUBRESOURCE_INTEGRITY_MANIFEST}.json`\n )\n const pathJs = join(\n this.distDir,\n 'server',\n `${SUBRESOURCE_INTEGRITY_MANIFEST}.js`\n )\n this.pendingCacheDeletes.push(pathJson)\n this.pendingCacheDeletes.push(pathJs)\n writeFileAtomic(pathJson, JSON.stringify(sriManifest, null, 2))\n writeFileAtomic(\n pathJs,\n `self.__SUBRESOURCE_INTEGRITY_MANIFEST=${JSON.stringify(\n JSON.stringify(sriManifest)\n )}`\n )\n }\n\n loadBuildManifest(pageName: string, type: 'app' | 'pages' = 'pages'): void {\n this.buildManifests.set(\n getEntryKey(type, 'server', pageName),\n readPartialManifestContent(this.distDir, BUILD_MANIFEST, pageName, type)\n )\n }\n\n loadClientBuildManifest(\n pageName: string,\n type: 'app' | 'pages' = 'pages'\n ): void {\n this.clientBuildManifests.set(\n getEntryKey(type, 'server', pageName),\n readPartialManifestContent(\n this.distDir,\n TURBOPACK_CLIENT_BUILD_MANIFEST,\n pageName,\n type\n )\n )\n }\n\n loadSriManifest(pageName: string, type: 'app' | 'pages' = 'pages'): void {\n if (!this.sriEnabled) return\n this.sriManifests.set(\n getEntryKey(type, 'client', pageName),\n readPartialManifestContent(\n this.distDir,\n `${SUBRESOURCE_INTEGRITY_MANIFEST}.json`,\n pageName,\n type\n )\n )\n }\n\n private mergeBuildManifests(\n manifests: Iterable<BuildManifest>,\n lowPriorityFiles: string[]\n ) {\n const manifest: Partial<BuildManifest> & Pick<BuildManifest, 'pages'> = {\n pages: {\n '/_app': [],\n },\n // Something in next.js depends on these to exist even for app dir rendering\n devFiles: [],\n polyfillFiles: [],\n lowPriorityFiles,\n rootMainFiles: [],\n rootMainFilesTree: {},\n pagesChunkGroupBootstrapParams: {},\n }\n for (const m of manifests) {\n Object.assign(manifest.pages, m.pages)\n if (m.rootMainFiles.length) manifest.rootMainFiles = m.rootMainFiles\n // polyfillFiles should always be the same, so we can overwrite instead of actually merging\n if (m.polyfillFiles.length) manifest.polyfillFiles = m.polyfillFiles\n if (m.rootMainFilesTree) {\n Object.assign(manifest.rootMainFilesTree!, m.rootMainFilesTree)\n }\n if (m.pagesChunkGroupBootstrapParams) {\n Object.assign(\n manifest.pagesChunkGroupBootstrapParams!,\n m.pagesChunkGroupBootstrapParams\n )\n }\n if (m.chunkLoadingGlobal)\n manifest.chunkLoadingGlobal = m.chunkLoadingGlobal\n }\n manifest.pages = sortObjectByKey(manifest.pages) as BuildManifest['pages']\n return manifest\n }\n\n private mergeClientBuildManifests(\n manifests: Iterable<ClientBuildManifest>,\n rewrites: CustomRoutes['rewrites'],\n sortedPageKeys: string[]\n ): ClientBuildManifest {\n const manifest = {\n __rewrites: rewrites as any,\n sortedPages: sortedPageKeys,\n }\n for (const m of manifests) {\n Object.assign(manifest, m)\n }\n return sortObjectByKey(manifest)\n }\n\n private writeInterceptionRouteRewriteManifest(\n devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined,\n productionRewrites: CustomRoutes['rewrites'] | undefined\n ): void {\n const rewrites = productionRewrites ?? {\n ...devRewrites,\n beforeFiles: (devRewrites?.beforeFiles ?? []).map(processRoute),\n afterFiles: (devRewrites?.afterFiles ?? []).map(processRoute),\n fallback: (devRewrites?.fallback ?? []).map(processRoute),\n }\n\n const interceptionRewrites = JSON.stringify(\n rewrites.beforeFiles.filter(\n (\n require('../../../lib/is-interception-route-rewrite') as typeof import('../../../lib/is-interception-route-rewrite')\n ).isInterceptionRouteRewrite\n )\n )\n\n if (this.cachedInterceptionRewrites === interceptionRewrites) {\n return\n }\n this.cachedInterceptionRewrites = interceptionRewrites\n\n const interceptionRewriteManifestPath = join(\n this.distDir,\n 'server',\n `${INTERCEPTION_ROUTE_REWRITE_MANIFEST}.js`\n )\n this.pendingCacheDeletes.push(interceptionRewriteManifestPath)\n\n writeFileAtomic(\n interceptionRewriteManifestPath,\n `self.__INTERCEPTION_ROUTE_REWRITE_MANIFEST=${JSON.stringify(\n interceptionRewrites\n )};`\n )\n }\n\n private writeBuildManifest(lowPriorityFiles: string[]): void {\n if (!this.buildManifests.takeChanged()) {\n return\n }\n const buildManifest = this.mergeBuildManifests(\n this.buildManifests.values(),\n lowPriorityFiles\n )\n\n const buildManifestPath = join(this.distDir, BUILD_MANIFEST)\n const middlewareBuildManifestPath = join(\n this.distDir,\n 'server',\n `${MIDDLEWARE_BUILD_MANIFEST}.js`\n )\n\n this.pendingCacheDeletes.push(buildManifestPath)\n this.pendingCacheDeletes.push(middlewareBuildManifestPath)\n writeFileAtomic(buildManifestPath, JSON.stringify(buildManifest, null, 2))\n writeFileAtomic(\n middlewareBuildManifestPath,\n createEdgeRuntimeManifest(buildManifest)\n )\n\n // Write fallback build manifest\n const fallbackBuildManifest = this.mergeBuildManifests(\n [\n this.buildManifests.get(getEntryKey('pages', 'server', '_app')),\n this.buildManifests.get(getEntryKey('pages', 'server', '_error')),\n ].filter(Boolean) as BuildManifest[],\n lowPriorityFiles\n )\n const fallbackBuildManifestPath = join(\n this.distDir,\n `fallback-${BUILD_MANIFEST}`\n )\n this.pendingCacheDeletes.push(fallbackBuildManifestPath)\n writeFileAtomic(\n fallbackBuildManifestPath,\n JSON.stringify(fallbackBuildManifest, null, 2)\n )\n }\n\n private writeClientBuildManifest(\n entrypoints: Entrypoints,\n devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined,\n productionRewrites: CustomRoutes['rewrites'] | undefined\n ): string[] {\n const rewrites = normalizeRewritesForBuildManifest(\n productionRewrites ?? {\n ...devRewrites,\n beforeFiles: (devRewrites?.beforeFiles ?? []).map(processRoute),\n afterFiles: (devRewrites?.afterFiles ?? []).map(processRoute),\n fallback: (devRewrites?.fallback ?? []).map(processRoute),\n }\n )\n\n const pagesKeys = [...entrypoints.page.keys()]\n if (entrypoints.global.app) {\n pagesKeys.push('/_app')\n }\n if (entrypoints.global.error) {\n pagesKeys.push('/_error')\n }\n\n const sortedPageKeys = getSortedRoutes(pagesKeys)\n\n let buildManifestPath = posix.join(\n CLIENT_STATIC_FILES_PATH,\n this.buildId,\n '_buildManifest.js'\n )\n let ssgManifestPath = posix.join(\n CLIENT_STATIC_FILES_PATH,\n this.buildId,\n '_ssgManifest.js'\n )\n\n if (\n this.dev &&\n !this.clientBuildManifests.takeChanged({ rewrites, sortedPageKeys })\n ) {\n return [buildManifestPath, ssgManifestPath]\n }\n\n const clientBuildManifest = this.mergeClientBuildManifests(\n this.clientBuildManifests.values(),\n rewrites,\n sortedPageKeys\n )\n\n // Expose each route's bootstrap params and the chunk-loading global to the client\n // so `route-loader` can instantiate a navigated page's entry module. The server\n // stores params as raw JSON per route.\n const pageBootstrapParams: Record<string, unknown> = {}\n let chunkLoadingGlobal: string | undefined\n for (const [key, m] of this.buildManifests.entries()) {\n // Only the pages-router `route-loader` reads `__TURBOPACK_PAGE_BOOTSTRAP`. App routes\n // navigate via flight and never use it, so skip app entries to keep `_buildManifest.js`\n // (loaded on every page) small.\n if (splitEntryKey(key).type !== 'pages') continue\n if (m.chunkLoadingGlobal) chunkLoadingGlobal = m.chunkLoadingGlobal\n for (const [route, params] of Object.entries(\n m.pagesChunkGroupBootstrapParams ?? {}\n )) {\n pageBootstrapParams[route] = params\n }\n }\n\n // Only emit the bootstrap globals when a route actually inlined its bootstrap (shared runtime\n // enabled).\n const hasBootstrapParams = Object.keys(pageBootstrapParams).length > 0\n const clientBuildManifestJs =\n `self.__BUILD_MANIFEST = ${JSON.stringify(clientBuildManifest, null, 2)};` +\n (hasBootstrapParams\n ? `self.__TURBOPACK_PAGE_BOOTSTRAP = ${JSON.stringify(pageBootstrapParams)};` +\n (chunkLoadingGlobal\n ? `self.__TURBOPACK_CHUNK_LOADING_GLOBAL = ${JSON.stringify(\n chunkLoadingGlobal\n )};`\n : '')\n : '') +\n `self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()`\n\n writeFileAtomic(\n join(this.distDir, buildManifestPath),\n clientBuildManifestJs\n )\n // This is just an empty placeholder, the actual manifest is written after prerendering in\n // packages/next/src/build/index.ts\n writeFileAtomic(join(this.distDir, ssgManifestPath), srcEmptySsgManifest)\n\n return [buildManifestPath, ssgManifestPath]\n }\n\n loadFontManifest(pageName: string, type: 'app' | 'pages' = 'pages'): void {\n this.fontManifests.set(\n getEntryKey(type, 'server', pageName),\n readPartialManifestContent(\n this.distDir,\n `${NEXT_FONT_MANIFEST}.json`,\n pageName,\n type\n )\n )\n }\n\n private mergeFontManifests(manifests: Iterable<NextFontManifest>) {\n const manifest: NextFontManifest = {\n app: {},\n appUsingSizeAdjust: false,\n pages: {},\n pagesUsingSizeAdjust: false,\n }\n for (const m of manifests) {\n Object.assign(manifest.app, m.app)\n Object.assign(manifest.pages, m.pages)\n\n manifest.appUsingSizeAdjust =\n manifest.appUsingSizeAdjust || m.appUsingSizeAdjust\n manifest.pagesUsingSizeAdjust =\n manifest.pagesUsingSizeAdjust || m.pagesUsingSizeAdjust\n }\n manifest.app = sortObjectByKey(manifest.app)\n manifest.pages = sortObjectByKey(manifest.pages)\n return manifest\n }\n\n private async writeNextFontManifest(): Promise<void> {\n if (!this.fontManifests.takeChanged()) {\n return\n }\n const fontManifest = this.mergeFontManifests(this.fontManifests.values())\n const json = JSON.stringify(fontManifest, null, 2)\n\n const fontManifestJsonPath = join(\n this.distDir,\n 'server',\n `${NEXT_FONT_MANIFEST}.json`\n )\n const fontManifestJsPath = join(\n this.distDir,\n 'server',\n `${NEXT_FONT_MANIFEST}.js`\n )\n this.pendingCacheDeletes.push(fontManifestJsonPath)\n this.pendingCacheDeletes.push(fontManifestJsPath)\n writeFileAtomic(fontManifestJsonPath, json)\n writeFileAtomic(\n fontManifestJsPath,\n `self.__NEXT_FONT_MANIFEST=${JSON.stringify(json)}`\n )\n }\n\n /**\n * @returns If the manifest was written or not\n */\n loadMiddlewareManifest(\n pageName: string,\n type: 'pages' | 'app' | 'middleware' | 'instrumentation'\n ): boolean {\n const middlewareManifestPath = getManifestPath(\n pageName,\n this.distDir,\n MIDDLEWARE_MANIFEST,\n type,\n true\n )\n\n // middlewareManifest is actually \"edge manifest\" and not all routes are edge runtime. If it is not written we skip it.\n if (!existsSync(middlewareManifestPath)) {\n return false\n }\n\n this.middlewareManifests.set(\n getEntryKey(\n type === 'middleware' || type === 'instrumentation' ? 'root' : type,\n 'server',\n pageName\n ),\n readPartialManifestContent(\n this.distDir,\n MIDDLEWARE_MANIFEST,\n pageName,\n type\n )\n )\n\n return true\n }\n\n getMiddlewareManifest(key: EntryKey) {\n return this.middlewareManifests.get(key)\n }\n\n deleteMiddlewareManifest(key: EntryKey) {\n return this.middlewareManifests.delete(key)\n }\n\n private mergeMiddlewareManifests(\n manifests: Iterable<TurbopackMiddlewareManifest>\n ): MiddlewareManifest {\n const manifest: MiddlewareManifest = {\n version: 3,\n middleware: {},\n sortedMiddleware: [],\n functions: {},\n }\n let instrumentation: InstrumentationDefinition | undefined = undefined\n for (const m of manifests) {\n Object.assign(manifest.functions, m.functions)\n Object.assign(manifest.middleware, m.middleware)\n if (m.instrumentation) {\n instrumentation = m.instrumentation\n }\n }\n manifest.functions = sortObjectByKey(manifest.functions)\n manifest.middleware = sortObjectByKey(manifest.middleware)\n const updateFunctionDefinition = (\n fun: EdgeFunctionDefinition\n ): EdgeFunctionDefinition => {\n return {\n ...fun,\n files: [...(instrumentation?.files ?? []), ...fun.files],\n }\n }\n for (const key of Object.keys(manifest.middleware)) {\n const value = manifest.middleware[key]\n manifest.middleware[key] = updateFunctionDefinition(value)\n }\n for (const key of Object.keys(manifest.functions)) {\n const value = manifest.functions[key]\n manifest.functions[key] = updateFunctionDefinition(value)\n }\n for (const fun of Object.values(manifest.functions).concat(\n Object.values(manifest.middleware)\n )) {\n for (const matcher of fun.matchers) {\n if (!matcher.regexp) {\n matcher.regexp = safePathToRegexp(matcher.originalSource, [], {\n delimiter: '/',\n sensitive: false,\n strict: true,\n }).source.replaceAll('\\\\/', '/')\n }\n }\n }\n manifest.sortedMiddleware = Object.keys(manifest.middleware)\n\n return manifest\n }\n\n private writeMiddlewareManifest(): {\n clientMiddlewareManifestPath: string\n } {\n let clientMiddlewareManifestPath = posix.join(\n CLIENT_STATIC_FILES_PATH,\n this.buildId,\n TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST\n )\n\n if (this.dev && !this.middlewareManifests.takeChanged()) {\n return {\n clientMiddlewareManifestPath,\n }\n }\n const middlewareManifest = this.mergeMiddlewareManifests(\n this.middlewareManifests.values()\n )\n\n // Server middleware manifest\n\n // Normalize regexes as it uses path-to-regexp\n for (const key in middlewareManifest.middleware) {\n middlewareManifest.middleware[key].matchers.forEach((matcher) => {\n if (!matcher.regexp.startsWith('^')) {\n const parsedPage = tryToParsePath(matcher.regexp)\n if (parsedPage.error || !parsedPage.regexStr) {\n throw new Error(`Invalid source: ${matcher.regexp}`)\n }\n matcher.regexp = parsedPage.regexStr\n }\n })\n }\n\n const middlewareManifestPath = join(\n this.distDir,\n 'server',\n MIDDLEWARE_MANIFEST\n )\n this.pendingCacheDeletes.push(middlewareManifestPath)\n writeFileAtomic(\n middlewareManifestPath,\n JSON.stringify(middlewareManifest, null, 2)\n )\n\n // Client middleware manifest This is only used in dev though, packages/next/src/build/index.ts\n // writes the manifest again for builds.\n const matchers = middlewareManifest?.middleware['/']?.matchers || []\n\n const clientMiddlewareManifestJs = `self.__MIDDLEWARE_MATCHERS = ${JSON.stringify(\n matchers,\n null,\n 2\n )};self.__MIDDLEWARE_MATCHERS_CB && self.__MIDDLEWARE_MATCHERS_CB()`\n\n this.pendingCacheDeletes.push(clientMiddlewareManifestPath)\n writeFileAtomic(\n join(this.distDir, clientMiddlewareManifestPath),\n clientMiddlewareManifestJs\n )\n\n return {\n clientMiddlewareManifestPath,\n }\n }\n\n loadPagesManifest(pageName: string): void {\n this.pagesManifests.set(\n getEntryKey('pages', 'server', pageName),\n readPartialManifestContent(this.distDir, PAGES_MANIFEST, pageName)\n )\n }\n\n private mergePagesManifests(manifests: Iterable<PagesManifest>) {\n const manifest: PagesManifest = {}\n for (const m of manifests) {\n Object.assign(manifest, m)\n }\n return sortObjectByKey(manifest)\n }\n\n private mergeSriManifests(manifests: Iterable<SubresourceIntegrityManifest>) {\n const manifest: SubresourceIntegrityManifest = {}\n for (const m of manifests) {\n Object.assign(manifest, m)\n }\n return sortObjectByKey(manifest)\n }\n\n private writePagesManifest(): void {\n if (!this.pagesManifests.takeChanged()) {\n return\n }\n const pagesManifest = this.mergePagesManifests(this.pagesManifests.values())\n const pagesManifestPath = join(this.distDir, 'server', PAGES_MANIFEST)\n this.pendingCacheDeletes.push(pagesManifestPath)\n writeFileAtomic(pagesManifestPath, JSON.stringify(pagesManifest, null, 2))\n }\n\n writeManifests({\n devRewrites,\n productionRewrites,\n entrypoints,\n }: {\n devRewrites: SetupOpts['fsChecker']['rewrites'] | undefined\n productionRewrites: CustomRoutes['rewrites'] | undefined\n entrypoints: Entrypoints\n }): void {\n this.writeActionManifest()\n this.writeAppPathsManifest()\n const lowPriorityFiles = this.writeClientBuildManifest(\n entrypoints,\n devRewrites,\n productionRewrites\n )\n const { clientMiddlewareManifestPath } = this.writeMiddlewareManifest()\n this.writeBuildManifest([...lowPriorityFiles, clientMiddlewareManifestPath])\n this.writeInterceptionRouteRewriteManifest(devRewrites, productionRewrites)\n this.writeNextFontManifest()\n this.writePagesManifest()\n\n this.writeSriManifest()\n\n // Flush all queued cache deletions in a single require.cache scan\n if (this.pendingCacheDeletes.length > 0) {\n deleteCache(this.pendingCacheDeletes)\n this.pendingCacheDeletes = []\n }\n }\n}\n\nfunction sortObjectByKey(obj: Record<string, any>) {\n return Object.keys(obj)\n .sort()\n .reduce(\n (acc, key) => {\n acc[key] = obj[key]\n return acc\n },\n {} as Record<string, any>\n )\n}\n"],"names":["TurbopackManifestLoader","getManifestPath","page","distDir","name","type","firstCall","manifestPath","posix","join","getAssetPathFromRoute","isSitemapRoute","test","existsSync","replace","endsWith","basePage","removeRouteSuffix","slice","length","metadataPage","addRouteSuffix","addMetadataIdToRoute","readPartialManifestContent","pageName","readFileSync","ManifestsMap","set","key","value","rawMap","get","changed","map","JSON","parse","delete","has","takeChanged","extraInvalidationKey","undefined","stringified","stringify","values","entries","Map","constructor","buildId","encryptionKey","dev","sriEnabled","actionManifests","appPathsManifests","buildManifests","clientBuildManifests","fontManifests","middlewareManifests","pagesManifests","sriManifests","cachedInterceptionRewrites","pendingCacheDeletes","loadActionManifest","getEntryKey","SERVER_REFERENCE_MANIFEST","mergeActionManifests","manifests","manifest","node","edge","mergeActionIds","actionEntries","other","action","workers","filename","exportedName","Object","assign","m","entry","sortObjectByKey","writeActionManifest","actionManifest","actionManifestJsonPath","actionManifestJsPath","json","push","writeFileAtomic","loadAppPathsManifest","APP_PATHS_MANIFEST","writeAppPathsManifest","appPathsManifest","mergePagesManifests","appPathsManifestPath","writeSriManifest","sriManifest","mergeSriManifests","pathJson","SUBRESOURCE_INTEGRITY_MANIFEST","pathJs","loadBuildManifest","BUILD_MANIFEST","loadClientBuildManifest","TURBOPACK_CLIENT_BUILD_MANIFEST","loadSriManifest","mergeBuildManifests","lowPriorityFiles","pages","devFiles","polyfillFiles","rootMainFiles","rootMainFilesTree","pagesChunkGroupBootstrapParams","chunkLoadingGlobal","mergeClientBuildManifests","rewrites","sortedPageKeys","__rewrites","sortedPages","writeInterceptionRouteRewriteManifest","devRewrites","productionRewrites","beforeFiles","processRoute","afterFiles","fallback","interceptionRewrites","filter","require","isInterceptionRouteRewrite","interceptionRewriteManifestPath","INTERCEPTION_ROUTE_REWRITE_MANIFEST","writeBuildManifest","buildManifest","buildManifestPath","middlewareBuildManifestPath","MIDDLEWARE_BUILD_MANIFEST","createEdgeRuntimeManifest","fallbackBuildManifest","Boolean","fallbackBuildManifestPath","writeClientBuildManifest","entrypoints","normalizeRewritesForBuildManifest","pagesKeys","keys","global","app","error","getSortedRoutes","CLIENT_STATIC_FILES_PATH","ssgManifestPath","clientBuildManifest","pageBootstrapParams","splitEntryKey","route","params","hasBootstrapParams","clientBuildManifestJs","srcEmptySsgManifest","loadFontManifest","NEXT_FONT_MANIFEST","mergeFontManifests","appUsingSizeAdjust","pagesUsingSizeAdjust","writeNextFontManifest","fontManifest","fontManifestJsonPath","fontManifestJsPath","loadMiddlewareManifest","middlewareManifestPath","MIDDLEWARE_MANIFEST","getMiddlewareManifest","deleteMiddlewareManifest","mergeMiddlewareManifests","version","middleware","sortedMiddleware","functions","instrumentation","updateFunctionDefinition","fun","files","concat","matcher","matchers","regexp","safePathToRegexp","originalSource","delimiter","sensitive","strict","source","replaceAll","writeMiddlewareManifest","clientMiddlewareManifestPath","TURBOPACK_CLIENT_MIDDLEWARE_MANIFEST","middlewareManifest","forEach","startsWith","parsedPage","tryToParsePath","regexStr","Error","clientMiddlewareManifestJs","loadPagesManifest","PAGES_MANIFEST","writePagesManifest","pagesManifest","pagesManifestPath","writeManifests","deleteCache","obj","sort","reduce","acc"],"mappings":";;;;+BAoLaA;;;eAAAA;;;;2BA9JN;sBACqB;oBACC;8BAED;6BACI;gFACE;0BACwB;uBAE1B;gCAMzB;gCACwB;iCACE;0CAQ1B;AAuBP,MAAMC,kBAAkB,CACtBC,MACAC,SACAC,MACAC,MACAC;IAEA,IAAIC,eAAeC,WAAK,CAACC,IAAI,CAC3BN,SACA,CAAC,MAAM,CAAC,EACRE,MACAA,SAAS,gBAAgBA,SAAS,oBAC9B,KACAA,SAAS,QACPH,OACAQ,IAAAA,8BAAqB,EAACR,OAC5BE;IAGF,IAAIE,WAAW;QACb,MAAMK,iBAAiB,8BAA8BC,IAAI,CAACV;QAC1D,mDAAmD;QACnD,IAAIS,kBAAkB,CAACE,IAAAA,cAAU,EAACN,eAAe;YAC/CA,eAAeN,gBACbC,KAAKY,OAAO,CAAC,qBAAqB,uBAClCX,SACAC,MACAC,MACA;QAEJ;QACA,oDAAoD;QACpD,IAAI,CAACQ,IAAAA,cAAU,EAACN,iBAAiBL,KAAKa,QAAQ,CAAC,WAAW;YACxD,6IAA6I;YAC7I,IAAIC,WAAWC,IAAAA,iCAAiB,EAACf;YACjC,mEAAmE;YACnE,qEAAqE;YACrE,wDAAwD;YACxD,IAAIc,SAASD,QAAQ,CAAC,iBAAiB;gBACrCC,WAAWA,SAASE,KAAK,CAAC,GAAG,CAAC,OAAOC,MAAM;YAC7C;YACA,IAAIC,eAAeC,IAAAA,8BAAc,EAACC,IAAAA,oCAAoB,EAACN;YACvDT,eAAeN,gBAAgBmB,cAAcjB,SAASC,MAAMC,MAAM;QACpE;IACF;IAEA,OAAOE;AACT;AAEA,SAASgB,2BACPpB,OAAe,EACfC,IAAkB,EAClBoB,QAAgB,EAChBnB,OAA2D,OAAO;IAElE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AQ;QACP,IAAI,CAAC7D,mBAAmB;QACxB,IAAI,CAACS,qBAAqB;QAC1B,MAAMgB,mBAAmB,IAAI,CAACmC,wBAAwB,CACpDC,aACAtB,aACAC;QAEF,MAAM,EAAE0E,4BAA4B,EAAE,GAAG,IAAI,CAACD,uBAAuB;QACrE,IAAI,CAAC9D,kBAAkB,CAAC;eAAI1B;YAAkByF;SAA6B;QAC3E,IAAI,CAAC5E,qCAAqC,CAACC,aAAaC;QACxD,IAAI,CAAC4C,qBAAqB;QAC1B,IAAI,CAAC0C,kBAAkB;QAEvB,IAAI,CAACjH,gBAAgB;QAErB,kEAAkE;QAClE,IAAI,IAAI,CAAClC,mBAAmB,CAACzC,MAAM,GAAG,GAAG;YACvCgM,IAAAA,yBAAW,EAAC,IAAI,CAACvJ,mBAAmB;YACpC,IAAI,CAACA,mBAAmB,GAAG,EAAE;QAC/B;IACF;AACF;AAEA,SAASoB,gBAAgBoI,GAAwB;IAC/C,OAAOxI,OAAOqE,IAAI,CAACmE,KAChBC,IAAI,GACJC,MAAM,CACL,CAACC,KAAK3L;QACJ2L,GAAG,CAAC3L,IAAI,GAAGwL,GAAG,CAACxL,IAAI;QACnB,OAAO2L;IACT,GACA,CAAC;AAEP","ignoreList":[0]} |
@@ -85,3 +85,3 @@ "use strict"; | ||
| ciName: _ciinfo.isCI && _ciinfo.name || null, | ||
| nextVersion: "16.3.1-canary.10", | ||
| nextVersion: "16.3.1-canary.11", | ||
| agentName: await (0, _agentname.getAgentName)() | ||
@@ -88,0 +88,0 @@ }; |
@@ -14,7 +14,7 @@ "use strict"; | ||
| // This should be an invariant, if it fails our build tooling is broken. | ||
| if (typeof "16.3.1-canary.10" !== 'string') { | ||
| if (typeof "16.3.1-canary.11" !== 'string') { | ||
| return []; | ||
| } | ||
| const payload = { | ||
| nextVersion: "16.3.1-canary.10", | ||
| nextVersion: "16.3.1-canary.11", | ||
| nodeVersion: process.version, | ||
@@ -21,0 +21,0 @@ cliCommand: event.cliCommand, |
@@ -41,3 +41,3 @@ "use strict"; | ||
| payload: { | ||
| nextVersion: "16.3.1-canary.10", | ||
| nextVersion: "16.3.1-canary.11", | ||
| glibcVersion, | ||
@@ -44,0 +44,0 @@ installedSwcPackages, |
@@ -15,3 +15,3 @@ "use strict"; | ||
| // This should be an invariant, if it fails our build tooling is broken. | ||
| if (typeof "16.3.1-canary.10" !== 'string') { | ||
| if (typeof "16.3.1-canary.11" !== 'string') { | ||
| return []; | ||
@@ -21,3 +21,3 @@ } | ||
| const payload = { | ||
| nextVersion: "16.3.1-canary.10", | ||
| nextVersion: "16.3.1-canary.11", | ||
| nodeVersion: process.version, | ||
@@ -24,0 +24,0 @@ cliCommand: event.cliCommand, |
+10
-10
| { | ||
| "name": "next", | ||
| "version": "16.3.1-canary.10", | ||
| "version": "16.3.1-canary.11", | ||
| "description": "The React Framework", | ||
@@ -84,3 +84,3 @@ "main": "./dist/server/next.js", | ||
| "dependencies": { | ||
| "@next/env": "16.3.1-canary.10", | ||
| "@next/env": "16.3.1-canary.11", | ||
| "@swc/helpers": "0.5.23", | ||
@@ -116,10 +116,10 @@ "baseline-browser-mapping": "^2.9.19", | ||
| "sharp": "^0.35.3", | ||
| "@next/swc-darwin-arm64": "16.3.1-canary.10", | ||
| "@next/swc-darwin-x64": "16.3.1-canary.10", | ||
| "@next/swc-linux-arm64-gnu": "16.3.1-canary.10", | ||
| "@next/swc-linux-arm64-musl": "16.3.1-canary.10", | ||
| "@next/swc-linux-x64-gnu": "16.3.1-canary.10", | ||
| "@next/swc-linux-x64-musl": "16.3.1-canary.10", | ||
| "@next/swc-win32-arm64-msvc": "16.3.1-canary.10", | ||
| "@next/swc-win32-x64-msvc": "16.3.1-canary.10" | ||
| "@next/swc-darwin-arm64": "16.3.1-canary.11", | ||
| "@next/swc-darwin-x64": "16.3.1-canary.11", | ||
| "@next/swc-linux-arm64-gnu": "16.3.1-canary.11", | ||
| "@next/swc-linux-arm64-musl": "16.3.1-canary.11", | ||
| "@next/swc-linux-x64-gnu": "16.3.1-canary.11", | ||
| "@next/swc-linux-x64-musl": "16.3.1-canary.11", | ||
| "@next/swc-win32-arm64-msvc": "16.3.1-canary.11", | ||
| "@next/swc-win32-x64-msvc": "16.3.1-canary.11" | ||
| }, | ||
@@ -126,0 +126,0 @@ "keywords": [ |
+1
-1
@@ -32,3 +32,3 @@ <div align="center"> | ||
| To chat with other community members you can join the Next.js [Discord](https://nextjs.org/discord) server. | ||
| To chat with other community members, you can join the Next.js [Discord](https://nextjs.org/discord) server. | ||
@@ -35,0 +35,0 @@ Do note that our [Code of Conduct](https://github.com/vercel/next.js/blob/canary/CODE_OF_CONDUCT.md) applies to all Next.js community channels. Users are **highly encouraged** to read and adhere to it to avoid repercussions. |
| self.__BUILD_MANIFEST = { | ||
| "__rewrites": { | ||
| "afterFiles": [], | ||
| "beforeFiles": [], | ||
| "fallback": [] | ||
| }, | ||
| "sortedPages": [ | ||
| "/_app", | ||
| "/_error" | ||
| ] | ||
| };self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB() |
| self.__MIDDLEWARE_MATCHERS = [];self.__MIDDLEWARE_MATCHERS_CB && self.__MIDDLEWARE_MATCHERS_CB() |
| self.__SSG_MANIFEST=new Set([]);self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB() |
| --- | ||
| title: Runtime prefetching | ||
| description: Prefetch URL data alongside the App Shell using the prefetch segment config and per-session caching directives. | ||
| nav_title: Runtime prefetching | ||
| related: | ||
| title: Learn more | ||
| description: Validate your structure and review the caching primitives. | ||
| links: | ||
| - app/api-reference/config/next-config-js/partialPrefetching | ||
| - app/api-reference/file-conventions/route-segment-config/prefetch | ||
| - app/api-reference/file-conventions/route-segment-config/instant | ||
| - app/api-reference/directives/use-cache-private | ||
| - app/getting-started/caching | ||
| - app/guides/instant-navigation | ||
| - app/guides/prefetching | ||
| --- | ||
| Prefetching downloads a route's JavaScript, CSS, and RSC payload before the user navigates to it, so the router can render the next route without waiting for a round trip. | ||
| The regular App Router prefetches a route all or nothing: the full route when it's static, and nothing for a dynamic route without a [`loading.js`](/docs/app/api-reference/file-conventions/loading). | ||
| [Cache Components](/docs/app/getting-started/caching) with [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching) enabled takes a different approach, prefetching one reusable [**App Shell**](/docs/app/glossary#app-shell) per route rather than a separate prefetch per link. The shell contains the route's static output, and for a route that reads [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers) (session data), it also carries UI gated behind that session data. | ||
| Any number of links to the same route share that one shell, fetched once as a [`<Link>`](/docs/app/api-reference/components/link) enters the viewport and reused for the rest. | ||
| The shell cannot carry data that varies per link: [`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional) and [`params`](/docs/app/api-reference/file-conventions/page#params-optional), the route's [URL data](/docs/app/glossary#url-data). **Runtime prefetching** resolves that URL data at prefetch time, ready before the click rather than streaming in after it. | ||
| This guide assumes [Cache Components](/docs/app/getting-started/caching) with [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) enabled: | ||
| ```ts filename="next.config.ts" highlight={4,5} | ||
| import type { NextConfig } from 'next' | ||
| const nextConfig: NextConfig = { | ||
| cacheComponents: true, | ||
| partialPrefetching: true, | ||
| } | ||
| export default nextConfig | ||
| ``` | ||
| It also assumes your route is already structured for instant navigation. If it isn't, start with the [Instant navigation guide](/docs/app/guides/instant-navigation) to validate its caching structure first. | ||
| ## What runtime prefetching does | ||
| Runtime prefetching is opted into per link with `<Link prefetch={true}>`. Any destination with [Partial Prefetching](/docs/app/api-reference/config/next-config-js/partialPrefetching) enabled supports it, either globally via `partialPrefetching` or per segment with [`prefetch = 'partial'`](/docs/app/api-reference/file-conventions/route-segment-config/prefetch#partial). | ||
| A user on `/` sees links to `/search?q=react` and `/search?q=next`, each opting in with `prefetch={true}`: | ||
| ```tsx filename="app/page.tsx" | ||
| import Link from 'next/link' | ||
| export default function Home() { | ||
| return ( | ||
| <nav> | ||
| <Link href="/search?q=react" prefetch={true}> | ||
| React | ||
| </Link> | ||
| <Link href="/search?q=next" prefetch={true}> | ||
| Next.js | ||
| </Link> | ||
| </nav> | ||
| ) | ||
| } | ||
| ``` | ||
| The destination renders a static heading and a `<Results>` list whose contents depend on the query. Each query is cached, computed once and reused. | ||
| ```tsx filename="app/search/page.tsx" | ||
| import { Suspense } from 'react' | ||
| export default function SearchPage({ searchParams }: PageProps<'/search'>) { | ||
| return ( | ||
| <> | ||
| <h1>Search</h1> | ||
| <Suspense fallback={<ResultsSkeleton />}> | ||
| <Results searchParams={searchParams} /> | ||
| </Suspense> | ||
| </> | ||
| ) | ||
| } | ||
| async function Results({ | ||
| searchParams, | ||
| }: { | ||
| searchParams: PageProps<'/search'>['searchParams'] | ||
| }) { | ||
| const { q } = await searchParams | ||
| return <ResultList items={await search(q)} /> | ||
| } | ||
| async function search(q: string) { | ||
| 'use cache' | ||
| return db.search(q) | ||
| } | ||
| ``` | ||
| Without `prefetch={true}`, the App Shell renders `<h1>` and shows the `<Results>` fallback. The query resolves after the click and streams the results in. | ||
| With `prefetch={true}` on the link, the router prefetches a prerender that resolves `<Results>` before the click. The `q` value comes from the link's URL, known at prefetch time, and the cached `search(q)` fills in from there. On the click, the results render immediately, with no fallback. | ||
| The prerender advances through anything static or cached, then stops at uncached reads and falls back to the surrounding `<Suspense>` boundary. That boundary is already in place from [structuring the route for instant navigation](/docs/app/guides/instant-navigation). | ||
| More of the page is rendered before the user clicks, with fewer loading states. | ||
| Generating it costs **a server invocation per prefetchable link**, so it is opt-in per link. On pages where all the content is statically renderable, Next.js serves the prefetch from the static cache instead. A page that accesses non-static data is prefetched at runtime. | ||
| > **Good to know:** A cold cache (first visit, or after expiration) means the server still has to compute the cached result. Users may see a loading spinner on that first navigation. Subsequent navigations are instant as long as the cache is warm. | ||
| Like `searchParams`, `params` needs a `<Suspense>` boundary, even when the values are predefined by [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params). A statically known param still belongs to one URL. Runtime prefetching resolves the values `generateStaticParams` does not cover. | ||
| ## Session data resolves in the shell | ||
| Runtime prefetching is for URL data. Session data is handled separately. A route that reads `cookies()` or `headers()`, including through `"use cache: private"`, gets an App Shell that includes its session data, cached per session on the client and ready on navigation without a per-link runtime prefetch. | ||
| A lookup based on session data needs a cache lifetime, the same way `search(q)` did for the URL. Take a dashboard nav that reads a cookie, then looks up content based on it: | ||
| ```tsx filename="app/dashboard/layout.tsx" | ||
| import { Suspense } from 'react' | ||
| export default function DashboardLayout({ | ||
| children, | ||
| }: LayoutProps<'/dashboard'>) { | ||
| return ( | ||
| <div> | ||
| <Suspense fallback={<nav>Loading...</nav>}> | ||
| <UserNav /> | ||
| </Suspense> | ||
| <main>{children}</main> | ||
| </div> | ||
| ) | ||
| } | ||
| ``` | ||
| The cookie itself is session data the App Shell already knows. But `"use cache"` can't read `cookies()` inside the cached function, so two patterns bridge it: | ||
| - **Extract and pass** when the lookup result is shared across many sessions. | ||
| - **`"use cache: private"`** when it is tied to one. | ||
| ### Extract and pass | ||
| Read the cookie outside the cached function and pass the value in as an argument. The `cookies()` call stays outside the cache scope, the argument crosses the boundary, and the cached function has a deterministic signature. The cache entry is keyed on that argument, and sessions that share the value share the entry. | ||
| ```tsx filename="app/dashboard/user-nav.tsx" | ||
| import { cookies } from 'next/headers' | ||
| async function UserNav() { | ||
| const team = (await cookies()).get('team')?.value | ||
| const topics = await getTopics(team) | ||
| return ( | ||
| <nav> | ||
| {topics.map((topic) => ( | ||
| <a key={topic.id} href={topic.href}> | ||
| {topic.label} | ||
| </a> | ||
| ))} | ||
| </nav> | ||
| ) | ||
| } | ||
| async function getTopics(team: string | undefined) { | ||
| 'use cache' | ||
| return db.topics.forTeam(team) | ||
| } | ||
| ``` | ||
| On a direct visit, `<UserNav>` shows its fallback until the lookup resolves. On navigation, the App Shell has already resolved it, because the team cookie is session data the shell can read. Because sessions on the same team share the cache entry, traffic to the underlying data scales with team count, not session count. | ||
| Anything without a caching directive still streams in after navigation. A shell holds only what can be prepared ahead of the navigation, not the whole page. It advances only as far as the caching structure allows. | ||
| ### `"use cache: private"` | ||
| When the lookup is tied to a single session, use [`"use cache: private"`](/docs/app/api-reference/directives/use-cache-private). It assigns a cache lifetime to a function that reads cookies, headers, or other runtime data directly. Results are cached in the browser only, scoped to that session. | ||
| ```tsx filename="app/dashboard/user-nav.tsx" | ||
| import { cookies } from 'next/headers' | ||
| async function UserNav() { | ||
| const user = await getUser() | ||
| return <nav>{user.name}</nav> | ||
| } | ||
| async function getUser() { | ||
| 'use cache: private' | ||
| const session = (await cookies()).get('session')?.value | ||
| return db.users.findBySession(session) | ||
| } | ||
| ``` | ||
| Here `cookies()` lives inside the cached function, which only works under `"use cache: private"`. This is also the pattern when you can't extract the runtime data from the outside: auth helpers that check `Date.now()` against a token's expiry, or session helpers that read cookies deep inside their own code, can't be wrapped at the call site. | ||
| Everything inside the scope shares the same lifetime. Colocate `"use cache: private"` as close to the runtime data access as possible. | ||
| ## Per-link prefetching trade-offs | ||
| Use it on routes where: | ||
| - Part of the component tree depends on URL data: the full URL, `searchParams`, or `params` not resolved by [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params) | ||
| - That part of the tree has a known cache lifetime (it can be expressed with `"use cache"` or `"use cache: private"`) | ||
| - The traffic justifies the per-link server invocation | ||
| Skip it when the prefetch can't produce a better UI than the App Shell. Each visible `<Link prefetch={true}>` can wake a server, and that cost only pays off if more of the page is ready before the click: | ||
| - The route has little or no URL-data dependency. The App Shell already makes the navigation instant. | ||
| - The dependent content has to be fresh on every request. The prerender stops at the same `<Suspense>` fallback, so the user sees the same UI either way. | ||
| - The route is rarely navigated to. You pay per visible link, regardless of click-through. | ||
| A per-link runtime prefetch is best-effort. It only helps the navigations where it completes before the click. On a slow connection, on a feed of many links, or on a direct visit, it may not be ready when the user navigates, and the navigation falls back to the App Shell. That shell is the reliable baseline, and runtime prefetching only layers on top when it arrives in time. | ||
| When many links to a route are visible at once, such as a grid of cards, each `<Link prefetch={true}>` prefetches that link's content as it enters the viewport, so the grid makes one such server request per card. Prefetch on intent instead. A [hover-triggered prefetch](/docs/app/guides/prefetching#hover-triggered-prefetch) fetches only the links the user is likely to click. The default `<Link>` (without `prefetch={true}`) prefetches only the App Shell, so it doesn't carry this cost. | ||
| | | App Shell | Per-link runtime prefetch with `prefetch={true}` | | ||
| | ------- | ------------------------------------------- | ------------------------------------------------ | | ||
| | Scope | One per route | One per visible `<Link prefetch={true}>` | | ||
| | Content | Route's rendered output minus per-link data | Same, plus per-link URL data resolved | | ||
| | Cost | Bounded by route count | Bounded by visible-link count | | ||
| | Role | Every route's instant floor | Upgrade: more rendered before click | | ||
| ## Next steps | ||
| - [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for how `<Link>` behaves under the new model and how to migrate existing apps. | ||
| - [`prefetch` API reference](/docs/app/api-reference/file-conventions/route-segment-config/prefetch) for all prefetch modes. | ||
| - [`use cache: private` reference](/docs/app/api-reference/directives/use-cache-private) for per-user caching specifics. | ||
| - [Instant navigation guide](/docs/app/guides/instant-navigation) for validating the route's caching structure. | ||
| - [Caching](/docs/app/getting-started/caching) for background on `use cache`, Suspense, and Partial Prerendering. |
| /** | ||
| * Percent-encode every character outside printable ASCII so a tag value can be | ||
| * safely serialized as part of the `x-next-cache-tags` HTTP header. | ||
| * | ||
| * Node's `validateHeaderValue` rejects any code unit outside `\t\x20-\x7e`, so | ||
| * a matched route path or user-supplied tag containing a non-ASCII character | ||
| * (Hebrew, Arabic, Chinese, emoji, …) would otherwise throw `ERR_INVALID_CHAR` | ||
| * and crash ISR on every affected request. | ||
| * | ||
| * This is applied at the public boundaries — tag construction | ||
| * (`getImplicitTags`, `validateTags`) and invalidation input (`revalidatePath`, | ||
| * `revalidateTag`, `updateTag`) — so storage, comparison, and the wire all see | ||
| * the same canonical ASCII-safe form. | ||
| * | ||
| * The character class `[\t\x20-\x7e]` mirrors Node's `validHdrChars` table — | ||
| * `\t` plus printable ASCII through `~`. Anything outside that is rejected | ||
| * by `validateHeaderValue`, so we encode runs of those characters and leave | ||
| * everything else (`,`, `/`, `%`, `[`, `]`, `_`, `-`, `\t`, …) byte-for-byte | ||
| * unchanged. This preserves the comma-separated header format and the | ||
| * dynamic-segment markers in derived tags (`_N_T_/[slug]/page`). | ||
| * | ||
| * Properties: | ||
| * - Fast-path: input that already fits the validation class is returned | ||
| * unchanged. This makes the encoder idempotent on already-encoded `%xx` | ||
| * sequences. | ||
| * - Matches *runs* of out-of-class code units so surrogate pairs (e.g. an | ||
| * emoji) are handed to `encodeURIComponent` as a complete code point — a | ||
| * per-code-unit regex would split the pair and throw `URIError`. | ||
| */ const OUT_OF_CLASS_CHAR = /[^\t\x20-\x7e]/; | ||
| const OUT_OF_CLASS_RUN = /[^\t\x20-\x7e]+/g; | ||
| export function encodeCacheTag(tag) { | ||
| return OUT_OF_CLASS_CHAR.test(tag) ? tag.replace(OUT_OF_CLASS_RUN, (run)=>encodeURIComponent(run)) : tag; | ||
| } | ||
| //# sourceMappingURL=encode-cache-tag.js.map |
| {"version":3,"sources":["../../../../src/server/lib/encode-cache-tag.ts"],"sourcesContent":["/**\n * Percent-encode every character outside printable ASCII so a tag value can be\n * safely serialized as part of the `x-next-cache-tags` HTTP header.\n *\n * Node's `validateHeaderValue` rejects any code unit outside `\\t\\x20-\\x7e`, so\n * a matched route path or user-supplied tag containing a non-ASCII character\n * (Hebrew, Arabic, Chinese, emoji, …) would otherwise throw `ERR_INVALID_CHAR`\n * and crash ISR on every affected request.\n *\n * This is applied at the public boundaries — tag construction\n * (`getImplicitTags`, `validateTags`) and invalidation input (`revalidatePath`,\n * `revalidateTag`, `updateTag`) — so storage, comparison, and the wire all see\n * the same canonical ASCII-safe form.\n *\n * The character class `[\\t\\x20-\\x7e]` mirrors Node's `validHdrChars` table —\n * `\\t` plus printable ASCII through `~`. Anything outside that is rejected\n * by `validateHeaderValue`, so we encode runs of those characters and leave\n * everything else (`,`, `/`, `%`, `[`, `]`, `_`, `-`, `\\t`, …) byte-for-byte\n * unchanged. This preserves the comma-separated header format and the\n * dynamic-segment markers in derived tags (`_N_T_/[slug]/page`).\n *\n * Properties:\n * - Fast-path: input that already fits the validation class is returned\n * unchanged. This makes the encoder idempotent on already-encoded `%xx`\n * sequences.\n * - Matches *runs* of out-of-class code units so surrogate pairs (e.g. an\n * emoji) are handed to `encodeURIComponent` as a complete code point — a\n * per-code-unit regex would split the pair and throw `URIError`.\n */\nconst OUT_OF_CLASS_CHAR = /[^\\t\\x20-\\x7e]/\nconst OUT_OF_CLASS_RUN = /[^\\t\\x20-\\x7e]+/g\n\nexport function encodeCacheTag(tag: string): string {\n return OUT_OF_CLASS_CHAR.test(tag)\n ? tag.replace(OUT_OF_CLASS_RUN, (run) => encodeURIComponent(run))\n : tag\n}\n"],"names":["OUT_OF_CLASS_CHAR","OUT_OF_CLASS_RUN","encodeCacheTag","tag","test","replace","run","encodeURIComponent"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BC,GACD,MAAMA,oBAAoB;AAC1B,MAAMC,mBAAmB;AAEzB,OAAO,SAASC,eAAeC,GAAW;IACxC,OAAOH,kBAAkBI,IAAI,CAACD,OAC1BA,IAAIE,OAAO,CAACJ,kBAAkB,CAACK,MAAQC,mBAAmBD,QAC1DH;AACN","ignoreList":[0]} |
| export declare function encodeCacheTag(tag: string): string; |
| /** | ||
| * Percent-encode every character outside printable ASCII so a tag value can be | ||
| * safely serialized as part of the `x-next-cache-tags` HTTP header. | ||
| * | ||
| * Node's `validateHeaderValue` rejects any code unit outside `\t\x20-\x7e`, so | ||
| * a matched route path or user-supplied tag containing a non-ASCII character | ||
| * (Hebrew, Arabic, Chinese, emoji, …) would otherwise throw `ERR_INVALID_CHAR` | ||
| * and crash ISR on every affected request. | ||
| * | ||
| * This is applied at the public boundaries — tag construction | ||
| * (`getImplicitTags`, `validateTags`) and invalidation input (`revalidatePath`, | ||
| * `revalidateTag`, `updateTag`) — so storage, comparison, and the wire all see | ||
| * the same canonical ASCII-safe form. | ||
| * | ||
| * The character class `[\t\x20-\x7e]` mirrors Node's `validHdrChars` table — | ||
| * `\t` plus printable ASCII through `~`. Anything outside that is rejected | ||
| * by `validateHeaderValue`, so we encode runs of those characters and leave | ||
| * everything else (`,`, `/`, `%`, `[`, `]`, `_`, `-`, `\t`, …) byte-for-byte | ||
| * unchanged. This preserves the comma-separated header format and the | ||
| * dynamic-segment markers in derived tags (`_N_T_/[slug]/page`). | ||
| * | ||
| * Properties: | ||
| * - Fast-path: input that already fits the validation class is returned | ||
| * unchanged. This makes the encoder idempotent on already-encoded `%xx` | ||
| * sequences. | ||
| * - Matches *runs* of out-of-class code units so surrogate pairs (e.g. an | ||
| * emoji) are handed to `encodeURIComponent` as a complete code point — a | ||
| * per-code-unit regex would split the pair and throw `URIError`. | ||
| */ "use strict"; | ||
| Object.defineProperty(exports, "__esModule", { | ||
| value: true | ||
| }); | ||
| Object.defineProperty(exports, "encodeCacheTag", { | ||
| enumerable: true, | ||
| get: function() { | ||
| return encodeCacheTag; | ||
| } | ||
| }); | ||
| const OUT_OF_CLASS_CHAR = /[^\t\x20-\x7e]/; | ||
| const OUT_OF_CLASS_RUN = /[^\t\x20-\x7e]+/g; | ||
| function encodeCacheTag(tag) { | ||
| return OUT_OF_CLASS_CHAR.test(tag) ? tag.replace(OUT_OF_CLASS_RUN, (run)=>encodeURIComponent(run)) : tag; | ||
| } | ||
| //# sourceMappingURL=encode-cache-tag.js.map |
| {"version":3,"sources":["../../../src/server/lib/encode-cache-tag.ts"],"sourcesContent":["/**\n * Percent-encode every character outside printable ASCII so a tag value can be\n * safely serialized as part of the `x-next-cache-tags` HTTP header.\n *\n * Node's `validateHeaderValue` rejects any code unit outside `\\t\\x20-\\x7e`, so\n * a matched route path or user-supplied tag containing a non-ASCII character\n * (Hebrew, Arabic, Chinese, emoji, …) would otherwise throw `ERR_INVALID_CHAR`\n * and crash ISR on every affected request.\n *\n * This is applied at the public boundaries — tag construction\n * (`getImplicitTags`, `validateTags`) and invalidation input (`revalidatePath`,\n * `revalidateTag`, `updateTag`) — so storage, comparison, and the wire all see\n * the same canonical ASCII-safe form.\n *\n * The character class `[\\t\\x20-\\x7e]` mirrors Node's `validHdrChars` table —\n * `\\t` plus printable ASCII through `~`. Anything outside that is rejected\n * by `validateHeaderValue`, so we encode runs of those characters and leave\n * everything else (`,`, `/`, `%`, `[`, `]`, `_`, `-`, `\\t`, …) byte-for-byte\n * unchanged. This preserves the comma-separated header format and the\n * dynamic-segment markers in derived tags (`_N_T_/[slug]/page`).\n *\n * Properties:\n * - Fast-path: input that already fits the validation class is returned\n * unchanged. This makes the encoder idempotent on already-encoded `%xx`\n * sequences.\n * - Matches *runs* of out-of-class code units so surrogate pairs (e.g. an\n * emoji) are handed to `encodeURIComponent` as a complete code point — a\n * per-code-unit regex would split the pair and throw `URIError`.\n */\nconst OUT_OF_CLASS_CHAR = /[^\\t\\x20-\\x7e]/\nconst OUT_OF_CLASS_RUN = /[^\\t\\x20-\\x7e]+/g\n\nexport function encodeCacheTag(tag: string): string {\n return OUT_OF_CLASS_CHAR.test(tag)\n ? tag.replace(OUT_OF_CLASS_RUN, (run) => encodeURIComponent(run))\n : tag\n}\n"],"names":["encodeCacheTag","OUT_OF_CLASS_CHAR","OUT_OF_CLASS_RUN","tag","test","replace","run","encodeURIComponent"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BC;;;;+BAIeA;;;eAAAA;;;AAHhB,MAAMC,oBAAoB;AAC1B,MAAMC,mBAAmB;AAElB,SAASF,eAAeG,GAAW;IACxC,OAAOF,kBAAkBG,IAAI,CAACD,OAC1BA,IAAIE,OAAO,CAACH,kBAAkB,CAACI,MAAQC,mBAAmBD,QAC1DH;AACN","ignoreList":[0]} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Potential vulnerability
Supply chain riskInitial human review suggests the presence of a vulnerability in this package. It is pending further analysis and confirmation.
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Found 13 instances
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Potential vulnerability
Supply chain riskInitial human review suggests the presence of a vulnerability in this package. It is pending further analysis and confirmation.
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Found 13 instances
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
184902735
0.09%1314828
0.04%4523
-0.22%+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
Updated