vinext 0.0.52 → 0.0.53
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/build/clean-output.d.ts +14 -0
- package/dist/build/clean-output.js +36 -0
- package/dist/build/clean-output.js.map +1 -0
- package/dist/build/prerender.d.ts +6 -2
- package/dist/build/prerender.js +49 -11
- package/dist/build/prerender.js.map +1 -1
- package/dist/build/run-prerender.js +10 -1
- package/dist/build/run-prerender.js.map +1 -1
- package/dist/build/static-export.d.ts +5 -0
- package/dist/build/static-export.js +8 -3
- package/dist/build/static-export.js.map +1 -1
- package/dist/cli.js +19 -4
- package/dist/cli.js.map +1 -1
- package/dist/client/instrumentation-client-inject.d.ts +34 -0
- package/dist/client/instrumentation-client-inject.js +57 -0
- package/dist/client/instrumentation-client-inject.js.map +1 -0
- package/dist/client/navigation-runtime.d.ts +14 -1
- package/dist/client/navigation-runtime.js +16 -1
- package/dist/client/navigation-runtime.js.map +1 -1
- package/dist/client/vinext-next-data.d.ts +2 -1
- package/dist/client/vinext-next-data.js.map +1 -1
- package/dist/client/window-next.d.ts +10 -2
- package/dist/client/window-next.js.map +1 -1
- package/dist/cloudflare/tpr.js +1 -1
- package/dist/cloudflare/tpr.js.map +1 -1
- package/dist/config/config-matchers.js +2 -1
- package/dist/config/config-matchers.js.map +1 -1
- package/dist/config/next-config.d.ts +12 -3
- package/dist/config/next-config.js +44 -14
- package/dist/config/next-config.js.map +1 -1
- package/dist/deploy.js +29 -7
- package/dist/deploy.js.map +1 -1
- package/dist/entries/app-rsc-entry.d.ts +4 -2
- package/dist/entries/app-rsc-entry.js +23 -3
- package/dist/entries/app-rsc-entry.js.map +1 -1
- package/dist/entries/pages-client-entry.js +22 -1
- package/dist/entries/pages-client-entry.js.map +1 -1
- package/dist/entries/pages-server-entry.js +211 -31
- package/dist/entries/pages-server-entry.js.map +1 -1
- package/dist/index.js +29 -6
- package/dist/index.js.map +1 -1
- package/dist/plugins/fonts.js +25 -2
- package/dist/plugins/fonts.js.map +1 -1
- package/dist/routing/route-trie.js +13 -18
- package/dist/routing/route-trie.js.map +1 -1
- package/dist/routing/utils.d.ts +11 -1
- package/dist/routing/utils.js +15 -1
- package/dist/routing/utils.js.map +1 -1
- package/dist/server/api-handler.js +18 -9
- package/dist/server/api-handler.js.map +1 -1
- package/dist/server/app-browser-action-result.d.ts +16 -1
- package/dist/server/app-browser-action-result.js +15 -1
- package/dist/server/app-browser-action-result.js.map +1 -1
- package/dist/server/app-browser-entry.js +22 -12
- package/dist/server/app-browser-entry.js.map +1 -1
- package/dist/server/app-elements.js +1 -1
- package/dist/server/app-fallback-renderer.d.ts +12 -3
- package/dist/server/app-fallback-renderer.js +10 -5
- package/dist/server/app-fallback-renderer.js.map +1 -1
- package/dist/server/app-history-state.js +6 -2
- package/dist/server/app-history-state.js.map +1 -1
- package/dist/server/app-interception-context-header.d.ts +33 -0
- package/dist/server/app-interception-context-header.js +44 -0
- package/dist/server/app-interception-context-header.js.map +1 -0
- package/dist/server/app-mounted-slots-header.d.ts +19 -0
- package/dist/server/app-mounted-slots-header.js +40 -1
- package/dist/server/app-mounted-slots-header.js.map +1 -1
- package/dist/server/app-optimistic-routing.js +26 -18
- package/dist/server/app-optimistic-routing.js.map +1 -1
- package/dist/server/app-page-boundary-render.d.ts +1 -0
- package/dist/server/app-page-boundary-render.js +2 -0
- package/dist/server/app-page-boundary-render.js.map +1 -1
- package/dist/server/app-page-boundary.d.ts +1 -0
- package/dist/server/app-page-boundary.js +2 -0
- package/dist/server/app-page-boundary.js.map +1 -1
- package/dist/server/app-page-cache.d.ts +2 -0
- package/dist/server/app-page-cache.js +7 -1
- package/dist/server/app-page-cache.js.map +1 -1
- package/dist/server/app-page-dispatch.d.ts +3 -0
- package/dist/server/app-page-dispatch.js +11 -4
- package/dist/server/app-page-dispatch.js.map +1 -1
- package/dist/server/app-page-element-builder.d.ts +2 -1
- package/dist/server/app-page-element-builder.js +5 -2
- package/dist/server/app-page-element-builder.js.map +1 -1
- package/dist/server/app-page-execution.d.ts +1 -0
- package/dist/server/app-page-execution.js +2 -0
- package/dist/server/app-page-execution.js.map +1 -1
- package/dist/server/app-page-head.d.ts +1 -0
- package/dist/server/app-page-head.js +8 -0
- package/dist/server/app-page-head.js.map +1 -1
- package/dist/server/app-page-render-observation.js +1 -1
- package/dist/server/app-page-render.d.ts +1 -0
- package/dist/server/app-page-render.js +5 -2
- package/dist/server/app-page-render.js.map +1 -1
- package/dist/server/app-page-response.d.ts +11 -1
- package/dist/server/app-page-response.js +14 -2
- package/dist/server/app-page-response.js.map +1 -1
- package/dist/server/app-page-route-wiring.d.ts +1 -0
- package/dist/server/app-page-route-wiring.js +19 -6
- package/dist/server/app-page-route-wiring.js.map +1 -1
- package/dist/server/app-page-stream.d.ts +1 -0
- package/dist/server/app-page-stream.js +2 -0
- package/dist/server/app-page-stream.js.map +1 -1
- package/dist/server/app-route-handler-dispatch.d.ts +1 -0
- package/dist/server/app-route-handler-dispatch.js +3 -0
- package/dist/server/app-route-handler-dispatch.js.map +1 -1
- package/dist/server/app-route-handler-execution.d.ts +1 -0
- package/dist/server/app-route-handler-execution.js +1 -0
- package/dist/server/app-route-handler-execution.js.map +1 -1
- package/dist/server/app-route-handler-response.js +1 -1
- package/dist/server/app-rsc-handler.d.ts +2 -0
- package/dist/server/app-rsc-handler.js +18 -9
- package/dist/server/app-rsc-handler.js.map +1 -1
- package/dist/server/app-rsc-request-normalization.js +3 -2
- package/dist/server/app-rsc-request-normalization.js.map +1 -1
- package/dist/server/app-segment-config.d.ts +4 -1
- package/dist/server/app-segment-config.js +6 -1
- package/dist/server/app-segment-config.js.map +1 -1
- package/dist/server/app-server-action-execution.d.ts +1 -0
- package/dist/server/app-server-action-execution.js +4 -0
- package/dist/server/app-server-action-execution.js.map +1 -1
- package/dist/server/app-ssr-entry.js +39 -3
- package/dist/server/app-ssr-entry.js.map +1 -1
- package/dist/server/app-ssr-stream.d.ts +24 -1
- package/dist/server/app-ssr-stream.js +78 -5
- package/dist/server/app-ssr-stream.js.map +1 -1
- package/dist/server/app-static-generation.d.ts +1 -0
- package/dist/server/app-static-generation.js +2 -1
- package/dist/server/app-static-generation.js.map +1 -1
- package/dist/server/default-not-found-module.d.ts +20 -0
- package/dist/server/default-not-found-module.js +20 -0
- package/dist/server/default-not-found-module.js.map +1 -0
- package/dist/server/dev-server.d.ts +1 -1
- package/dist/server/dev-server.js +23 -7
- package/dist/server/dev-server.js.map +1 -1
- package/dist/server/headers.d.ts +5 -1
- package/dist/server/headers.js +5 -1
- package/dist/server/headers.js.map +1 -1
- package/dist/server/image-optimization.d.ts +13 -4
- package/dist/server/image-optimization.js +15 -4
- package/dist/server/image-optimization.js.map +1 -1
- package/dist/server/middleware.js +1 -1
- package/dist/server/middleware.js.map +1 -1
- package/dist/server/pages-api-route.d.ts +18 -0
- package/dist/server/pages-api-route.js +3 -1
- package/dist/server/pages-api-route.js.map +1 -1
- package/dist/server/pages-body-parser-config.d.ts +60 -0
- package/dist/server/pages-body-parser-config.js +79 -0
- package/dist/server/pages-body-parser-config.js.map +1 -0
- package/dist/server/pages-data-route.js +1 -0
- package/dist/server/pages-data-route.js.map +1 -1
- package/dist/server/pages-default-404.d.ts +31 -0
- package/dist/server/pages-default-404.js +40 -0
- package/dist/server/pages-default-404.js.map +1 -0
- package/dist/server/pages-node-compat.d.ts +10 -0
- package/dist/server/pages-node-compat.js +12 -1
- package/dist/server/pages-node-compat.js.map +1 -1
- package/dist/server/pages-page-data.d.ts +40 -0
- package/dist/server/pages-page-data.js +16 -14
- package/dist/server/pages-page-data.js.map +1 -1
- package/dist/server/pages-page-response.d.ts +2 -0
- package/dist/server/pages-page-response.js +11 -8
- package/dist/server/pages-page-response.js.map +1 -1
- package/dist/server/prerender-route-params.d.ts +14 -0
- package/dist/server/prerender-route-params.js +94 -0
- package/dist/server/prerender-route-params.js.map +1 -0
- package/dist/server/prod-server.d.ts +3 -23
- package/dist/server/prod-server.js +40 -57
- package/dist/server/prod-server.js.map +1 -1
- package/dist/server/proxy-trust.d.ts +41 -0
- package/dist/server/proxy-trust.js +70 -0
- package/dist/server/proxy-trust.js.map +1 -0
- package/dist/server/request-pipeline.d.ts +3 -3
- package/dist/server/request-pipeline.js +5 -4
- package/dist/server/request-pipeline.js.map +1 -1
- package/dist/server/seed-cache.js +12 -6
- package/dist/server/seed-cache.js.map +1 -1
- package/dist/server/static-file-cache.js +1 -1
- package/dist/server/static-file-cache.js.map +1 -1
- package/dist/server/streaming-metadata.d.ts +5 -0
- package/dist/server/streaming-metadata.js +10 -0
- package/dist/server/streaming-metadata.js.map +1 -0
- package/dist/shims/app-router-scroll-state.d.ts +12 -0
- package/dist/shims/app-router-scroll-state.js +38 -0
- package/dist/shims/app-router-scroll-state.js.map +1 -0
- package/dist/shims/app-router-scroll.d.ts +14 -0
- package/dist/shims/app-router-scroll.js +100 -0
- package/dist/shims/app-router-scroll.js.map +1 -0
- package/dist/shims/before-interactive-context.d.ts +30 -0
- package/dist/shims/before-interactive-context.js +10 -0
- package/dist/shims/before-interactive-context.js.map +1 -0
- package/dist/shims/cache-runtime.d.ts +1 -1
- package/dist/shims/cache-runtime.js +14 -1
- package/dist/shims/cache-runtime.js.map +1 -1
- package/dist/shims/default-not-found.d.ts +12 -0
- package/dist/shims/default-not-found.js +61 -0
- package/dist/shims/default-not-found.js.map +1 -0
- package/dist/shims/font-local.d.ts +5 -0
- package/dist/shims/font-local.js +6 -2
- package/dist/shims/font-local.js.map +1 -1
- package/dist/shims/head.js +4 -4
- package/dist/shims/head.js.map +1 -1
- package/dist/shims/headers.d.ts +6 -2
- package/dist/shims/headers.js +64 -21
- package/dist/shims/headers.js.map +1 -1
- package/dist/shims/image.d.ts +1 -1
- package/dist/shims/image.js +4 -4
- package/dist/shims/image.js.map +1 -1
- package/dist/shims/internal/pages-data-target.d.ts +58 -0
- package/dist/shims/internal/pages-data-target.js +91 -0
- package/dist/shims/internal/pages-data-target.js.map +1 -0
- package/dist/shims/internal/pages-data-url.d.ts +42 -0
- package/dist/shims/internal/pages-data-url.js +73 -0
- package/dist/shims/internal/pages-data-url.js.map +1 -0
- package/dist/shims/link.js +59 -9
- package/dist/shims/link.js.map +1 -1
- package/dist/shims/metadata.d.ts +2 -1
- package/dist/shims/metadata.js +61 -2
- package/dist/shims/metadata.js.map +1 -1
- package/dist/shims/navigation.js +32 -9
- package/dist/shims/navigation.js.map +1 -1
- package/dist/shims/router.js +376 -77
- package/dist/shims/router.js.map +1 -1
- package/dist/shims/script.js +86 -12
- package/dist/shims/script.js.map +1 -1
- package/dist/shims/server.js +1 -0
- package/dist/shims/server.js.map +1 -1
- package/dist/shims/url-utils.d.ts +2 -1
- package/dist/shims/url-utils.js +15 -4
- package/dist/shims/url-utils.js.map +1 -1
- package/dist/utils/html-limited-bots.d.ts +5 -0
- package/dist/utils/html-limited-bots.js +15 -0
- package/dist/utils/html-limited-bots.js.map +1 -0
- package/dist/utils/query.d.ts +6 -0
- package/dist/utils/query.js +10 -1
- package/dist/utils/query.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-browser-entry.js","names":["_exhaustive"],"sources":["../../src/server/app-browser-entry.ts"],"sourcesContent":["/// <reference types=\"vite/client\" />\n\nimport { createElement, startTransition, use, useLayoutEffect, useRef, useState } from \"react\";\nimport {\n createFromFetch,\n createFromReadableStream,\n createTemporaryReferenceSet,\n encodeReply,\n setServerCallback,\n} from \"@vitejs/plugin-rsc/browser\";\nimport { hydrateRoot } from \"react-dom/client\";\nimport \"../client/instrumentation-client.js\";\nimport { notifyAppRouterTransitionStart } from \"../client/instrumentation-client-state.js\";\nimport {\n __basePath,\n appRouterInstance,\n commitClientNavigationState,\n consumePrefetchResponse,\n createCachedRscResponseSnapshot,\n createClientNavigationRenderSnapshot,\n getClientNavigationRenderContext,\n getPrefetchCache,\n invalidatePrefetchCache,\n pushHistoryStateWithoutNotify,\n replaceClientParamsWithoutNotify,\n replaceHistoryStateWithoutNotify,\n restoreRscResponse,\n setClientParams,\n setPendingPathname,\n setMountedSlotsHeader,\n setNavigationContext,\n type CachedRscResponse,\n type ClientNavigationRenderSnapshot,\n type PrefetchCacheEntry,\n} from \"vinext/shims/navigation\";\nimport {\n getNavigationRuntime,\n registerNavigationRuntimeBootstrap,\n registerNavigationRuntimeFunctions,\n type NavigationRuntimeNavigate,\n type NavigationRuntimeRscBootstrap,\n} from \"../client/navigation-runtime.js\";\nimport { scrollToHashTargetOnNextFrame } from \"vinext/shims/hash-scroll\";\nimport { installWindowNext } from \"../client/window-next.js\";\nimport {\n chunksToReadableStream,\n createProgressiveRscStream,\n getVinextBrowserGlobal,\n} from \"./app-browser-stream.js\";\nimport {\n createAppBrowserNavigationController,\n clearHardNavigationLoopGuard,\n type HistoryUpdateMode,\n type NavigationPayloadOutcome,\n type PendingBrowserRouterState,\n} from \"./app-browser-navigation-controller.js\";\nimport { resolveManifestNavigationInterceptionContext } from \"./app-browser-interception-context.js\";\nimport {\n createDiscardedServerActionRefreshScheduler,\n createServerActionInitiationSnapshot,\n isServerActionResult,\n parseServerActionRevalidationHeader,\n shouldClearClientNavigationCachesForServerActionResult,\n type ServerActionRevalidationKind,\n type AppBrowserServerActionResult,\n} from \"./app-browser-action-result.js\";\nimport {\n consumeInitialFormState,\n createVinextHydrateRootOptions,\n hydrateRootInTransition,\n} from \"./app-browser-hydration.js\";\nimport {\n AppElementsWire,\n getMountedSlotIdsHeader,\n resolveVisitedResponseInterceptionContext,\n type AppElements,\n type AppWireElements,\n} from \"./app-elements.js\";\nimport {\n FRESH_APP_NAVIGATION_PAYLOAD_ORIGIN,\n VISITED_CACHE_APP_NAVIGATION_PAYLOAD_ORIGIN,\n createHistoryStateWithNavigationMetadata,\n createHistoryStateWithPreviousNextUrl,\n readHistoryStatePreviousNextUrl,\n readHistoryStateTraversalIndex,\n isCacheRestorableAppPayloadMetadata,\n resolveHistoryTraversalIntent,\n resolveInterceptionContextFromPreviousNextUrl,\n resolveServerActionRequestState,\n type AppNavigationPayloadOrigin,\n type AppRouterState,\n type HistoryTraversalIntent,\n type OperationLane,\n} from \"./app-browser-state.js\";\nimport { createPopstateRestoreHandler } from \"./app-browser-popstate.js\";\nimport { DevRecoveryBoundary, RedirectBoundary } from \"vinext/shims/error-boundary\";\nimport { AppRouterContext } from \"vinext/shims/internal/app-router-context\";\nimport { ElementsContext, Slot } from \"vinext/shims/slot\";\nimport type { RouteManifest } from \"../routing/app-route-graph.js\";\nimport { stripBasePath } from \"../utils/base-path.js\";\nimport { createOnUncaughtError } from \"./app-browser-error.js\";\nimport {\n devOnCaughtError,\n devOnUncaughtError,\n dismissOverlay,\n installDevErrorOverlay,\n} from \"./dev-error-overlay.js\";\nimport { DANGEROUS_URL_BLOCK_MESSAGE, isDangerousScheme } from \"vinext/shims/url-safety\";\nimport { throwOnServerActionNotFound } from \"./server-action-not-found.js\";\nimport {\n createRscRequestHeaders,\n createRscRequestUrl,\n getVinextRscCompatibilityId,\n resolveHardNavigationTargetFromRscResponse,\n resolveRscCompatibilityNavigationDecision,\n VINEXT_RSC_COMPATIBILITY_ID_HEADER,\n VINEXT_RSC_CONTENT_TYPE,\n} from \"./app-rsc-cache-busting.js\";\nimport { APP_RSC_RENDER_MODE_REFRESH_PRESERVE_UI } from \"./app-rsc-render-mode.js\";\nimport {\n MAX_RSC_REDIRECT_DEPTH,\n resolveRscRedirectLifecycleHop,\n} from \"./app-browser-rsc-redirect.js\";\nimport {\n createOptimisticRouteTemplate,\n getOptimisticPrefetchSourceKey,\n getOptimisticRouteTemplateKey,\n resolveOptimisticNavigationPayload,\n type OptimisticRouteTemplate,\n} from \"./app-optimistic-routing.js\";\nimport {\n ACTION_REDIRECT_HEADER,\n ACTION_REDIRECT_TYPE_HEADER,\n VINEXT_MOUNTED_SLOTS_HEADER,\n VINEXT_PARAMS_HEADER,\n VINEXT_RSC_REDIRECT_HEADER,\n} from \"./headers.js\";\n\ntype SearchParamInput = ConstructorParameters<typeof URLSearchParams>[0];\n\ntype ServerActionResult = AppBrowserServerActionResult<AppWireElements>;\n\ntype NavigationKind = \"navigate\" | \"traverse\" | \"refresh\";\n\n// Maps NavigationKind to the AppRouterAction type used by the reducer.\n// \"refresh\" is intentionally treated as \"navigate\" (merge, preserve absent slots).\n// Both call sites must stay in sync — update here if NavigationKind gains new values.\nfunction toActionType(kind: NavigationKind): \"navigate\" | \"traverse\" {\n return kind === \"traverse\" ? \"traverse\" : \"navigate\";\n}\n\nfunction toOperationLane(kind: NavigationKind): OperationLane {\n switch (kind) {\n case \"navigate\":\n return \"navigation\";\n case \"refresh\":\n return \"refresh\";\n case \"traverse\":\n return \"traverse\";\n default: {\n const _exhaustive: never = kind;\n throw new Error(\"[vinext] Unknown navigation kind: \" + String(_exhaustive));\n }\n }\n}\n\ntype VisitedResponseCacheEntry = {\n params: Record<string, string | string[]>;\n expiresAt: number;\n response: CachedRscResponse;\n};\n\nconst MAX_VISITED_RESPONSE_CACHE_SIZE = 50;\nconst VISITED_RESPONSE_CACHE_TTL = 5 * 60_000;\nconst MAX_TRAVERSAL_CACHE_TTL = 30 * 60_000;\nconst CLIENT_RSC_COMPATIBILITY_ID = getVinextRscCompatibilityId();\nconst optimisticRouteTemplates = new Map<string, OptimisticRouteTemplate>();\nconst optimisticRouteTemplateSources = new Set<string>();\nconst optimisticRouteTemplateLearning = new Map<string, Promise<void>>();\nfunction getBrowserRouteManifest(): RouteManifest | null {\n return getNavigationRuntime()?.bootstrap.routeManifest ?? null;\n}\n\nconst browserNavigationController = createAppBrowserNavigationController({\n getRouteManifest: getBrowserRouteManifest,\n syncHistoryStatePreviousNextUrl: syncCurrentHistoryStatePreviousNextUrl,\n});\nconst discardedServerActionRefreshScheduler = createDiscardedServerActionRefreshScheduler({\n runRefresh() {\n clearClientNavigationCaches();\n void getNavigationRuntime()?.functions.navigate?.(\n window.location.href,\n 0,\n \"refresh\",\n undefined,\n undefined,\n true,\n );\n },\n});\nconst NavigationCommitSignal = browserNavigationController.NavigationCommitSignal;\n\n// Parses a URI-encoded JSON value carried in a response header (e.g.\n// `X-Vinext-Params`). Returns `null` on missing or malformed input so callers\n// can fall back to their own defaults. Silent by design — these headers are\n// best-effort hydration data and a parse failure should not break navigation.\nfunction parseEncodedJsonHeader<T>(value: string | null): T | null {\n if (!value) return null;\n try {\n return JSON.parse(decodeURIComponent(value)) as T;\n } catch {\n return null;\n }\n}\n\nfunction isRouterStatePromise(\n value: AppRouterState | Promise<AppRouterState>,\n): value is Promise<AppRouterState> {\n return value instanceof Promise;\n}\n\nlet latestClientParams: Record<string, string | string[]> = {};\nconst visitedResponseCache = new Map<string, VisitedResponseCacheEntry>();\n// Sticky bit: stays true once BrowserRoot has committed at least once. Used by\n// the HMR handler to distinguish \"still hydrating\" (wait) from \"was up, then\n// torn down by a render error\" (full reload to recover).\nlet browserRouterStateHasEverCommitted = false;\n// Most recent navigation target that has been dispatched but not yet committed.\n// Read by the onUncaughtError handler so a render error tearing down the tree\n// can land the browser on the URL the user was actually navigating to, instead\n// of stranding them on the previous URL with a blank page. Cleared once the\n// commit effect runs (URL update succeeded) or the navigation is superseded.\nlet pendingNavigationRecoveryHref: string | null = null;\nlet currentHistoryTraversalIndex: number | null =\n readHistoryStateTraversalIndex(window.history.state) ?? 0;\nlet nextHistoryTraversalIndex: number = currentHistoryTraversalIndex;\n\nfunction allocateNavigationHistoryTraversalIndex(\n historyUpdateMode: HistoryUpdateMode | undefined,\n): number | null {\n switch (historyUpdateMode) {\n case \"push\":\n return nextHistoryTraversalIndex + 1;\n case \"replace\":\n return currentHistoryTraversalIndex;\n case undefined:\n return null;\n default: {\n const _exhaustive: never = historyUpdateMode;\n throw new Error(\"[vinext] Unknown history update mode: \" + String(_exhaustive));\n }\n }\n}\n\nfunction commitHistoryTraversalIndex(index: number | null): void {\n currentHistoryTraversalIndex = index;\n if (index !== null) {\n // Keep allocation anchored to the highest app-owned entry we know about.\n // Traversing to metadata-less entries makes the current index unknown, but\n // the next app-owned push should still continue from known app history.\n nextHistoryTraversalIndex = Math.max(nextHistoryTraversalIndex, index);\n }\n}\n\nfunction commitHashOnlyNavigation(\n href: string,\n historyUpdateMode: Exclude<HistoryUpdateMode, undefined>,\n scroll: boolean,\n): void {\n const navigationHistoryIndex = allocateNavigationHistoryTraversalIndex(historyUpdateMode);\n const previousNextUrl = hasBrowserRouterState()\n ? getBrowserRouterState().previousNextUrl\n : readHistoryStatePreviousNextUrl(window.history.state);\n const historyState = createHistoryStateWithNavigationMetadata(\n createHashOnlyNavigationBaseHistoryState(historyUpdateMode, scroll),\n {\n previousNextUrl,\n traversalIndex: navigationHistoryIndex,\n },\n );\n\n if (historyUpdateMode === \"replace\") {\n replaceHistoryStateWithoutNotify(historyState, \"\", href);\n } else {\n pushHistoryStateWithoutNotify(historyState, \"\", href);\n }\n commitHistoryTraversalIndex(navigationHistoryIndex);\n}\n\nfunction createHashOnlyNavigationBaseHistoryState(\n historyUpdateMode: Exclude<HistoryUpdateMode, undefined>,\n scroll: boolean,\n): unknown {\n if (historyUpdateMode !== \"replace\") {\n return null;\n }\n return scroll ? stripVinextScrollState(window.history.state) : window.history.state;\n}\n\nfunction stripVinextScrollState(state: unknown): unknown {\n if (!state || typeof state !== \"object\") {\n return state;\n }\n\n const nextState: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(state)) {\n if (key === \"__vinext_scrollX\" || key === \"__vinext_scrollY\") {\n continue;\n }\n nextState[key] = value;\n }\n\n return Object.keys(nextState).length > 0 ? nextState : null;\n}\n\nfunction commitTraversalIndexFromHistoryState(historyState: unknown): void {\n commitHistoryTraversalIndex(readHistoryStateTraversalIndex(historyState));\n}\n\nfunction getBrowserRouterState(): AppRouterState {\n return browserNavigationController.getBrowserRouterState();\n}\n\nfunction hasBrowserRouterState(): boolean {\n return browserNavigationController.hasBrowserRouterState();\n}\n\nfunction waitForBrowserRouterStateReady(): Promise<void> {\n return browserNavigationController.waitForBrowserRouterStateReady();\n}\n\nfunction beginPendingBrowserRouterState(): PendingBrowserRouterState {\n return browserNavigationController.beginPendingBrowserRouterState();\n}\n\nfunction applyClientParams(params: Record<string, string | string[]>): void {\n latestClientParams = params;\n setClientParams(params);\n}\n\nfunction stageClientParams(params: Record<string, string | string[]>): void {\n // NB: latestClientParams diverges from ClientNavigationState.clientParams\n // between staging and commit. Server action snapshots capture the committed\n // browser router state at invocation time, so they do not read this mutable\n // module-level value after their async request boundary.\n latestClientParams = params;\n replaceClientParamsWithoutNotify(params);\n}\n\nfunction clearVisitedResponseCache(): void {\n visitedResponseCache.clear();\n}\n\nfunction clearPrefetchState(): void {\n invalidatePrefetchCache();\n optimisticRouteTemplates.clear();\n optimisticRouteTemplateSources.clear();\n optimisticRouteTemplateLearning.clear();\n}\n\nfunction clearClientNavigationCaches(): void {\n clearVisitedResponseCache();\n clearPrefetchState();\n}\n\nfunction isSettledPrefetchCacheEntry(\n entry: PrefetchCacheEntry,\n): entry is PrefetchCacheEntry & { snapshot: CachedRscResponse } {\n return (\n entry.outcome === \"cache-seeded\" && entry.pending === undefined && entry.snapshot !== undefined\n );\n}\n\nfunction parsePrefetchCacheKey(cacheKey: string): {\n interceptionContext: string | null;\n rscUrl: string;\n} {\n const separatorIndex = cacheKey.indexOf(\"\\0\");\n if (separatorIndex === -1) {\n return { interceptionContext: null, rscUrl: cacheKey };\n }\n return {\n interceptionContext: cacheKey.slice(separatorIndex + 1),\n rscUrl: cacheKey.slice(0, separatorIndex),\n };\n}\n\nasync function learnOptimisticRouteTemplateFromPrefetch(options: {\n cacheKey: string;\n entry: PrefetchCacheEntry & { snapshot: CachedRscResponse };\n interceptionContext: string | null;\n mountedSlotsHeader: string | null;\n routeManifest: RouteManifest;\n}): Promise<boolean> {\n const source = parsePrefetchCacheKey(options.cacheKey);\n if (source.interceptionContext !== options.interceptionContext) return false;\n if ((options.entry.snapshot.mountedSlotsHeader ?? null) !== options.mountedSlotsHeader)\n return false;\n if (options.interceptionContext !== null) return false;\n\n const elements = await decodeAppElementsPromise(\n createFromFetch<AppWireElements>(Promise.resolve(restoreRscResponse(options.entry.snapshot))),\n );\n const template = createOptimisticRouteTemplate({\n allowLoadingShell: options.entry.optimisticRouteShell === true,\n basePath: __basePath,\n elements,\n href: options.entry.snapshot.url || source.rscUrl,\n interceptionContext: options.interceptionContext,\n mountedSlotsHeader: options.mountedSlotsHeader,\n routeManifest: options.routeManifest,\n });\n if (template === null) return false;\n\n optimisticRouteTemplates.set(\n getOptimisticRouteTemplateKey({\n interceptionContext: options.interceptionContext,\n mountedSlotsHeader: options.mountedSlotsHeader,\n routeId: template.routeId,\n }),\n template,\n );\n return true;\n}\n\nasync function learnOptimisticRouteTemplatesFromPrefetchCache(options: {\n interceptionContext: string | null;\n mountedSlotsHeader: string | null;\n routeManifest: RouteManifest | null;\n}): Promise<void> {\n if (options.routeManifest === null) return;\n\n const learning: Promise<void>[] = [...optimisticRouteTemplateLearning.values()];\n for (const [cacheKey, entry] of getPrefetchCache()) {\n const sourceKey = getOptimisticPrefetchSourceKey({\n cacheKey,\n interceptionContext: options.interceptionContext,\n mountedSlotsHeader: options.mountedSlotsHeader,\n });\n if (optimisticRouteTemplateSources.has(sourceKey)) continue;\n if (optimisticRouteTemplateLearning.has(sourceKey)) continue;\n if (!isSettledPrefetchCacheEntry(entry)) continue;\n\n const promise = learnOptimisticRouteTemplateFromPrefetch({\n cacheKey,\n entry,\n interceptionContext: options.interceptionContext,\n mountedSlotsHeader: options.mountedSlotsHeader,\n routeManifest: options.routeManifest,\n })\n .then((learned) => {\n if (learned) optimisticRouteTemplateSources.add(sourceKey);\n })\n .finally(() => {\n optimisticRouteTemplateLearning.delete(sourceKey);\n });\n optimisticRouteTemplateLearning.set(sourceKey, promise);\n learning.push(promise);\n }\n\n if (learning.length === 0) return;\n await Promise.allSettled(learning);\n}\n\nfunction syncCurrentHistoryStatePreviousNextUrl(previousNextUrl: string | null): void {\n if (readHistoryStatePreviousNextUrl(window.history.state) === previousNextUrl) {\n return;\n }\n\n const nextHistoryState = createHistoryStateWithPreviousNextUrl(\n window.history.state,\n previousNextUrl,\n );\n // First attempt: use replaceHistoryStateWithoutNotify which fires no popstate\n // or hashchange events. If the browser accepted the state update (checked via\n // readHistoryStatePreviousNextUrl), we're done. The double-read is needed\n // because some browsers (notably Safari) can silently coalesce or ignore\n // replaceState calls when called in rapid succession (e.g. back-to-back\n // navigation commits). The fallback fires only when the state didn't stick.\n replaceHistoryStateWithoutNotify(nextHistoryState, \"\", window.location.href);\n if (readHistoryStatePreviousNextUrl(window.history.state) === previousNextUrl) {\n return;\n }\n window.history.replaceState(nextHistoryState, \"\", window.location.href);\n}\n\nfunction createActionInitiationSnapshot() {\n const routerState = getBrowserRouterState();\n return createServerActionInitiationSnapshot({\n href: window.location.href,\n navigationId: browserNavigationController.getActiveNavigationId(),\n routerState,\n });\n}\n\ntype ActionInitiationSnapshot = ReturnType<typeof createActionInitiationSnapshot>;\n\nfunction createNavigationCommitEffect(options: {\n href: string;\n historyUpdateMode: HistoryUpdateMode | undefined;\n navId: number;\n params: Record<string, string | string[]>;\n previousNextUrl: string | null;\n targetHistoryIndex?: number | null;\n}): () => void {\n const { href, historyUpdateMode, navId, params, previousNextUrl, targetHistoryIndex } = options;\n\n return () => {\n // Only update URL if this is still the active navigation.\n // A newer navigation would have superseded this navigation id.\n if (!browserNavigationController.isCurrentNavigation(navId)) {\n // This transition was superseded before commit; balance the active\n // snapshot counter without clearing pendingPathname ownership.\n commitClientNavigationState(undefined, { releaseSnapshot: true });\n return;\n }\n\n const targetHref = new URL(href, window.location.origin).href;\n const preserveExistingState = historyUpdateMode === \"replace\";\n const navigationHistoryIndex =\n targetHistoryIndex !== undefined\n ? targetHistoryIndex\n : allocateNavigationHistoryTraversalIndex(historyUpdateMode);\n const historyState = createHistoryStateWithNavigationMetadata(\n preserveExistingState ? window.history.state : null,\n {\n previousNextUrl,\n traversalIndex: navigationHistoryIndex,\n },\n );\n\n let wroteHistoryState = false;\n if (historyUpdateMode === \"replace\" && window.location.href !== targetHref) {\n stageClientParams(params);\n replaceHistoryStateWithoutNotify(historyState, \"\", href);\n wroteHistoryState = true;\n commitHistoryTraversalIndex(navigationHistoryIndex);\n } else if (historyUpdateMode === \"push\" && window.location.href !== targetHref) {\n stageClientParams(params);\n pushHistoryStateWithoutNotify(historyState, \"\", href);\n wroteHistoryState = true;\n commitHistoryTraversalIndex(navigationHistoryIndex);\n }\n\n if (!wroteHistoryState) {\n syncCurrentHistoryStatePreviousNextUrl(previousNextUrl);\n stageClientParams(params);\n if (targetHistoryIndex !== undefined) {\n commitHistoryTraversalIndex(targetHistoryIndex);\n }\n }\n\n // URL has been updated; the recovery hard-nav target is no longer needed.\n pendingNavigationRecoveryHref = null;\n commitClientNavigationState(navId);\n };\n}\n\nasync function renderNavigationPayload(\n payload: Promise<AppElements>,\n navigationSnapshot: ClientNavigationRenderSnapshot,\n targetHref: string,\n navId: number,\n historyUpdateMode: HistoryUpdateMode | undefined,\n params: Record<string, string | string[]>,\n previousNextUrl: string | null,\n pendingRouterState: PendingBrowserRouterState | null,\n payloadOrigin: AppNavigationPayloadOrigin,\n actionType: \"navigate\" | \"replace\" | \"traverse\" = \"navigate\",\n operationLane: OperationLane = \"navigation\",\n traversalIntent: HistoryTraversalIntent | null = null,\n): Promise<NavigationPayloadOutcome> {\n try {\n return await browserNavigationController.renderNavigationPayload({\n actionType,\n createNavigationCommitEffect: (options) => {\n pendingNavigationRecoveryHref = options.href;\n return createNavigationCommitEffect(options);\n },\n historyUpdateMode,\n navigationSnapshot,\n nextElements: payload,\n operationLane,\n payloadOrigin,\n params,\n pendingRouterState,\n previousNextUrl,\n targetHistoryIndex: traversalIntent === null ? undefined : traversalIntent.targetHistoryIndex,\n targetHref,\n navId,\n });\n } catch (error) {\n pendingNavigationRecoveryHref = null;\n throw error;\n }\n}\n\nasync function commitSameUrlNavigatePayload(\n nextElements: Promise<AppElements>,\n actionInitiation: ActionInitiationSnapshot,\n returnValue?: ServerActionResult[\"returnValue\"],\n revalidation: ServerActionRevalidationKind = \"none\",\n): Promise<unknown> {\n const navigationSnapshot = createClientNavigationRenderSnapshot(\n actionInitiation.href,\n actionInitiation.routerState.navigationSnapshot.params,\n );\n return browserNavigationController.commitSameUrlNavigatePayload(\n nextElements,\n navigationSnapshot,\n returnValue,\n actionInitiation.routerState,\n {\n onDiscardedRevalidation() {\n discardedServerActionRefreshScheduler.schedule();\n },\n revalidation,\n startedNavigationId: actionInitiation.navigationId,\n targetHref: actionInitiation.href,\n },\n );\n}\n\nfunction evictVisitedResponseCacheIfNeeded(): void {\n while (visitedResponseCache.size >= MAX_VISITED_RESPONSE_CACHE_SIZE) {\n const oldest = visitedResponseCache.keys().next().value;\n if (oldest === undefined) {\n return;\n }\n visitedResponseCache.delete(oldest);\n }\n}\n\nfunction getVisitedResponse(\n rscUrl: string,\n interceptionContext: string | null,\n mountedSlotsHeader: string | null,\n navigationKind: NavigationKind,\n): VisitedResponseCacheEntry | null {\n const cacheKey = AppElementsWire.encodeCacheKey(rscUrl, interceptionContext);\n const cached = visitedResponseCache.get(cacheKey);\n if (!cached) {\n return null;\n }\n\n if ((cached.response.mountedSlotsHeader ?? null) !== mountedSlotsHeader) {\n visitedResponseCache.delete(cacheKey);\n return null;\n }\n\n if (navigationKind === \"refresh\") {\n return null;\n }\n\n if (navigationKind === \"traverse\") {\n const createdAt = cached.expiresAt - VISITED_RESPONSE_CACHE_TTL;\n if (Date.now() - createdAt >= MAX_TRAVERSAL_CACHE_TTL) {\n visitedResponseCache.delete(cacheKey);\n return null;\n }\n // LRU: promote to most-recently-used (delete + re-insert moves to end of Map)\n visitedResponseCache.delete(cacheKey);\n visitedResponseCache.set(cacheKey, cached);\n return cached;\n }\n\n if (cached.expiresAt > Date.now()) {\n // LRU: promote to most-recently-used\n visitedResponseCache.delete(cacheKey);\n visitedResponseCache.set(cacheKey, cached);\n return cached;\n }\n\n visitedResponseCache.delete(cacheKey);\n return null;\n}\n\nfunction storeVisitedResponseSnapshot(\n rscUrl: string,\n interceptionContext: string | null,\n snapshot: CachedRscResponse,\n params: Record<string, string | string[]>,\n): void {\n const cacheKey = AppElementsWire.encodeCacheKey(rscUrl, interceptionContext);\n visitedResponseCache.delete(cacheKey);\n evictVisitedResponseCacheIfNeeded();\n const now = Date.now();\n visitedResponseCache.set(cacheKey, {\n params,\n expiresAt: now + VISITED_RESPONSE_CACHE_TTL,\n response: snapshot,\n });\n}\n\ntype NavigationRequestState = {\n interceptionContext: string | null;\n previousNextUrl: string | null;\n};\n\nfunction getRequestState(\n navigationKind: NavigationKind,\n targetPathname: string,\n previousNextUrlOverride?: string | null,\n traverseHistoryState?: unknown,\n): NavigationRequestState {\n if (previousNextUrlOverride !== undefined) {\n return {\n interceptionContext: resolveInterceptionContextFromPreviousNextUrl(\n previousNextUrlOverride,\n __basePath,\n ),\n previousNextUrl: previousNextUrlOverride,\n };\n }\n\n // Three branches for \"navigate\":\n // 1. previousNextUrl !== null → a committed intercepted navigation set this\n // in browser state (requires proof). This is the proven interception path.\n // 2. route manifest declares current URL can intercept target URL → ask the\n // server for an intercepted payload using manifest route facts only.\n // 3. otherwise, send no interception context.\n switch (navigationKind) {\n case \"navigate\": {\n const currentPreviousNextUrl = getBrowserRouterState().previousNextUrl;\n if (currentPreviousNextUrl !== null) {\n return {\n interceptionContext: resolveInterceptionContextFromPreviousNextUrl(\n currentPreviousNextUrl,\n __basePath,\n ),\n previousNextUrl: currentPreviousNextUrl,\n };\n }\n const manifestInterceptionContext = resolveManifestNavigationInterceptionContext({\n basePath: __basePath,\n currentPathname: window.location.pathname,\n routeManifest: getBrowserRouteManifest(),\n targetPathname,\n });\n if (manifestInterceptionContext !== null) {\n return {\n interceptionContext: manifestInterceptionContext,\n previousNextUrl: window.location.pathname + window.location.search,\n };\n }\n return {\n interceptionContext: null,\n previousNextUrl: null,\n };\n }\n case \"traverse\": {\n const previousNextUrl = readHistoryStatePreviousNextUrl(\n traverseHistoryState ?? window.history.state,\n );\n return {\n interceptionContext: resolveInterceptionContextFromPreviousNextUrl(\n previousNextUrl,\n __basePath,\n ),\n previousNextUrl,\n };\n }\n case \"refresh\": {\n const currentPreviousNextUrl = getBrowserRouterState().previousNextUrl;\n return {\n interceptionContext: resolveInterceptionContextFromPreviousNextUrl(\n currentPreviousNextUrl,\n __basePath,\n ),\n previousNextUrl: currentPreviousNextUrl,\n };\n }\n default: {\n const _exhaustive: never = navigationKind;\n throw new Error(\"[vinext] Unknown navigation kind: \" + String(_exhaustive));\n }\n }\n}\n\n// Dev-only callback invoked when DevRecoveryBoundary catches. The replaced\n// subtree means NavigationCommitSignal's useLayoutEffect never fires, so the\n// URL update for the in-flight navigation would otherwise be lost. Force-drain\n// the queued pre-paint effect for this renderId so the URL still moves to the\n// navigation target, the dev overlay shows which URL is broken, and HMR's\n// rsc:update fetches the right payload after the bug is fixed.\nfunction handleDevRecoveryBoundaryCatch(resetKey: number): void {\n // React's onCaughtError option already routes the error to the dev overlay.\n // Our job here is purely to drive the URL update for the in-flight\n // navigation that this failed render belonged to.\n browserNavigationController.drainPrePaintEffects(resetKey);\n}\n\nfunction decodeAppElementsPromise(payload: Promise<AppWireElements>): Promise<AppElements> {\n // Wrap in Promise.resolve() because createFromReadableStream() returns a\n // React Flight thenable whose .then() returns undefined (not a new Promise).\n // Without the wrap, chaining .then() produces undefined → use() crashes.\n return Promise.resolve(payload).then((elements) => AppElementsWire.decode(elements));\n}\n\nfunction BrowserRoot({\n initialElements,\n initialNavigationSnapshot,\n}: {\n initialElements: Promise<AppElements>;\n initialNavigationSnapshot: ClientNavigationRenderSnapshot;\n}) {\n const resolvedElements = use(initialElements);\n const initialMetadata = AppElementsWire.readMetadata(resolvedElements);\n const [treeStateValue, setTreeStateValue] = useState<AppRouterState | Promise<AppRouterState>>({\n activeOperation: null,\n elements: resolvedElements,\n interception: initialMetadata.interception,\n interceptionContext: initialMetadata.interceptionContext,\n layoutIds: initialMetadata.layoutIds,\n layoutFlags: initialMetadata.layoutFlags,\n navigationSnapshot: initialNavigationSnapshot,\n previousNextUrl: null,\n renderId: 0,\n rootLayoutTreePath: initialMetadata.rootLayoutTreePath,\n routeId: initialMetadata.routeId,\n slotBindings: initialMetadata.slotBindings,\n visibleCommitVersion: 0,\n });\n const treeState = isRouterStatePromise(treeStateValue) ? use(treeStateValue) : treeStateValue;\n\n // Keep the latest router state in a ref so external callers (navigate(),\n // server actions, HMR) always read the current state. Safe: those readers\n // run from events/effects, never from React render itself.\n // Note: stateRef.current is written during render, not in an effect, to\n // avoid a stale-read window between commit and layout effects. This mirrors\n // the same render-phase ref update pattern used by Next.js's own router.\n const stateRef = useRef(treeState);\n stateRef.current = treeState;\n\n // Publish the stable ref object and dispatch during layout commit. This keeps\n // the module-level escape hatches aligned with React's committed tree without\n // performing module writes during render. The navigation runtime is registered\n // after hydrateRoot() returns; by then this layout effect has already run for\n // the hydration commit, so getBrowserRouterState() never observes a null ref.\n useLayoutEffect(() => {\n const detach = browserNavigationController.attachBrowserRouterState(\n setTreeStateValue,\n stateRef,\n );\n browserRouterStateHasEverCommitted = true;\n // App Router uses this timestamp as first committed tree readiness: the\n // browser router state is attached and link/router interactions can safely\n // observe the committed tree. It is intentionally later than hydrateRoot()\n // returning.\n const hydratedAt = performance.now();\n window.__VINEXT_HYDRATED_AT = hydratedAt;\n window.__NEXT_HYDRATED = true;\n window.__NEXT_HYDRATED_AT = hydratedAt;\n window.__NEXT_HYDRATED_CB?.();\n return () => {\n detach();\n setMountedSlotsHeader(null);\n };\n }, [setTreeStateValue]);\n\n useLayoutEffect(() => {\n setMountedSlotsHeader(getMountedSlotIdsHeader(stateRef.current.elements));\n getNavigationRuntime()?.functions.pingVisibleLinks?.();\n }, [treeState.elements]);\n\n useLayoutEffect(() => {\n if (treeState.renderId !== 0) {\n return;\n }\n\n replaceHistoryStateWithoutNotify(\n createHistoryStateWithNavigationMetadata(window.history.state, {\n previousNextUrl: treeState.previousNextUrl,\n traversalIndex: currentHistoryTraversalIndex,\n }),\n \"\",\n window.location.href,\n );\n }, [treeState.previousNextUrl, treeState.renderId]);\n\n const routeTree = createElement(\n RedirectBoundary,\n null,\n createElement(\n NavigationCommitSignal,\n { renderId: treeState.renderId },\n createElement(\n ElementsContext.Provider,\n { value: treeState.elements },\n createElement(Slot, { id: treeState.routeId }),\n ),\n ),\n );\n const innerTree = AppRouterContext\n ? createElement(AppRouterContext.Provider, { value: appRouterInstance }, routeTree)\n : routeTree;\n\n // In dev, wrap the route tree in a top-level recovery boundary. A render\n // error (e.g. a slot's RSC reference rejects) is caught here instead of\n // tearing down BrowserRoot, so HMR can dispatch the next payload —\n // identified by an incremented renderId, which doubles as the boundary's\n // reset key — without a full page reload. The dev overlay (a separate\n // React root) shows the error itself.\n //\n // onCatch drains the pending pre-paint effect for the failed render so\n // the URL update bound to that navigation still runs. Without this, a\n // soft-nav whose target throws would leave the browser on the previous\n // URL, hiding which route is broken and mis-targeting the next HMR\n // payload (which fetches RSC for window.location.pathname).\n //\n // This file is .ts, not .tsx — children are passed positionally to satisfy\n // both the createElement overload and eslint's no-children-prop rule.\n const committedTree = import.meta.env.DEV\n ? createElement(\n DevRecoveryBoundary,\n {\n resetKey: treeState.renderId,\n onCatch: handleDevRecoveryBoundaryCatch,\n },\n innerTree,\n )\n : innerTree;\n\n const ClientNavigationRenderContext = getClientNavigationRenderContext();\n if (!ClientNavigationRenderContext) {\n return committedTree;\n }\n\n return createElement(\n ClientNavigationRenderContext.Provider,\n { value: treeState.navigationSnapshot },\n committedTree,\n );\n}\n\nfunction restoreHydrationNavigationContext(\n pathname: string,\n searchParams: SearchParamInput,\n params: Record<string, string | string[]>,\n): void {\n setNavigationContext({\n pathname,\n searchParams: new URLSearchParams(searchParams),\n params,\n });\n}\n\nfunction restorePopstateScrollPosition(state: unknown): void {\n if (!(state && typeof state === \"object\" && \"__vinext_scrollY\" in state)) {\n if (window.location.hash) {\n scrollToHashTargetOnNextFrame(window.location.hash);\n }\n return;\n }\n\n const y = Number(state.__vinext_scrollY);\n const x = \"__vinext_scrollX\" in state ? Number(state.__vinext_scrollX) : 0;\n\n requestAnimationFrame(() => {\n window.scrollTo(x, y);\n });\n}\n\nfunction isSameAppRoutePopstateTarget(href: string): boolean {\n if (!hasBrowserRouterState()) return false;\n\n const target = new URL(href, window.location.origin);\n const routerState = getBrowserRouterState();\n const targetPathname = stripBasePath(target.pathname, __basePath);\n const targetSearch = new URLSearchParams(target.search).toString();\n const currentSearch = routerState.navigationSnapshot.searchParams.toString();\n\n return (\n targetPathname === routerState.navigationSnapshot.pathname && targetSearch === currentSearch\n );\n}\n\n// Set on pagehide so the RSC navigation catch block can distinguish expected\n// fetch aborts (triggered by the unload itself) from real errors worth logging.\nlet isPageUnloading = false;\n\nconst RSC_RELOAD_KEY = \"__vinext_rsc_initial_reload__\";\n\n// sessionStorage can throw SecurityError in strict-mode iframes, storage-\n// disabled browsers, and some Safari private-browsing configurations. Wrap\n// every access so a recovery path for one error does not crash hydration.\nfunction readReloadFlag(): string | null {\n try {\n return sessionStorage.getItem(RSC_RELOAD_KEY);\n } catch {\n return null;\n }\n}\nfunction writeReloadFlag(path: string): void {\n try {\n sessionStorage.setItem(RSC_RELOAD_KEY, path);\n } catch {}\n}\nfunction clearReloadFlag(): void {\n try {\n sessionStorage.removeItem(RSC_RELOAD_KEY);\n } catch {}\n}\n\n// A non-ok or wrong-content-type RSC response during initial hydration means\n// the server cannot deliver a valid RSC payload for this URL. Parsing the\n// response as RSC causes an opaque parse failure. On the first attempt,\n// reload once so the server has a chance to render the correct error page\n// as HTML. On the second attempt (detected via the sessionStorage flag), the\n// endpoint is persistently broken. Returns null so main() aborts the\n// hydration bootstrap without registering RSC navigation globals —\n// including during the brief window between reload() firing and the page\n// actually unloading — so external probes never see a half-hydrated page.\nfunction recoverFromBadInitialRscResponse(reason: string): null {\n const currentPath = window.location.pathname + window.location.search;\n if (readReloadFlag() === currentPath) {\n clearReloadFlag();\n console.error(\n `[vinext] Initial RSC fetch ${reason} after reload; aborting hydration. ` +\n \"Server-rendered HTML remains visible; client components will not hydrate.\",\n );\n return null;\n }\n writeReloadFlag(currentPath);\n // Verify the write persisted. In storage-denied environments (strict-mode\n // iframes, locked-down enterprise policies), every getItem returns null and\n // every setItem silently no-ops, so the reload-loop guard cannot survive\n // the reload — the page would loop forever. Abort instead so the user at\n // least sees the server-rendered HTML.\n if (readReloadFlag() !== currentPath) {\n console.error(\n `[vinext] Initial RSC fetch ${reason}; sessionStorage unavailable so the ` +\n \"reload-loop guard cannot persist — aborting hydration. \" +\n \"Server-rendered HTML remains visible; client components will not hydrate.\",\n );\n return null;\n }\n // One-shot diagnostic so a production reload is traceable. Only fires once\n // per broken path thanks to the sessionStorage flag above; not noisy.\n console.warn(\n `[vinext] Initial RSC fetch ${reason}; reloading once to let the server render the HTML error page`,\n );\n window.location.reload();\n return null;\n}\n\nasync function readInitialRscStream(): Promise<ReadableStream<Uint8Array> | null> {\n const vinext = getVinextBrowserGlobal();\n const runtimeRsc = getNavigationRuntime()?.bootstrap.rsc;\n\n if (runtimeRsc || vinext.__VINEXT_RSC_CHUNKS__ || vinext.__VINEXT_RSC_DONE__) {\n // Reaching the embedded-RSC branch means the server successfully rendered\n // the page — any prior reload flag for this path is stale and must be\n // cleared so a future failure gets its own fresh recovery attempt.\n clearReloadFlag();\n clearHardNavigationLoopGuard();\n\n if (runtimeRsc) {\n applyRuntimeRscBootstrap(runtimeRsc);\n if (runtimeRsc.done) {\n registerNavigationRuntimeBootstrap({ rsc: undefined });\n return chunksToReadableStream(runtimeRsc.rsc);\n }\n // The progressive stream must capture this bootstrap object before any\n // cleanup clears it from the runtime.\n return createProgressiveRscStream();\n }\n\n const params = vinext.__VINEXT_RSC_PARAMS__ ?? {};\n if (vinext.__VINEXT_RSC_PARAMS__) {\n applyClientParams(vinext.__VINEXT_RSC_PARAMS__);\n }\n if (vinext.__VINEXT_RSC_NAV__) {\n restoreHydrationNavigationContext(\n vinext.__VINEXT_RSC_NAV__.pathname,\n vinext.__VINEXT_RSC_NAV__.searchParams,\n params,\n );\n }\n\n return createProgressiveRscStream();\n }\n\n const rscHeaders = createRscRequestHeaders();\n const rscResponse = await fetch(\n await createRscRequestUrl(window.location.pathname + window.location.search, rscHeaders),\n { credentials: \"include\", headers: rscHeaders },\n );\n\n if (!rscResponse.ok) {\n return recoverFromBadInitialRscResponse(`returned ${rscResponse.status}`);\n }\n // Guard against proxies/CDNs that return 200 with a rewritten Content-Type\n // (e.g. text/html instead of text/x-component). Such responses cannot be\n // parsed as RSC and would throw the same opaque parse error this fallback\n // exists to prevent.\n const contentType = rscResponse.headers.get(\"content-type\") ?? \"\";\n if (!contentType.startsWith(VINEXT_RSC_CONTENT_TYPE)) {\n return recoverFromBadInitialRscResponse(\n `returned non-RSC content-type \"${contentType || \"(missing)\"}\"`,\n );\n }\n // Missing body (e.g. 204 No Content, or an edge worker that returned ok\n // headers without piping the stream) fails the same way downstream.\n // Matches Next.js' `!res.body` branch in fetch-server-response.ts.\n if (!rscResponse.body) {\n return recoverFromBadInitialRscResponse(\"returned empty body\");\n }\n // Successful RSC response clears the guard so a subsequent reload of the\n // same path after a transient failure still gets one recovery attempt.\n clearReloadFlag();\n clearHardNavigationLoopGuard();\n\n // Ignore malformed param headers and continue with hydration. The original\n // try/catch also swallowed errors from applyClientParams; preserve that.\n const parsedParams = parseEncodedJsonHeader<Record<string, string | string[]>>(\n rscResponse.headers.get(VINEXT_PARAMS_HEADER),\n );\n const params: Record<string, string | string[]> = parsedParams ?? {};\n if (parsedParams) {\n try {\n applyClientParams(parsedParams);\n } catch {\n // Ignore — matches the previous combined try/catch behavior.\n }\n }\n\n restoreHydrationNavigationContext(window.location.pathname, window.location.search, params);\n\n return rscResponse.body;\n}\n\nfunction applyRuntimeRscBootstrap(rsc: NavigationRuntimeRscBootstrap): void {\n const params = rsc.params ?? {};\n if (rsc.params) {\n applyClientParams(rsc.params);\n }\n if (rsc.nav) {\n restoreHydrationNavigationContext(rsc.nav.pathname, rsc.nav.searchParams, params);\n }\n}\n\nfunction registerServerActionCallback(): void {\n setServerCallback(async (id, args) => {\n const temporaryReferences = createTemporaryReferenceSet();\n\n // Carry the interception context + mounted slots from the current router\n // state so the server-action re-render rebuilds the intercepted tree\n // instead of replacing it with the direct page. Parity with Next.js,\n // which sends `Next-URL` on action POSTs when the current tree contains\n // an interception route.\n const actionInitiation = createActionInitiationSnapshot();\n // Keep history aligned with the captured snapshot. Action POST headers\n // read from actionInitiation, not from history, after this point.\n syncCurrentHistoryStatePreviousNextUrl(actionInitiation.routerState.previousNextUrl);\n const body = await encodeReply(args, { temporaryReferences });\n const { headers } = resolveServerActionRequestState({\n actionId: id,\n basePath: __basePath,\n elements: actionInitiation.routerState.elements,\n previousNextUrl: actionInitiation.routerState.previousNextUrl,\n });\n\n const fetchResponse = await fetch(await createRscRequestUrl(actionInitiation.path, headers), {\n method: \"POST\",\n headers,\n body,\n });\n\n // Surface an `UnrecognizedActionError` so client `catch` blocks can detect\n // client/server deployment skew via `unstable_isUnrecognizedActionError`.\n throwOnServerActionNotFound(fetchResponse, id);\n\n const actionRedirect = fetchResponse.headers.get(ACTION_REDIRECT_HEADER);\n if (actionRedirect) {\n if (isDangerousScheme(actionRedirect)) {\n console.error(DANGEROUS_URL_BLOCK_MESSAGE);\n return undefined;\n }\n\n // Check for external URLs that need a hard redirect.\n try {\n const redirectUrl = new URL(actionRedirect, window.location.origin);\n if (redirectUrl.origin !== window.location.origin) {\n browserNavigationController.performHardNavigation(actionRedirect);\n return undefined;\n }\n } catch {\n // Fall through to hard redirect below if URL parsing fails.\n }\n\n // Use hard redirect for all action redirects because vinext's server\n // currently returns an empty body for redirect responses. RSC navigation\n // requires a valid RSC payload. This is a known parity gap with Next.js,\n // which pre-renders the redirect target's RSC payload.\n clearClientNavigationCaches();\n const redirectType = fetchResponse.headers.get(ACTION_REDIRECT_TYPE_HEADER) ?? \"replace\";\n if (redirectType === \"push\") {\n browserNavigationController.performHardNavigation(actionRedirect, \"assign\");\n } else {\n browserNavigationController.performHardNavigation(actionRedirect, \"replace\");\n }\n return undefined;\n }\n\n if (\n resolveRscCompatibilityNavigationDecision({\n clientCompatibilityId: CLIENT_RSC_COMPATIBILITY_ID,\n currentHref: actionInitiation.href,\n origin: window.location.origin,\n responseCompatibilityId: fetchResponse.headers.get(VINEXT_RSC_COMPATIBILITY_ID_HEADER),\n responseUrl: fetchResponse.url,\n }).kind === \"hard-navigate\"\n ) {\n browserNavigationController.performHardNavigation(actionInitiation.href);\n return undefined;\n }\n\n const revalidation = parseServerActionRevalidationHeader(fetchResponse.headers);\n const result = await createFromFetch<ServerActionResult | AppWireElements>(\n Promise.resolve(fetchResponse),\n { temporaryReferences },\n );\n if (shouldClearClientNavigationCachesForServerActionResult(result, revalidation)) {\n clearClientNavigationCaches();\n }\n\n // Server actions stay on the same URL and use commitSameUrlNavigatePayload()\n // for merge-based dispatch. This path does not call\n // activateNavigationSnapshot() because there is no URL change to commit, so\n // hooks continue reading the live external-store values directly. If server\n // actions ever trigger URL changes via RSC payload (instead of hard\n // redirects), this would need renderNavigationPayload().\n if (isServerActionResult(result)) {\n if (result.root !== undefined) {\n return commitSameUrlNavigatePayload(\n Promise.resolve(AppElementsWire.decode(result.root)),\n actionInitiation,\n result.returnValue,\n revalidation,\n );\n }\n\n if (result.returnValue) {\n if (!result.returnValue.ok) {\n throw result.returnValue.data;\n }\n return result.returnValue.data;\n }\n\n return undefined;\n }\n\n return commitSameUrlNavigatePayload(\n Promise.resolve(AppElementsWire.decode(result)),\n actionInitiation,\n undefined,\n revalidation,\n );\n });\n}\n\nasync function main(): Promise<void> {\n registerServerActionCallback();\n\n const rscStream = await readInitialRscStream();\n // null signals that readInitialRscStream aborted hydration — either because\n // a reload is in flight (first-attempt recovery) or the endpoint is\n // persistently broken (post-reload). Bootstrap is a separate synchronous\n // helper so the null-branch structurally cannot reach any RSC bootstrap\n // global assignment, even if a future refactor interposes async work here.\n if (rscStream === null) return;\n bootstrapHydration(rscStream);\n}\n\nfunction bootstrapHydration(rscStream: ReadableStream<Uint8Array>): void {\n if (import.meta.env.DEV) {\n installDevErrorOverlay();\n }\n\n const root = decodeAppElementsPromise(createFromReadableStream<AppWireElements>(rscStream));\n const initialNavigationSnapshot = createClientNavigationRenderSnapshot(\n window.location.href,\n latestClientParams,\n );\n replaceHistoryStateWithoutNotify(\n createHistoryStateWithNavigationMetadata(window.history.state, {\n previousNextUrl: null,\n traversalIndex: currentHistoryTraversalIndex,\n }),\n \"\",\n window.location.href,\n );\n\n // In dev we route uncaught errors into the dev overlay rather than the\n // hard-nav recovery: the overlay is what the developer needs to see, and a\n // recovery nav would wipe it. In prod we keep the recovery hard-nav so the\n // user lands on a renderable URL with the actual error UI.\n const onUncaughtError = import.meta.env.DEV\n ? devOnUncaughtError\n : createOnUncaughtError(() => pendingNavigationRecoveryHref);\n const formState = consumeInitialFormState(getVinextBrowserGlobal());\n const hydrateRootOptions = import.meta.env.DEV\n ? createVinextHydrateRootOptions({\n formState,\n onCaughtError: devOnCaughtError,\n onUncaughtError,\n })\n : createVinextHydrateRootOptions({\n formState,\n onUncaughtError,\n });\n window.__VINEXT_RSC_ROOT__ = hydrateRootInTransition({\n children: createElement(BrowserRoot, {\n initialElements: root,\n initialNavigationSnapshot,\n }),\n container: document,\n hydrateRoot,\n options: hydrateRootOptions,\n startTransition,\n });\n\n const navigateRsc: NavigationRuntimeNavigate = async function navigateRsc(\n href: string,\n redirectDepth = 0,\n navigationKind: NavigationKind = \"navigate\",\n historyUpdateMode?: HistoryUpdateMode,\n previousNextUrlOverride?: string | null,\n programmaticTransition = false,\n traversalIntent?: HistoryTraversalIntent,\n ): Promise<void> {\n let pendingRouterState: PendingBrowserRouterState | null = null;\n // Hoist navId above try so the catch and finally blocks can reference it.\n const navId = browserNavigationController.beginNavigation();\n discardedServerActionRefreshScheduler.markNavigationStart();\n\n // Loop variables for inline redirect following. On a redirect, these are\n // updated and the loop continues without returning or re-entering navigateRsc,\n // so a single pendingRouterState spans all hops and isPending never flashes.\n let currentHref = href;\n let currentHistoryMode = historyUpdateMode;\n let currentPrevNextUrl = previousNextUrlOverride;\n let redirectCount = redirectDepth;\n let detachedNavigationCommits = false;\n const activeTraversalIntent =\n navigationKind === \"traverse\"\n ? (traversalIntent ??\n resolveHistoryTraversalIntent({\n currentHistoryIndex: currentHistoryTraversalIndex,\n historyState: window.history.state,\n }))\n : null;\n\n try {\n const shouldUsePendingRouterState = programmaticTransition;\n if (shouldUsePendingRouterState && hasBrowserRouterState()) {\n pendingRouterState = beginPendingBrowserRouterState();\n } else {\n await waitForBrowserRouterStateReady();\n if (!browserNavigationController.isCurrentNavigation(navId)) return;\n\n if (shouldUsePendingRouterState) {\n pendingRouterState = beginPendingBrowserRouterState();\n }\n }\n\n while (true) {\n const url = new URL(currentHref, window.location.origin);\n const requestState = getRequestState(\n navigationKind,\n url.pathname,\n currentPrevNextUrl,\n activeTraversalIntent?.historyState,\n );\n const requestInterceptionContext = requestState.interceptionContext;\n const requestPreviousNextUrl = requestState.previousNextUrl;\n if (navigationKind === \"refresh\") {\n syncCurrentHistoryStatePreviousNextUrl(requestPreviousNextUrl);\n }\n\n // Set this navigation as the pending pathname, overwriting any previous.\n // Pass navId so only this navigation (or a newer one) can clear it later.\n setPendingPathname(url.pathname, navId);\n\n const elementsAtNavStart = getBrowserRouterState().elements;\n const mountedSlotsHeader = getMountedSlotIdsHeader(elementsAtNavStart);\n const requestHeaders = createRscRequestHeaders({\n interceptionContext: requestInterceptionContext,\n renderMode:\n navigationKind === \"refresh\" ? APP_RSC_RENDER_MODE_REFRESH_PRESERVE_UI : undefined,\n });\n if (mountedSlotsHeader) {\n requestHeaders.set(VINEXT_MOUNTED_SLOTS_HEADER, mountedSlotsHeader);\n }\n const rscUrl = await createRscRequestUrl(url.pathname + url.search, requestHeaders);\n const cachedRoute = getVisitedResponse(\n rscUrl,\n requestInterceptionContext,\n mountedSlotsHeader,\n navigationKind,\n );\n if (cachedRoute) {\n const compatibilityDecision = resolveRscCompatibilityNavigationDecision({\n clientCompatibilityId: CLIENT_RSC_COMPATIBILITY_ID,\n currentHref,\n origin: window.location.origin,\n responseCompatibilityId: cachedRoute.response.compatibilityIdHeader,\n responseUrl: cachedRoute.response.url,\n });\n if (compatibilityDecision.kind === \"hard-navigate\") {\n browserNavigationController.performHardNavigation(\n compatibilityDecision.hardNavigationTarget,\n );\n return;\n }\n // Check stale-navigation before and after createFromFetch. The pre-check\n // avoids wasted parse work; the post-check catches supersessions that\n // occur during the await. createFromFetch on a buffered response is fast\n // but still async, so the window exists. The non-cached path (below) places\n // its heavyweight async steps (fetch, body.tee + createFromFetch on the\n // live RSC branch) between navId checks consistently; the cached path omits\n // the check between createClientNavigationRenderSnapshot (synchronous) and\n // createFromFetch because there is no await in that gap.\n if (!browserNavigationController.isCurrentNavigation(navId)) return;\n const cachedParams = cachedRoute.params;\n // createClientNavigationRenderSnapshot is synchronous (URL parsing + param\n // wrapping only) — no stale-navigation recheck needed between here and the\n // next await.\n const cachedNavigationSnapshot = createClientNavigationRenderSnapshot(\n currentHref,\n cachedParams,\n );\n const cachedPayload = decodeAppElementsPromise(\n createFromFetch<AppWireElements>(\n Promise.resolve(restoreRscResponse(cachedRoute.response)),\n ),\n );\n if (!browserNavigationController.isCurrentNavigation(navId)) return;\n await renderNavigationPayload(\n cachedPayload,\n cachedNavigationSnapshot,\n currentHref,\n navId,\n currentHistoryMode,\n cachedParams,\n requestPreviousNextUrl,\n detachedNavigationCommits ? null : pendingRouterState,\n VISITED_CACHE_APP_NAVIGATION_PAYLOAD_ORIGIN,\n toActionType(navigationKind),\n toOperationLane(navigationKind),\n activeTraversalIntent,\n );\n return;\n }\n\n // Continue using the slot state captured at navigation start for fetches\n // and prefetch compatibility decisions.\n\n let navResponse: Response | undefined;\n let navResponseUrl: string | null = null;\n if (navigationKind !== \"refresh\") {\n const prefetchedResponse = consumePrefetchResponse(\n rscUrl,\n requestInterceptionContext,\n mountedSlotsHeader,\n );\n if (prefetchedResponse) {\n navResponse = restoreRscResponse(prefetchedResponse, false);\n navResponseUrl = prefetchedResponse.url;\n }\n }\n\n if (!navResponse && navigationKind === \"navigate\") {\n const routeManifest = getBrowserRouteManifest();\n await learnOptimisticRouteTemplatesFromPrefetchCache({\n interceptionContext: requestInterceptionContext,\n mountedSlotsHeader,\n routeManifest,\n });\n if (!browserNavigationController.isCurrentNavigation(navId)) return;\n\n if (routeManifest !== null) {\n const optimisticPayload = resolveOptimisticNavigationPayload({\n basePath: __basePath,\n href: currentHref,\n interceptionContext: requestInterceptionContext,\n mountedSlotsHeader,\n routeManifest,\n templates: optimisticRouteTemplates,\n });\n\n if (optimisticPayload !== null) {\n detachedNavigationCommits = true;\n const optimisticNavigationSnapshot = createClientNavigationRenderSnapshot(\n currentHref,\n optimisticPayload.params,\n );\n // The optimistic shell is a detached commit for this navigation.\n // It uses the same navId gate as the real payload, while the real\n // payload skips pending-router-state reuse via\n // detachedNavigationCommits. That keeps late optimistic errors or\n // transitions from mutating a newer navigation or sharing mutable\n // pending state with the authoritative render.\n void renderNavigationPayload(\n Promise.resolve(optimisticPayload.elements),\n optimisticNavigationSnapshot,\n currentHref,\n navId,\n currentHistoryMode,\n optimisticPayload.params,\n requestPreviousNextUrl,\n null,\n FRESH_APP_NAVIGATION_PAYLOAD_ORIGIN,\n toActionType(navigationKind),\n toOperationLane(navigationKind),\n activeTraversalIntent,\n ).catch((error) => {\n if (browserNavigationController.isCurrentNavigation(navId)) {\n console.error(\"[vinext] Optimistic RSC navigation error:\", error);\n }\n });\n }\n }\n }\n\n if (!navResponse) {\n navResponse = await fetch(rscUrl, {\n headers: requestHeaders,\n credentials: \"include\",\n });\n }\n\n if (!browserNavigationController.isCurrentNavigation(navId)) return;\n\n // Any response that isn't a valid RSC payload (non-ok status,\n // missing/rewritten Content-Type, or missing body) means the server\n // returned something we cannot parse — typically an HTML error page\n // or a proxy-rewritten response. Parsing such a body as an RSC stream\n // throws a cryptic \"Connection closed\" error. Match Next.js behavior\n // (fetch-server-response.ts:211, `!isFlightResponse || !res.ok || !res.body`):\n // hard-navigate to the response URL so the server can render the correct\n // error page as HTML. The outer finally handles\n // settlePendingBrowserRouterState and clearPendingPathname on this\n // return path.\n //\n // Prefer the post-redirect response URL over `currentHref`: on a\n // redirect chain like `/old` → 307 → `/new` → 500, the browser's\n // fetch already followed the redirect, so `navResponse.url` is the\n // failing `/new` destination. Hard-navigating there directly avoids\n // bouncing off `/old` just to re-follow the same 307, which would\n // flash the wrong URL in the address bar and mis-key analytics.\n // Matches Next.js' `doMpaNavigation(responseUrl.toString())`. Falls\n // back to `currentHref` when no response URL is available.\n const navContentType = navResponse.headers.get(\"content-type\") ?? \"\";\n const isRscResponse = navContentType.startsWith(\"text/x-component\");\n if (!navResponse.ok || !isRscResponse || !navResponse.body) {\n const responseUrl = navResponseUrl ?? navResponse.url;\n browserNavigationController.performHardNavigation(\n resolveHardNavigationTargetFromRscResponse(\n responseUrl,\n currentHref,\n window.location.origin,\n ),\n );\n return;\n }\n\n const compatibilityDecision = resolveRscCompatibilityNavigationDecision({\n clientCompatibilityId: CLIENT_RSC_COMPATIBILITY_ID,\n currentHref,\n origin: window.location.origin,\n responseCompatibilityId: navResponse.headers.get(VINEXT_RSC_COMPATIBILITY_ID_HEADER),\n responseUrl: navResponseUrl ?? navResponse.url,\n });\n if (compatibilityDecision.kind === \"hard-navigate\") {\n browserNavigationController.performHardNavigation(\n compatibilityDecision.hardNavigationTarget,\n );\n return;\n }\n\n const redirectDecision = resolveRscRedirectLifecycleHop({\n currentHref,\n historyUpdateMode: currentHistoryMode ?? \"replace\",\n origin: window.location.origin,\n redirectDepth: redirectCount,\n requestPreviousNextUrl,\n responseUrl: navResponseUrl ?? navResponse.url,\n });\n\n if (redirectDecision.kind === \"terminal-hard-navigation\") {\n if (redirectDecision.reason === \"maxRedirectsExceeded\") {\n console.error(\n \"[vinext] Too many RSC redirects — aborting navigation to prevent infinite loop.\",\n );\n }\n browserNavigationController.performHardNavigation(redirectDecision.href);\n return;\n }\n\n if (redirectDecision.kind === \"follow\") {\n // Server-side redirect: keep the redirect chain inside this operation\n // and defer URL/history mutation to the eventual approved commit.\n // This keeps isPending true across all hops and avoids publishing a\n // destination URL before its RSC payload is lifecycle-approved.\n currentHref = redirectDecision.href;\n currentHistoryMode = redirectDecision.historyUpdateMode;\n currentPrevNextUrl = redirectDecision.previousNextUrl;\n redirectCount = redirectDecision.redirectDepth;\n continue;\n }\n\n // RSC redirect encoded as 200 + flight payload (the server's response\n // for `redirect()` thrown from a server component during RSC rendering;\n // see issue #1347 and `buildAppPageSpecialErrorResponse`). The flight\n // body carries the canonical `NEXT_REDIRECT;...` digest for clients\n // that decode it through React's RedirectBoundary, but vinext's\n // browser-navigation loop catches it ahead of decode via this\n // side-channel header so the redirect-following loop above can drain\n // the body and continue without bouncing through the catch path.\n // Reusing the same loop variables keeps `pendingRouterState` and the\n // outer `useTransition` pending state continuous across the hop —\n // matching the pre-1347 fetch-auto-follow-307 behavior.\n const flightRedirectTarget = navResponse.headers.get(VINEXT_RSC_REDIRECT_HEADER);\n if (flightRedirectTarget) {\n // Drain the response body so the underlying connection is released.\n // We do this best-effort: the destination's `.rsc` fetch on the next\n // loop iteration will replace this response entirely.\n void navResponse.body?.cancel().catch(() => {});\n const resolvedTarget = new URL(flightRedirectTarget, window.location.origin);\n if (resolvedTarget.origin !== window.location.origin) {\n browserNavigationController.performHardNavigation(resolvedTarget.href);\n return;\n }\n if (redirectCount >= MAX_RSC_REDIRECT_DEPTH) {\n console.error(\n \"[vinext] Too many RSC redirects — aborting navigation to prevent infinite loop.\",\n );\n browserNavigationController.performHardNavigation(resolvedTarget.href);\n return;\n }\n currentHref = `${resolvedTarget.pathname}${resolvedTarget.search}${resolvedTarget.hash}`;\n redirectCount += 1;\n continue;\n }\n\n // navParams falls back to {} on a missing or malformed header.\n const navParams: Record<string, string | string[]> =\n parseEncodedJsonHeader<Record<string, string | string[]>>(\n navResponse.headers.get(VINEXT_PARAMS_HEADER),\n ) ?? {};\n // Build snapshot from local params, not latestClientParams\n const navigationSnapshot = createClientNavigationRenderSnapshot(currentHref, navParams);\n\n // Tee the response body so React can consume it incrementally —\n // shell parses fast, and any Suspense boundary inside (e.g. the\n // route's loading.tsx) shows its fallback while the rest of the\n // RSC stream resolves. Buffering with `await response.arrayBuffer()`\n // here would block the commit until the page's slowest server\n // promise resolved, hiding the loading state entirely.\n //\n // The cache branch is read in the background so the visited-\n // response snapshot lands as soon as the full stream completes,\n // without holding up React's commit.\n const navBody = navResponse.body;\n if (!navBody) {\n // Already validated above (`!navResponse.body` triggers a hard\n // navigation), so this branch is unreachable — kept for type\n // narrowing only.\n return;\n }\n const [reactBranch, cacheBranch] = navBody.tee();\n const reactResponse = new Response(reactBranch, {\n status: navResponse.status,\n headers: navResponse.headers,\n });\n const cacheBufferPromise = new Response(cacheBranch).arrayBuffer();\n\n if (!browserNavigationController.isCurrentNavigation(navId)) return;\n\n const rscPayload = decodeAppElementsPromise(\n createFromFetch<AppWireElements>(Promise.resolve(reactResponse)),\n );\n\n if (!browserNavigationController.isCurrentNavigation(navId)) return;\n\n const renderOutcome = await renderNavigationPayload(\n rscPayload,\n navigationSnapshot,\n currentHref,\n navId,\n currentHistoryMode,\n navParams,\n requestPreviousNextUrl,\n detachedNavigationCommits ? null : pendingRouterState,\n FRESH_APP_NAVIGATION_PAYLOAD_ORIGIN,\n toActionType(navigationKind),\n toOperationLane(navigationKind),\n activeTraversalIntent,\n );\n if (renderOutcome !== \"committed\") return;\n // Don't cache the response if this navigation was superseded during\n // renderNavigationPayload's await — the elements were never dispatched.\n if (!browserNavigationController.isCurrentNavigation(navId)) return;\n // Store the visited response only after renderNavigationPayload succeeds.\n // If we stored it before and renderNavigationPayload threw, a future\n // back/forward navigation could replay a snapshot from a navigation that\n // never actually rendered successfully.\n const resolvedElements = await rscPayload;\n const metadata = AppElementsWire.readMetadata(resolvedElements);\n if (!isCacheRestorableAppPayloadMetadata(metadata)) {\n void cacheBufferPromise.catch(() => {});\n return;\n }\n const cacheBuffer = await cacheBufferPromise;\n storeVisitedResponseSnapshot(\n rscUrl,\n resolveVisitedResponseInterceptionContext(\n requestInterceptionContext,\n metadata.interceptionContext,\n ),\n createCachedRscResponseSnapshot(navResponse, cacheBuffer, navResponseUrl),\n navParams,\n );\n return;\n }\n } catch (error) {\n // Don't hard-navigate to a stale URL if this navigation was superseded by\n // a newer one — the newer navigation is already in flight and would be clobbered.\n if (!browserNavigationController.isCurrentNavigation(navId)) return;\n // Suppress the diagnostic when the page is unloading: a hard-nav or anchor\n // click tears down the document and aborts any in-flight RSC fetch, which\n // surfaces here as an error. The page is already going away, so the log\n // is just noise. Mirrors Next.js' isPageUnloading pattern.\n if (!isPageUnloading) {\n console.error(\"[vinext] RSC navigation error:\", error);\n }\n browserNavigationController.performHardNavigation(currentHref);\n } finally {\n // Single settlement site: covers normal return, early returns on stale-id\n // checks, and error paths. The finally runs even when the catch returns.\n // settlePendingBrowserRouterState is idempotent via the settled flag.\n browserNavigationController.finalizeNavigation(navId, pendingRouterState);\n discardedServerActionRefreshScheduler.markNavigationSettled();\n }\n };\n\n // Exposed through one typed runtime seam so next/navigation, Link, Form, and\n // the browser entry share a single App Router capability contract.\n registerNavigationRuntimeFunctions({\n clearNavigationCaches: clearClientNavigationCaches,\n commitHashNavigation: commitHashOnlyNavigation,\n navigate: navigateRsc,\n });\n\n if (\"scrollRestoration\" in history) {\n history.scrollRestoration = \"manual\";\n }\n\n // Note: This popstate handler runs for App Router (RSC navigation available).\n // It coordinates scroll restoration with the pending RSC navigation.\n // Pages Router scroll restoration is handled in shims/navigation.ts:1289 with\n // microtask-based deferral for compatibility with non-RSC navigation.\n // See: https://github.com/vercel/next.js/discussions/41934#discussioncomment-4602607\n const handlePopstate = createPopstateRestoreHandler({\n getActiveNavigationId: browserNavigationController.getActiveNavigationId.bind(\n browserNavigationController,\n ),\n getPendingNavigation: () => window.__VINEXT_RSC_PENDING__,\n getNavigate: () => getNavigationRuntime()?.functions.navigate,\n isCurrentNavigation: browserNavigationController.isCurrentNavigation.bind(\n browserNavigationController,\n ),\n notifyAppRouterTransitionStart: (href) => {\n notifyAppRouterTransitionStart(href, \"traverse\");\n },\n restorePopstateScrollPosition,\n setPendingNavigation: (pendingNavigation) => {\n window.__VINEXT_RSC_PENDING__ = pendingNavigation;\n },\n });\n\n window.addEventListener(\"popstate\", (event) => {\n // The browser has already applied the history entry by the time popstate\n // fires. App Router state does not include hashes, so matching the\n // committed pathname/search proves this traversal does not need a new RSC\n // payload. This covers both /page#target -> /page and /page -> /page#target.\n // Notify the transition start so observers still see the URL change, then\n // restore scroll directly and skip the RSC dispatch.\n const href = window.location.href;\n if (isSameAppRoutePopstateTarget(href)) {\n notifyAppRouterTransitionStart(href, \"traverse\");\n commitTraversalIndexFromHistoryState(event.state);\n restorePopstateScrollPosition(event.state);\n return;\n }\n handlePopstate(event);\n });\n\n if (import.meta.hot) {\n const handleRscUpdate = async (): Promise<void> => {\n try {\n // If BrowserRoot has been mounted before but isn't now, a render\n // error tore down the tree (e.g. a server route threw). HMR can't\n // dispatch into a missing setter, and waitForBrowserRouterStateReady\n // would block forever — the tree won't remount until the page reloads.\n // Trigger that reload so the user's fix actually lands without a\n // manual refresh. Cleared after a successful mount, so this only\n // fires once per teardown.\n if (\n browserRouterStateHasEverCommitted &&\n !browserNavigationController.hasBrowserRouterState()\n ) {\n window.location.reload();\n return;\n }\n // HMR can also fire before BrowserRoot's layout effect publishes\n // the browser router state (e.g. saving a file while the initial RSC\n // stream is still suspended). Wait for readiness, then re-check the\n // mounted state — readiness can race with cleanup, which nulls it again.\n // Skip silently when the tree is not currently mounted; the next\n // HMR push or full reload will reconcile.\n await waitForBrowserRouterStateReady();\n if (!browserNavigationController.hasBrowserRouterState()) {\n return;\n }\n clearClientNavigationCaches();\n const navigationSnapshot = createClientNavigationRenderSnapshot(\n window.location.href,\n latestClientParams,\n );\n // Clear stale errors from the dev overlay before dispatching the\n // fresh tree. If the new tree renders cleanly, the overlay stays\n // empty; if it throws again, devOnCaughtError/devOnUncaughtError\n // re-populates it. Without this, an old \"DropZone is not defined\"\n // error would linger after the developer fixed the bug.\n dismissOverlay();\n // Interception context on HMR re-renders is intentionally deferred:\n // preserving intercepted modal state across HMR reloads is out of scope\n // for the previousNextUrl mechanism.\n const hmrHeaders = createRscRequestHeaders();\n await browserNavigationController.hmrReplaceTree(\n decodeAppElementsPromise(\n createFromFetch<AppWireElements>(\n fetch(\n await createRscRequestUrl(\n window.location.pathname + window.location.search,\n hmrHeaders,\n ),\n { headers: hmrHeaders },\n ),\n ),\n ),\n navigationSnapshot,\n );\n } catch (error) {\n console.error(\"[vinext] RSC HMR error:\", error);\n }\n };\n\n import.meta.hot.on(\"rsc:update\", () => {\n void handleRscUpdate();\n });\n }\n}\n\nif (typeof document !== \"undefined\") {\n // Install `window.next` as early as possible so any client component that\n // synchronously dereferences it during hydration (or any third-party\n // library script tag that loads before the React tree mounts) sees the\n // expected shape. Mirrors Next.js's app-bootstrap.ts (line 13) which sets\n // `window.next = { version, appDir: true }` before the React runtime\n // initializes, and `app-router-instance.ts` (line 510) which assigns\n // `router: publicAppRouterInstance` at module load.\n installWindowNext({ appDir: true, router: appRouterInstance });\n\n window.addEventListener(\"pagehide\", () => {\n isPageUnloading = true;\n });\n // Reset on pageshow so a bfcache-restored document does not resume with\n // the flag stuck at true, which would silently swallow every subsequent\n // RSC navigation error for the lifetime of that tab. Matches Next.js'\n // fetch-server-response.ts handler pair.\n window.addEventListener(\"pageshow\", () => {\n isPageUnloading = false;\n });\n void main();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmJA,SAAS,aAAa,MAA+C;CACnE,OAAO,SAAS,aAAa,aAAa;;AAG5C,SAAS,gBAAgB,MAAqC;CAC5D,QAAQ,MAAR;EACE,KAAK,YACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,YACH,OAAO;EACT,SAEE,MAAM,IAAI,MAAM,uCAAuC,OAAOA,KAAY,CAAC;;;AAWjF,MAAM,kCAAkC;AACxC,MAAM,6BAA6B,IAAI;AACvC,MAAM,0BAA0B,KA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KACxB;;IAQF,MAAM,gCAAgC;IACtC,IAAI,CAAC,4BAA4B,uBAAuB,EACtD;IAEF,6BAA6B;IAC7B,MAAM,qBAAqB,qCACzB,OAAO,SAAS,MAChB,mBACD;IAMD,gBAAgB;IAIhB,MAAM,aAAa,yBAAyB;IAC5C,MAAM,4BAA4B,eAChC,yBACE,gBACE,MACE,MAAM,oBACJ,OAAO,SAAS,WAAW,OAAO,SAAS,QAC3C,WACD,EACD,EAAE,SAAS,YAAY,CACxB,CACF,CACF,EACD,mBACD;YACM,OAAO;IACd,QAAQ,MAAM,2BAA2B,MAAM;;;EAInD,OAAO,KAAK,IAAI,GAAG,oBAAoB;GACrC,iBAAsB;IACtB;;;AAIN,IAAI,OAAO,aAAa,aAAa;CAQnC,kBAAkB;EAAE,QAAQ;EAAM,QAAQ;EAAmB,CAAC;CAE9D,OAAO,iBAAiB,kBAAkB;EACxC,kBAAkB;GAClB;CAKF,OAAO,iBAAiB,kBAAkB;EACxC,kBAAkB;GAClB;CACF,MAAW"}
|
|
1
|
+
{"version":3,"file":"app-browser-entry.js","names":["_exhaustive"],"sources":["../../src/server/app-browser-entry.ts"],"sourcesContent":["/// <reference types=\"vite/client\" />\n\nimport { createElement, startTransition, use, useLayoutEffect, useRef, useState } from \"react\";\nimport {\n createFromFetch,\n createFromReadableStream,\n createTemporaryReferenceSet,\n encodeReply,\n setServerCallback,\n} from \"@vitejs/plugin-rsc/browser\";\nimport { hydrateRoot } from \"react-dom/client\";\nimport \"../client/instrumentation-client.js\";\nimport { notifyAppRouterTransitionStart } from \"../client/instrumentation-client-state.js\";\nimport {\n __basePath,\n appRouterInstance,\n commitClientNavigationState,\n consumePrefetchResponse,\n createCachedRscResponseSnapshot,\n createClientNavigationRenderSnapshot,\n getClientNavigationRenderContext,\n getPrefetchCache,\n invalidatePrefetchCache,\n navigateClientSide,\n pushHistoryStateWithoutNotify,\n replaceClientParamsWithoutNotify,\n replaceHistoryStateWithoutNotify,\n restoreRscResponse,\n setClientParams,\n setPendingPathname,\n setMountedSlotsHeader,\n setNavigationContext,\n type CachedRscResponse,\n type ClientNavigationRenderSnapshot,\n type PrefetchCacheEntry,\n} from \"vinext/shims/navigation\";\nimport {\n getNavigationRuntime,\n registerNavigationRuntimeBootstrap,\n registerNavigationRuntimeFunctions,\n type NavigationRuntimeNavigate,\n type NavigationRuntimeRscBootstrap,\n} from \"../client/navigation-runtime.js\";\nimport { scrollToHashTargetOnNextFrame } from \"vinext/shims/hash-scroll\";\nimport { installWindowNext } from \"../client/window-next.js\";\nimport {\n chunksToReadableStream,\n createProgressiveRscStream,\n getVinextBrowserGlobal,\n} from \"./app-browser-stream.js\";\nimport {\n createAppBrowserNavigationController,\n clearHardNavigationLoopGuard,\n type HistoryUpdateMode,\n type NavigationPayloadOutcome,\n type PendingBrowserRouterState,\n} from \"./app-browser-navigation-controller.js\";\nimport { resolveManifestNavigationInterceptionContext } from \"./app-browser-interception-context.js\";\nimport {\n createDiscardedServerActionRefreshScheduler,\n createServerActionInitiationSnapshot,\n isServerActionResult,\n parseServerActionRevalidationHeader,\n resolveServerActionRedirectLocation,\n shouldClearClientNavigationCachesForServerActionResult,\n type ServerActionRevalidationKind,\n type AppBrowserServerActionResult,\n} from \"./app-browser-action-result.js\";\nimport {\n consumeInitialFormState,\n createVinextHydrateRootOptions,\n hydrateRootInTransition,\n} from \"./app-browser-hydration.js\";\nimport {\n AppElementsWire,\n getMountedSlotIdsHeader,\n resolveVisitedResponseInterceptionContext,\n type AppElements,\n type AppWireElements,\n} from \"./app-elements.js\";\nimport {\n FRESH_APP_NAVIGATION_PAYLOAD_ORIGIN,\n VISITED_CACHE_APP_NAVIGATION_PAYLOAD_ORIGIN,\n createHistoryStateWithNavigationMetadata,\n createHistoryStateWithPreviousNextUrl,\n readHistoryStatePreviousNextUrl,\n readHistoryStateTraversalIndex,\n isCacheRestorableAppPayloadMetadata,\n resolveHistoryTraversalIntent,\n resolveInterceptionContextFromPreviousNextUrl,\n resolveServerActionRequestState,\n type AppNavigationPayloadOrigin,\n type AppRouterState,\n type HistoryTraversalIntent,\n type OperationLane,\n} from \"./app-browser-state.js\";\nimport { createPopstateRestoreHandler } from \"./app-browser-popstate.js\";\nimport { DevRecoveryBoundary, RedirectBoundary } from \"vinext/shims/error-boundary\";\nimport { AppRouterContext } from \"vinext/shims/internal/app-router-context\";\nimport { ElementsContext, Slot } from \"vinext/shims/slot\";\nimport type { RouteManifest } from \"../routing/app-route-graph.js\";\nimport { stripBasePath } from \"../utils/base-path.js\";\nimport { createOnUncaughtError } from \"./app-browser-error.js\";\nimport {\n devOnCaughtError,\n devOnUncaughtError,\n dismissOverlay,\n installDevErrorOverlay,\n} from \"./dev-error-overlay.js\";\nimport { DANGEROUS_URL_BLOCK_MESSAGE, isDangerousScheme } from \"vinext/shims/url-safety\";\nimport { throwOnServerActionNotFound } from \"./server-action-not-found.js\";\nimport {\n createRscRequestHeaders,\n createRscRequestUrl,\n getVinextRscCompatibilityId,\n resolveHardNavigationTargetFromRscResponse,\n resolveRscCompatibilityNavigationDecision,\n VINEXT_RSC_COMPATIBILITY_ID_HEADER,\n VINEXT_RSC_CONTENT_TYPE,\n} from \"./app-rsc-cache-busting.js\";\nimport { APP_RSC_RENDER_MODE_REFRESH_PRESERVE_UI } from \"./app-rsc-render-mode.js\";\nimport {\n MAX_RSC_REDIRECT_DEPTH,\n resolveRscRedirectLifecycleHop,\n} from \"./app-browser-rsc-redirect.js\";\nimport {\n createOptimisticRouteTemplate,\n getOptimisticPrefetchSourceKey,\n getOptimisticRouteTemplateKey,\n resolveOptimisticNavigationPayload,\n type OptimisticRouteTemplate,\n} from \"./app-optimistic-routing.js\";\nimport {\n ACTION_REDIRECT_HEADER,\n ACTION_REDIRECT_TYPE_HEADER,\n VINEXT_MOUNTED_SLOTS_HEADER,\n VINEXT_PARAMS_HEADER,\n VINEXT_RSC_REDIRECT_HEADER,\n} from \"./headers.js\";\n\ntype SearchParamInput = ConstructorParameters<typeof URLSearchParams>[0];\n\ntype ServerActionResult = AppBrowserServerActionResult<AppWireElements>;\n\ntype NavigationKind = \"navigate\" | \"traverse\" | \"refresh\";\n\n// Maps NavigationKind to the AppRouterAction type used by the reducer.\n// \"refresh\" is intentionally treated as \"navigate\" (merge, preserve absent slots).\n// Both call sites must stay in sync — update here if NavigationKind gains new values.\nfunction toActionType(kind: NavigationKind): \"navigate\" | \"traverse\" {\n return kind === \"traverse\" ? \"traverse\" : \"navigate\";\n}\n\nfunction toOperationLane(kind: NavigationKind): OperationLane {\n switch (kind) {\n case \"navigate\":\n return \"navigation\";\n case \"refresh\":\n return \"refresh\";\n case \"traverse\":\n return \"traverse\";\n default: {\n const _exhaustive: never = kind;\n throw new Error(\"[vinext] Unknown navigation kind: \" + String(_exhaustive));\n }\n }\n}\n\ntype VisitedResponseCacheEntry = {\n params: Record<string, string | string[]>;\n expiresAt: number;\n response: CachedRscResponse;\n};\n\nconst MAX_VISITED_RESPONSE_CACHE_SIZE = 50;\nconst VISITED_RESPONSE_CACHE_TTL = 5 * 60_000;\nconst MAX_TRAVERSAL_CACHE_TTL = 30 * 60_000;\nconst CLIENT_RSC_COMPATIBILITY_ID = getVinextRscCompatibilityId();\nconst optimisticRouteTemplates = new Map<string, OptimisticRouteTemplate>();\nconst optimisticRouteTemplateSources = new Set<string>();\nconst optimisticRouteTemplateLearning = new Map<string, Promise<void>>();\nfunction getBrowserRouteManifest(): RouteManifest | null {\n return getNavigationRuntime()?.bootstrap.routeManifest ?? null;\n}\n\nconst browserNavigationController = createAppBrowserNavigationController({\n getRouteManifest: getBrowserRouteManifest,\n syncHistoryStatePreviousNextUrl: syncCurrentHistoryStatePreviousNextUrl,\n});\nconst discardedServerActionRefreshScheduler = createDiscardedServerActionRefreshScheduler({\n runRefresh() {\n clearClientNavigationCaches();\n void getNavigationRuntime()?.functions.navigate?.(\n window.location.href,\n 0,\n \"refresh\",\n undefined,\n undefined,\n true,\n );\n },\n});\nconst NavigationCommitSignal = browserNavigationController.NavigationCommitSignal;\n\n// Parses a URI-encoded JSON value carried in a response header (e.g.\n// `X-Vinext-Params`). Returns `null` on missing or malformed input so callers\n// can fall back to their own defaults. Silent by design — these headers are\n// best-effort hydration data and a parse failure should not break navigation.\nfunction parseEncodedJsonHeader<T>(value: string | null): T | null {\n if (!value) return null;\n try {\n return JSON.parse(decodeURIComponent(value)) as T;\n } catch {\n return null;\n }\n}\n\nfunction isRouterStatePromise(\n value: AppRouterState | Promise<AppRouterState>,\n): value is Promise<AppRouterState> {\n return value instanceof Promise;\n}\n\nlet latestClientParams: Record<string, string | string[]> = {};\nconst visitedResponseCache = new Map<string, VisitedResponseCacheEntry>();\n// Sticky bit: stays true once BrowserRoot has committed at least once. Used by\n// the HMR handler to distinguish \"still hydrating\" (wait) from \"was up, then\n// torn down by a render error\" (full reload to recover).\nlet browserRouterStateHasEverCommitted = false;\n// Most recent navigation target that has been dispatched but not yet committed.\n// Read by the onUncaughtError handler so a render error tearing down the tree\n// can land the browser on the URL the user was actually navigating to, instead\n// of stranding them on the previous URL with a blank page. Cleared once the\n// commit effect runs (URL update succeeded) or the navigation is superseded.\nlet pendingNavigationRecoveryHref: string | null = null;\nlet currentHistoryTraversalIndex: number | null =\n readHistoryStateTraversalIndex(window.history.state) ?? 0;\nlet nextHistoryTraversalIndex: number = currentHistoryTraversalIndex;\n\nfunction allocateNavigationHistoryTraversalIndex(\n historyUpdateMode: HistoryUpdateMode | undefined,\n): number | null {\n switch (historyUpdateMode) {\n case \"push\":\n return nextHistoryTraversalIndex + 1;\n case \"replace\":\n return currentHistoryTraversalIndex;\n case undefined:\n return null;\n default: {\n const _exhaustive: never = historyUpdateMode;\n throw new Error(\"[vinext] Unknown history update mode: \" + String(_exhaustive));\n }\n }\n}\n\nfunction commitHistoryTraversalIndex(index: number | null): void {\n currentHistoryTraversalIndex = index;\n if (index !== null) {\n // Keep allocation anchored to the highest app-owned entry we know about.\n // Traversing to metadata-less entries makes the current index unknown, but\n // the next app-owned push should still continue from known app history.\n nextHistoryTraversalIndex = Math.max(nextHistoryTraversalIndex, index);\n }\n}\n\nfunction commitHashOnlyNavigation(\n href: string,\n historyUpdateMode: Exclude<HistoryUpdateMode, undefined>,\n scroll: boolean,\n): void {\n const navigationHistoryIndex = allocateNavigationHistoryTraversalIndex(historyUpdateMode);\n const previousNextUrl = hasBrowserRouterState()\n ? getBrowserRouterState().previousNextUrl\n : readHistoryStatePreviousNextUrl(window.history.state);\n const historyState = createHistoryStateWithNavigationMetadata(\n createHashOnlyNavigationBaseHistoryState(historyUpdateMode, scroll),\n {\n previousNextUrl,\n traversalIndex: navigationHistoryIndex,\n },\n );\n\n if (historyUpdateMode === \"replace\") {\n replaceHistoryStateWithoutNotify(historyState, \"\", href);\n } else {\n pushHistoryStateWithoutNotify(historyState, \"\", href);\n }\n commitHistoryTraversalIndex(navigationHistoryIndex);\n}\n\nfunction createHashOnlyNavigationBaseHistoryState(\n historyUpdateMode: Exclude<HistoryUpdateMode, undefined>,\n scroll: boolean,\n): unknown {\n if (historyUpdateMode !== \"replace\") {\n return null;\n }\n return scroll ? stripVinextScrollState(window.history.state) : window.history.state;\n}\n\nfunction stripVinextScrollState(state: unknown): unknown {\n if (!state || typeof state !== \"object\") {\n return state;\n }\n\n const nextState: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(state)) {\n if (key === \"__vinext_scrollX\" || key === \"__vinext_scrollY\") {\n continue;\n }\n nextState[key] = value;\n }\n\n return Object.keys(nextState).length > 0 ? nextState : null;\n}\n\nfunction commitTraversalIndexFromHistoryState(historyState: unknown): void {\n commitHistoryTraversalIndex(readHistoryStateTraversalIndex(historyState));\n}\n\nfunction getBrowserRouterState(): AppRouterState {\n return browserNavigationController.getBrowserRouterState();\n}\n\nfunction hasBrowserRouterState(): boolean {\n return browserNavigationController.hasBrowserRouterState();\n}\n\nfunction waitForBrowserRouterStateReady(): Promise<void> {\n return browserNavigationController.waitForBrowserRouterStateReady();\n}\n\nfunction beginPendingBrowserRouterState(): PendingBrowserRouterState {\n return browserNavigationController.beginPendingBrowserRouterState();\n}\n\nfunction applyClientParams(params: Record<string, string | string[]>): void {\n latestClientParams = params;\n setClientParams(params);\n}\n\nfunction stageClientParams(params: Record<string, string | string[]>): void {\n // NB: latestClientParams diverges from ClientNavigationState.clientParams\n // between staging and commit. Server action snapshots capture the committed\n // browser router state at invocation time, so they do not read this mutable\n // module-level value after their async request boundary.\n latestClientParams = params;\n replaceClientParamsWithoutNotify(params);\n}\n\nfunction clearVisitedResponseCache(): void {\n visitedResponseCache.clear();\n}\n\nfunction clearPrefetchState(): void {\n invalidatePrefetchCache();\n optimisticRouteTemplates.clear();\n optimisticRouteTemplateSources.clear();\n optimisticRouteTemplateLearning.clear();\n}\n\nfunction clearClientNavigationCaches(): void {\n clearVisitedResponseCache();\n clearPrefetchState();\n}\n\nfunction isSettledPrefetchCacheEntry(\n entry: PrefetchCacheEntry,\n): entry is PrefetchCacheEntry & { snapshot: CachedRscResponse } {\n return (\n entry.outcome === \"cache-seeded\" && entry.pending === undefined && entry.snapshot !== undefined\n );\n}\n\nfunction parsePrefetchCacheKey(cacheKey: string): {\n interceptionContext: string | null;\n rscUrl: string;\n} {\n const separatorIndex = cacheKey.indexOf(\"\\0\");\n if (separatorIndex === -1) {\n return { interceptionContext: null, rscUrl: cacheKey };\n }\n return {\n interceptionContext: cacheKey.slice(separatorIndex + 1),\n rscUrl: cacheKey.slice(0, separatorIndex),\n };\n}\n\nasync function learnOptimisticRouteTemplateFromPrefetch(options: {\n cacheKey: string;\n entry: PrefetchCacheEntry & { snapshot: CachedRscResponse };\n interceptionContext: string | null;\n mountedSlotsHeader: string | null;\n routeManifest: RouteManifest;\n}): Promise<boolean> {\n const source = parsePrefetchCacheKey(options.cacheKey);\n if (source.interceptionContext !== options.interceptionContext) return false;\n if ((options.entry.snapshot.mountedSlotsHeader ?? null) !== options.mountedSlotsHeader)\n return false;\n if (options.interceptionContext !== null) return false;\n\n const elements = await decodeAppElementsPromise(\n createFromFetch<AppWireElements>(Promise.resolve(restoreRscResponse(options.entry.snapshot))),\n );\n const template = createOptimisticRouteTemplate({\n allowLoadingShell: options.entry.optimisticRouteShell === true,\n basePath: __basePath,\n elements,\n href: options.entry.snapshot.url || source.rscUrl,\n interceptionContext: options.interceptionContext,\n mountedSlotsHeader: options.mountedSlotsHeader,\n routeManifest: options.routeManifest,\n });\n if (template === null) return false;\n\n optimisticRouteTemplates.set(\n getOptimisticRouteTemplateKey({\n interceptionContext: options.interceptionContext,\n mountedSlotsHeader: options.mountedSlotsHeader,\n routeId: template.routeId,\n }),\n template,\n );\n return true;\n}\n\nasync function learnOptimisticRouteTemplatesFromPrefetchCache(options: {\n interceptionContext: string | null;\n mountedSlotsHeader: string | null;\n routeManifest: RouteManifest | null;\n}): Promise<void> {\n if (options.routeManifest === null) return;\n\n const learning: Promise<void>[] = [...optimisticRouteTemplateLearning.values()];\n for (const [cacheKey, entry] of getPrefetchCache()) {\n const sourceKey = getOptimisticPrefetchSourceKey({\n cacheKey,\n interceptionContext: options.interceptionContext,\n mountedSlotsHeader: options.mountedSlotsHeader,\n });\n if (optimisticRouteTemplateSources.has(sourceKey)) continue;\n if (optimisticRouteTemplateLearning.has(sourceKey)) continue;\n if (!isSettledPrefetchCacheEntry(entry)) continue;\n\n const promise = learnOptimisticRouteTemplateFromPrefetch({\n cacheKey,\n entry,\n interceptionContext: options.interceptionContext,\n mountedSlotsHeader: options.mountedSlotsHeader,\n routeManifest: options.routeManifest,\n })\n .then((learned) => {\n if (learned) optimisticRouteTemplateSources.add(sourceKey);\n })\n .finally(() => {\n optimisticRouteTemplateLearning.delete(sourceKey);\n });\n optimisticRouteTemplateLearning.set(sourceKey, promise);\n learning.push(promise);\n }\n\n if (learning.length === 0) return;\n await Promise.allSettled(learning);\n}\n\nfunction syncCurrentHistoryStatePreviousNextUrl(previousNextUrl: string | null): void {\n if (readHistoryStatePreviousNextUrl(window.history.state) === previousNextUrl) {\n return;\n }\n\n const nextHistoryState = createHistoryStateWithPreviousNextUrl(\n window.history.state,\n previousNextUrl,\n );\n // First attempt: use replaceHistoryStateWithoutNotify which fires no popstate\n // or hashchange events. If the browser accepted the state update (checked via\n // readHistoryStatePreviousNextUrl), we're done. The double-read is needed\n // because some browsers (notably Safari) can silently coalesce or ignore\n // replaceState calls when called in rapid succession (e.g. back-to-back\n // navigation commits). The fallback fires only when the state didn't stick.\n replaceHistoryStateWithoutNotify(nextHistoryState, \"\", window.location.href);\n if (readHistoryStatePreviousNextUrl(window.history.state) === previousNextUrl) {\n return;\n }\n window.history.replaceState(nextHistoryState, \"\", window.location.href);\n}\n\nfunction createActionInitiationSnapshot() {\n const routerState = getBrowserRouterState();\n return createServerActionInitiationSnapshot({\n href: window.location.href,\n navigationId: browserNavigationController.getActiveNavigationId(),\n routerState,\n });\n}\n\ntype ActionInitiationSnapshot = ReturnType<typeof createActionInitiationSnapshot>;\n\nfunction createNavigationCommitEffect(options: {\n href: string;\n historyUpdateMode: HistoryUpdateMode | undefined;\n navId: number;\n params: Record<string, string | string[]>;\n previousNextUrl: string | null;\n targetHistoryIndex?: number | null;\n}): () => void {\n const { href, historyUpdateMode, navId, params, previousNextUrl, targetHistoryIndex } = options;\n\n return () => {\n // Only update URL if this is still the active navigation.\n // A newer navigation would have superseded this navigation id.\n if (!browserNavigationController.isCurrentNavigation(navId)) {\n // This transition was superseded before commit; balance the active\n // snapshot counter without clearing pendingPathname ownership.\n commitClientNavigationState(undefined, { releaseSnapshot: true });\n return;\n }\n\n const targetHref = new URL(href, window.location.origin).href;\n const preserveExistingState = historyUpdateMode === \"replace\";\n const navigationHistoryIndex =\n targetHistoryIndex !== undefined\n ? targetHistoryIndex\n : allocateNavigationHistoryTraversalIndex(historyUpdateMode);\n const historyState = createHistoryStateWithNavigationMetadata(\n preserveExistingState ? window.history.state : null,\n {\n previousNextUrl,\n traversalIndex: navigationHistoryIndex,\n },\n );\n\n let wroteHistoryState = false;\n if (historyUpdateMode === \"replace\" && window.location.href !== targetHref) {\n stageClientParams(params);\n replaceHistoryStateWithoutNotify(historyState, \"\", href);\n wroteHistoryState = true;\n commitHistoryTraversalIndex(navigationHistoryIndex);\n } else if (historyUpdateMode === \"push\" && window.location.href !== targetHref) {\n stageClientParams(params);\n pushHistoryStateWithoutNotify(historyState, \"\", href);\n wroteHistoryState = true;\n commitHistoryTraversalIndex(navigationHistoryIndex);\n }\n\n if (!wroteHistoryState) {\n syncCurrentHistoryStatePreviousNextUrl(previousNextUrl);\n stageClientParams(params);\n if (targetHistoryIndex !== undefined) {\n commitHistoryTraversalIndex(targetHistoryIndex);\n }\n }\n\n // URL has been updated; the recovery hard-nav target is no longer needed.\n pendingNavigationRecoveryHref = null;\n commitClientNavigationState(navId);\n };\n}\n\nasync function renderNavigationPayload(\n payload: Promise<AppElements>,\n navigationSnapshot: ClientNavigationRenderSnapshot,\n targetHref: string,\n navId: number,\n historyUpdateMode: HistoryUpdateMode | undefined,\n params: Record<string, string | string[]>,\n previousNextUrl: string | null,\n pendingRouterState: PendingBrowserRouterState | null,\n payloadOrigin: AppNavigationPayloadOrigin,\n actionType: \"navigate\" | \"replace\" | \"traverse\" = \"navigate\",\n operationLane: OperationLane = \"navigation\",\n traversalIntent: HistoryTraversalIntent | null = null,\n): Promise<NavigationPayloadOutcome> {\n try {\n return await browserNavigationController.renderNavigationPayload({\n actionType,\n createNavigationCommitEffect: (options) => {\n pendingNavigationRecoveryHref = options.href;\n return createNavigationCommitEffect(options);\n },\n historyUpdateMode,\n navigationSnapshot,\n nextElements: payload,\n operationLane,\n payloadOrigin,\n params,\n pendingRouterState,\n previousNextUrl,\n targetHistoryIndex: traversalIntent === null ? undefined : traversalIntent.targetHistoryIndex,\n targetHref,\n navId,\n });\n } catch (error) {\n pendingNavigationRecoveryHref = null;\n throw error;\n }\n}\n\nasync function commitSameUrlNavigatePayload(\n nextElements: Promise<AppElements>,\n actionInitiation: ActionInitiationSnapshot,\n returnValue?: ServerActionResult[\"returnValue\"],\n revalidation: ServerActionRevalidationKind = \"none\",\n): Promise<unknown> {\n const navigationSnapshot = createClientNavigationRenderSnapshot(\n actionInitiation.href,\n actionInitiation.routerState.navigationSnapshot.params,\n );\n return browserNavigationController.commitSameUrlNavigatePayload(\n nextElements,\n navigationSnapshot,\n returnValue,\n actionInitiation.routerState,\n {\n onDiscardedRevalidation() {\n discardedServerActionRefreshScheduler.schedule();\n },\n revalidation,\n startedNavigationId: actionInitiation.navigationId,\n targetHref: actionInitiation.href,\n },\n );\n}\n\nfunction evictVisitedResponseCacheIfNeeded(): void {\n while (visitedResponseCache.size >= MAX_VISITED_RESPONSE_CACHE_SIZE) {\n const oldest = visitedResponseCache.keys().next().value;\n if (oldest === undefined) {\n return;\n }\n visitedResponseCache.delete(oldest);\n }\n}\n\nfunction getVisitedResponse(\n rscUrl: string,\n interceptionContext: string | null,\n mountedSlotsHeader: string | null,\n navigationKind: NavigationKind,\n): VisitedResponseCacheEntry | null {\n const cacheKey = AppElementsWire.encodeCacheKey(rscUrl, interceptionContext);\n const cached = visitedResponseCache.get(cacheKey);\n if (!cached) {\n return null;\n }\n\n if ((cached.response.mountedSlotsHeader ?? null) !== mountedSlotsHeader) {\n visitedResponseCache.delete(cacheKey);\n return null;\n }\n\n if (navigationKind === \"refresh\") {\n return null;\n }\n\n if (navigationKind === \"traverse\") {\n const createdAt = cached.expiresAt - VISITED_RESPONSE_CACHE_TTL;\n if (Date.now() - createdAt >= MAX_TRAVERSAL_CACHE_TTL) {\n visitedResponseCache.delete(cacheKey);\n return null;\n }\n // LRU: promote to most-recently-used (delete + re-insert moves to end of Map)\n visitedResponseCache.delete(cacheKey);\n visitedResponseCache.set(cacheKey, cached);\n return cached;\n }\n\n if (cached.expiresAt > Date.now()) {\n // LRU: promote to most-recently-used\n visitedResponseCache.delete(cacheKey);\n visitedResponseCache.set(cacheKey, cached);\n return cached;\n }\n\n visitedResponseCache.delete(cacheKey);\n return null;\n}\n\nfunction storeVisitedResponseSnapshot(\n rscUrl: string,\n interceptionContext: string | null,\n snapshot: CachedRscResponse,\n params: Record<string, string | string[]>,\n): void {\n const cacheKey = AppElementsWire.encodeCacheKey(rscUrl, interceptionContext);\n visitedResponseCache.delete(cacheKey);\n evictVisitedResponseCacheIfNeeded();\n const now = Date.now();\n visitedResponseCache.set(cacheKey, {\n params,\n expiresAt: now + VISITED_RESPONSE_CACHE_TTL,\n response: snapshot,\n });\n}\n\ntype NavigationRequestState = {\n interceptionContext: string | null;\n previousNextUrl: string | null;\n};\n\nfunction getRequestState(\n navigationKind: NavigationKind,\n targetPathname: string,\n previousNextUrlOverride?: string | null,\n traverseHistoryState?: unknown,\n): NavigationRequestState {\n if (previousNextUrlOverride !== undefined) {\n return {\n interceptionContext: resolveInterceptionContextFromPreviousNextUrl(\n previousNextUrlOverride,\n __basePath,\n ),\n previousNextUrl: previousNextUrlOverride,\n };\n }\n\n // Three branches for \"navigate\":\n // 1. previousNextUrl !== null → a committed intercepted navigation set this\n // in browser state (requires proof). This is the proven interception path.\n // 2. route manifest declares current URL can intercept target URL → ask the\n // server for an intercepted payload using manifest route facts only.\n // 3. otherwise, send no interception context.\n switch (navigationKind) {\n case \"navigate\": {\n const currentPreviousNextUrl = getBrowserRouterState().previousNextUrl;\n if (currentPreviousNextUrl !== null) {\n return {\n interceptionContext: resolveInterceptionContextFromPreviousNextUrl(\n currentPreviousNextUrl,\n __basePath,\n ),\n previousNextUrl: currentPreviousNextUrl,\n };\n }\n const manifestInterceptionContext = resolveManifestNavigationInterceptionContext({\n basePath: __basePath,\n currentPathname: window.location.pathname,\n routeManifest: getBrowserRouteManifest(),\n targetPathname,\n });\n if (manifestInterceptionContext !== null) {\n return {\n interceptionContext: manifestInterceptionContext,\n previousNextUrl: window.location.pathname + window.location.search,\n };\n }\n return {\n interceptionContext: null,\n previousNextUrl: null,\n };\n }\n case \"traverse\": {\n const previousNextUrl = readHistoryStatePreviousNextUrl(\n traverseHistoryState ?? window.history.state,\n );\n return {\n interceptionContext: resolveInterceptionContextFromPreviousNextUrl(\n previousNextUrl,\n __basePath,\n ),\n previousNextUrl,\n };\n }\n case \"refresh\": {\n const currentPreviousNextUrl = getBrowserRouterState().previousNextUrl;\n return {\n interceptionContext: resolveInterceptionContextFromPreviousNextUrl(\n currentPreviousNextUrl,\n __basePath,\n ),\n previousNextUrl: currentPreviousNextUrl,\n };\n }\n default: {\n const _exhaustive: never = navigationKind;\n throw new Error(\"[vinext] Unknown navigation kind: \" + String(_exhaustive));\n }\n }\n}\n\n// Dev-only callback invoked when DevRecoveryBoundary catches. The replaced\n// subtree means NavigationCommitSignal's useLayoutEffect never fires, so the\n// URL update for the in-flight navigation would otherwise be lost. Force-drain\n// the queued pre-paint effect for this renderId so the URL still moves to the\n// navigation target, the dev overlay shows which URL is broken, and HMR's\n// rsc:update fetches the right payload after the bug is fixed.\nfunction handleDevRecoveryBoundaryCatch(resetKey: number): void {\n // React's onCaughtError option already routes the error to the dev overlay.\n // Our job here is purely to drive the URL update for the in-flight\n // navigation that this failed render belonged to.\n browserNavigationController.drainPrePaintEffects(resetKey);\n}\n\nfunction decodeAppElementsPromise(payload: Promise<AppWireElements>): Promise<AppElements> {\n // Wrap in Promise.resolve() because createFromReadableStream() returns a\n // React Flight thenable whose .then() returns undefined (not a new Promise).\n // Without the wrap, chaining .then() produces undefined → use() crashes.\n return Promise.resolve(payload).then((elements) => AppElementsWire.decode(elements));\n}\n\nfunction BrowserRoot({\n initialElements,\n initialNavigationSnapshot,\n}: {\n initialElements: Promise<AppElements>;\n initialNavigationSnapshot: ClientNavigationRenderSnapshot;\n}) {\n const resolvedElements = use(initialElements);\n const initialMetadata = AppElementsWire.readMetadata(resolvedElements);\n const [treeStateValue, setTreeStateValue] = useState<AppRouterState | Promise<AppRouterState>>({\n activeOperation: null,\n elements: resolvedElements,\n interception: initialMetadata.interception,\n interceptionContext: initialMetadata.interceptionContext,\n layoutIds: initialMetadata.layoutIds,\n layoutFlags: initialMetadata.layoutFlags,\n navigationSnapshot: initialNavigationSnapshot,\n previousNextUrl: null,\n renderId: 0,\n rootLayoutTreePath: initialMetadata.rootLayoutTreePath,\n routeId: initialMetadata.routeId,\n slotBindings: initialMetadata.slotBindings,\n visibleCommitVersion: 0,\n });\n const treeState = isRouterStatePromise(treeStateValue) ? use(treeStateValue) : treeStateValue;\n\n // Keep the latest router state in a ref so external callers (navigate(),\n // server actions, HMR) always read the current state. Safe: those readers\n // run from events/effects, never from React render itself.\n // Note: stateRef.current is written during render, not in an effect, to\n // avoid a stale-read window between commit and layout effects. This mirrors\n // the same render-phase ref update pattern used by Next.js's own router.\n const stateRef = useRef(treeState);\n stateRef.current = treeState;\n\n // Publish the stable ref object and dispatch during layout commit. This keeps\n // the module-level escape hatches aligned with React's committed tree without\n // performing module writes during render. The navigation runtime is registered\n // after hydrateRoot() returns; by then this layout effect has already run for\n // the hydration commit, so getBrowserRouterState() never observes a null ref.\n useLayoutEffect(() => {\n const detach = browserNavigationController.attachBrowserRouterState(\n setTreeStateValue,\n stateRef,\n );\n browserRouterStateHasEverCommitted = true;\n // App Router uses this timestamp as first committed tree readiness: the\n // browser router state is attached and link/router interactions can safely\n // observe the committed tree. It is intentionally later than hydrateRoot()\n // returning.\n const hydratedAt = performance.now();\n window.__VINEXT_HYDRATED_AT = hydratedAt;\n window.__NEXT_HYDRATED = true;\n window.__NEXT_HYDRATED_AT = hydratedAt;\n window.__NEXT_HYDRATED_CB?.();\n return () => {\n detach();\n setMountedSlotsHeader(null);\n };\n }, [setTreeStateValue]);\n\n useLayoutEffect(() => {\n setMountedSlotsHeader(getMountedSlotIdsHeader(stateRef.current.elements));\n getNavigationRuntime()?.functions.pingVisibleLinks?.();\n }, [treeState.elements]);\n\n useLayoutEffect(() => {\n if (treeState.renderId !== 0) {\n return;\n }\n\n replaceHistoryStateWithoutNotify(\n createHistoryStateWithNavigationMetadata(window.history.state, {\n previousNextUrl: treeState.previousNextUrl,\n traversalIndex: currentHistoryTraversalIndex,\n }),\n \"\",\n window.location.href,\n );\n }, [treeState.previousNextUrl, treeState.renderId]);\n\n const routeTree = createElement(\n RedirectBoundary,\n null,\n createElement(\n NavigationCommitSignal,\n { renderId: treeState.renderId },\n createElement(\n ElementsContext.Provider,\n { value: treeState.elements },\n createElement(Slot, { id: treeState.routeId }),\n ),\n ),\n );\n const innerTree = AppRouterContext\n ? createElement(AppRouterContext.Provider, { value: appRouterInstance }, routeTree)\n : routeTree;\n\n // In dev, wrap the route tree in a top-level recovery boundary. A render\n // error (e.g. a slot's RSC reference rejects) is caught here instead of\n // tearing down BrowserRoot, so HMR can dispatch the next payload —\n // identified by an incremented renderId, which doubles as the boundary's\n // reset key — without a full page reload. The dev overlay (a separate\n // React root) shows the error itself.\n //\n // onCatch drains the pending pre-paint effect for the failed render so\n // the URL update bound to that navigation still runs. Without this, a\n // soft-nav whose target throws would leave the browser on the previous\n // URL, hiding which route is broken and mis-targeting the next HMR\n // payload (which fetches RSC for window.location.pathname).\n //\n // This file is .ts, not .tsx — children are passed positionally to satisfy\n // both the createElement overload and eslint's no-children-prop rule.\n const committedTree = import.meta.env.DEV\n ? createElement(\n DevRecoveryBoundary,\n {\n resetKey: treeState.renderId,\n onCatch: handleDevRecoveryBoundaryCatch,\n },\n innerTree,\n )\n : innerTree;\n\n const ClientNavigationRenderContext = getClientNavigationRenderContext();\n if (!ClientNavigationRenderContext) {\n return committedTree;\n }\n\n return createElement(\n ClientNavigationRenderContext.Provider,\n { value: treeState.navigationSnapshot },\n committedTree,\n );\n}\n\nfunction restoreHydrationNavigationContext(\n pathname: string,\n searchParams: SearchParamInput,\n params: Record<string, string | string[]>,\n): void {\n setNavigationContext({\n pathname,\n searchParams: new URLSearchParams(searchParams),\n params,\n });\n}\n\nfunction restorePopstateScrollPosition(state: unknown): void {\n if (!(state && typeof state === \"object\" && \"__vinext_scrollY\" in state)) {\n if (window.location.hash) {\n scrollToHashTargetOnNextFrame(window.location.hash);\n }\n return;\n }\n\n const y = Number(state.__vinext_scrollY);\n const x = \"__vinext_scrollX\" in state ? Number(state.__vinext_scrollX) : 0;\n\n requestAnimationFrame(() => {\n window.scrollTo(x, y);\n });\n}\n\nfunction isSameAppRoutePopstateTarget(href: string): boolean {\n if (!hasBrowserRouterState()) return false;\n\n const target = new URL(href, window.location.origin);\n const routerState = getBrowserRouterState();\n const targetPathname = stripBasePath(target.pathname, __basePath);\n const targetSearch = new URLSearchParams(target.search).toString();\n const currentSearch = routerState.navigationSnapshot.searchParams.toString();\n\n return (\n targetPathname === routerState.navigationSnapshot.pathname && targetSearch === currentSearch\n );\n}\n\n// Set on pagehide so the RSC navigation catch block can distinguish expected\n// fetch aborts (triggered by the unload itself) from real errors worth logging.\nlet isPageUnloading = false;\n\nconst RSC_RELOAD_KEY = \"__vinext_rsc_initial_reload__\";\n\n// sessionStorage can throw SecurityError in strict-mode iframes, storage-\n// disabled browsers, and some Safari private-browsing configurations. Wrap\n// every access so a recovery path for one error does not crash hydration.\nfunction readReloadFlag(): string | null {\n try {\n return sessionStorage.getItem(RSC_RELOAD_KEY);\n } catch {\n return null;\n }\n}\nfunction writeReloadFlag(path: string): void {\n try {\n sessionStorage.setItem(RSC_RELOAD_KEY, path);\n } catch {}\n}\nfunction clearReloadFlag(): void {\n try {\n sessionStorage.removeItem(RSC_RELOAD_KEY);\n } catch {}\n}\n\n// A non-ok or wrong-content-type RSC response during initial hydration means\n// the server cannot deliver a valid RSC payload for this URL. Parsing the\n// response as RSC causes an opaque parse failure. On the first attempt,\n// reload once so the server has a chance to render the correct error page\n// as HTML. On the second attempt (detected via the sessionStorage flag), the\n// endpoint is persistently broken. Returns null so main() aborts the\n// hydration bootstrap without registering RSC navigation globals —\n// including during the brief window between reload() firing and the page\n// actually unloading — so external probes never see a half-hydrated page.\nfunction recoverFromBadInitialRscResponse(reason: string): null {\n const currentPath = window.location.pathname + window.location.search;\n if (readReloadFlag() === currentPath) {\n clearReloadFlag();\n console.error(\n `[vinext] Initial RSC fetch ${reason} after reload; aborting hydration. ` +\n \"Server-rendered HTML remains visible; client components will not hydrate.\",\n );\n return null;\n }\n writeReloadFlag(currentPath);\n // Verify the write persisted. In storage-denied environments (strict-mode\n // iframes, locked-down enterprise policies), every getItem returns null and\n // every setItem silently no-ops, so the reload-loop guard cannot survive\n // the reload — the page would loop forever. Abort instead so the user at\n // least sees the server-rendered HTML.\n if (readReloadFlag() !== currentPath) {\n console.error(\n `[vinext] Initial RSC fetch ${reason}; sessionStorage unavailable so the ` +\n \"reload-loop guard cannot persist — aborting hydration. \" +\n \"Server-rendered HTML remains visible; client components will not hydrate.\",\n );\n return null;\n }\n // One-shot diagnostic so a production reload is traceable. Only fires once\n // per broken path thanks to the sessionStorage flag above; not noisy.\n console.warn(\n `[vinext] Initial RSC fetch ${reason}; reloading once to let the server render the HTML error page`,\n );\n window.location.reload();\n return null;\n}\n\nasync function readInitialRscStream(): Promise<ReadableStream<Uint8Array> | null> {\n const vinext = getVinextBrowserGlobal();\n const runtimeRsc = getNavigationRuntime()?.bootstrap.rsc;\n\n if (runtimeRsc || vinext.__VINEXT_RSC_CHUNKS__ || vinext.__VINEXT_RSC_DONE__) {\n // Reaching the embedded-RSC branch means the server successfully rendered\n // the page — any prior reload flag for this path is stale and must be\n // cleared so a future failure gets its own fresh recovery attempt.\n clearReloadFlag();\n clearHardNavigationLoopGuard();\n\n if (runtimeRsc) {\n applyRuntimeRscBootstrap(runtimeRsc);\n if (runtimeRsc.done) {\n registerNavigationRuntimeBootstrap({ rsc: undefined });\n return chunksToReadableStream(runtimeRsc.rsc);\n }\n // The progressive stream must capture this bootstrap object before any\n // cleanup clears it from the runtime.\n return createProgressiveRscStream();\n }\n\n const params = vinext.__VINEXT_RSC_PARAMS__ ?? {};\n if (vinext.__VINEXT_RSC_PARAMS__) {\n applyClientParams(vinext.__VINEXT_RSC_PARAMS__);\n }\n if (vinext.__VINEXT_RSC_NAV__) {\n restoreHydrationNavigationContext(\n vinext.__VINEXT_RSC_NAV__.pathname,\n vinext.__VINEXT_RSC_NAV__.searchParams,\n params,\n );\n }\n\n return createProgressiveRscStream();\n }\n\n const rscHeaders = createRscRequestHeaders();\n const rscResponse = await fetch(\n await createRscRequestUrl(window.location.pathname + window.location.search, rscHeaders),\n { credentials: \"include\", headers: rscHeaders },\n );\n\n if (!rscResponse.ok) {\n return recoverFromBadInitialRscResponse(`returned ${rscResponse.status}`);\n }\n // Guard against proxies/CDNs that return 200 with a rewritten Content-Type\n // (e.g. text/html instead of text/x-component). Such responses cannot be\n // parsed as RSC and would throw the same opaque parse error this fallback\n // exists to prevent.\n const contentType = rscResponse.headers.get(\"content-type\") ?? \"\";\n if (!contentType.startsWith(VINEXT_RSC_CONTENT_TYPE)) {\n return recoverFromBadInitialRscResponse(\n `returned non-RSC content-type \"${contentType || \"(missing)\"}\"`,\n );\n }\n // Missing body (e.g. 204 No Content, or an edge worker that returned ok\n // headers without piping the stream) fails the same way downstream.\n // Matches Next.js' `!res.body` branch in fetch-server-response.ts.\n if (!rscResponse.body) {\n return recoverFromBadInitialRscResponse(\"returned empty body\");\n }\n // Successful RSC response clears the guard so a subsequent reload of the\n // same path after a transient failure still gets one recovery attempt.\n clearReloadFlag();\n clearHardNavigationLoopGuard();\n\n // Ignore malformed param headers and continue with hydration. The original\n // try/catch also swallowed errors from applyClientParams; preserve that.\n const parsedParams = parseEncodedJsonHeader<Record<string, string | string[]>>(\n rscResponse.headers.get(VINEXT_PARAMS_HEADER),\n );\n const params: Record<string, string | string[]> = parsedParams ?? {};\n if (parsedParams) {\n try {\n applyClientParams(parsedParams);\n } catch {\n // Ignore — matches the previous combined try/catch behavior.\n }\n }\n\n restoreHydrationNavigationContext(window.location.pathname, window.location.search, params);\n\n return rscResponse.body;\n}\n\nfunction applyRuntimeRscBootstrap(rsc: NavigationRuntimeRscBootstrap): void {\n const params = rsc.params ?? {};\n if (rsc.params) {\n applyClientParams(rsc.params);\n }\n if (rsc.nav) {\n restoreHydrationNavigationContext(rsc.nav.pathname, rsc.nav.searchParams, params);\n }\n}\n\nfunction registerServerActionCallback(): void {\n setServerCallback(async (id, args) => {\n const temporaryReferences = createTemporaryReferenceSet();\n\n // Carry the interception context + mounted slots from the current router\n // state so the server-action re-render rebuilds the intercepted tree\n // instead of replacing it with the direct page. Parity with Next.js,\n // which sends `Next-URL` on action POSTs when the current tree contains\n // an interception route.\n const actionInitiation = createActionInitiationSnapshot();\n // Keep history aligned with the captured snapshot. Action POST headers\n // read from actionInitiation, not from history, after this point.\n syncCurrentHistoryStatePreviousNextUrl(actionInitiation.routerState.previousNextUrl);\n const body = await encodeReply(args, { temporaryReferences });\n const { headers } = resolveServerActionRequestState({\n actionId: id,\n basePath: __basePath,\n elements: actionInitiation.routerState.elements,\n previousNextUrl: actionInitiation.routerState.previousNextUrl,\n });\n\n const fetchResponse = await fetch(await createRscRequestUrl(actionInitiation.path, headers), {\n method: \"POST\",\n headers,\n body,\n });\n\n // Surface an `UnrecognizedActionError` so client `catch` blocks can detect\n // client/server deployment skew via `unstable_isUnrecognizedActionError`.\n throwOnServerActionNotFound(fetchResponse, id);\n\n const actionRedirect = fetchResponse.headers.get(ACTION_REDIRECT_HEADER);\n if (actionRedirect) {\n if (isDangerousScheme(actionRedirect)) {\n console.error(DANGEROUS_URL_BLOCK_MESSAGE);\n return undefined;\n }\n\n const redirectType = fetchResponse.headers.get(ACTION_REDIRECT_TYPE_HEADER) ?? \"push\";\n const historyUpdateMode = redirectType === \"push\" ? \"push\" : \"replace\";\n const hardNavigationMode = historyUpdateMode === \"push\" ? \"assign\" : \"replace\";\n let redirectLocation: ReturnType<typeof resolveServerActionRedirectLocation>;\n try {\n redirectLocation = resolveServerActionRedirectLocation({\n currentHref: actionInitiation.href,\n location: actionRedirect,\n origin: window.location.origin,\n });\n } catch {\n clearClientNavigationCaches();\n browserNavigationController.performHardNavigation(actionRedirect, hardNavigationMode);\n return undefined;\n }\n\n clearClientNavigationCaches();\n startTransition(() => {\n void navigateClientSide(redirectLocation.href, historyUpdateMode, true, true);\n });\n return undefined;\n }\n\n if (\n resolveRscCompatibilityNavigationDecision({\n clientCompatibilityId: CLIENT_RSC_COMPATIBILITY_ID,\n currentHref: actionInitiation.href,\n origin: window.location.origin,\n responseCompatibilityId: fetchResponse.headers.get(VINEXT_RSC_COMPATIBILITY_ID_HEADER),\n responseUrl: fetchResponse.url,\n }).kind === \"hard-navigate\"\n ) {\n browserNavigationController.performHardNavigation(actionInitiation.href);\n return undefined;\n }\n\n const revalidation = parseServerActionRevalidationHeader(fetchResponse.headers);\n const result = await createFromFetch<ServerActionResult | AppWireElements>(\n Promise.resolve(fetchResponse),\n { temporaryReferences },\n );\n if (shouldClearClientNavigationCachesForServerActionResult(result, revalidation)) {\n clearClientNavigationCaches();\n }\n\n // Server actions stay on the same URL and use commitSameUrlNavigatePayload()\n // for merge-based dispatch. This path does not call\n // activateNavigationSnapshot() because there is no URL change to commit, so\n // hooks continue reading the live external-store values directly. If server\n // actions ever trigger URL changes via RSC payload (instead of hard\n // redirects), this would need renderNavigationPayload().\n if (isServerActionResult(result)) {\n if (result.root !== undefined) {\n return commitSameUrlNavigatePayload(\n Promise.resolve(AppElementsWire.decode(result.root)),\n actionInitiation,\n result.returnValue,\n revalidation,\n );\n }\n\n if (result.returnValue) {\n if (!result.returnValue.ok) {\n throw result.returnValue.data;\n }\n return result.returnValue.data;\n }\n\n return undefined;\n }\n\n return commitSameUrlNavigatePayload(\n Promise.resolve(AppElementsWire.decode(result)),\n actionInitiation,\n undefined,\n revalidation,\n );\n });\n}\n\nasync function main(): Promise<void> {\n registerServerActionCallback();\n\n const rscStream = await readInitialRscStream();\n // null signals that readInitialRscStream aborted hydration — either because\n // a reload is in flight (first-attempt recovery) or the endpoint is\n // persistently broken (post-reload). Bootstrap is a separate synchronous\n // helper so the null-branch structurally cannot reach any RSC bootstrap\n // global assignment, even if a future refactor interposes async work here.\n if (rscStream === null) return;\n bootstrapHydration(rscStream);\n}\n\nfunction bootstrapHydration(rscStream: ReadableStream<Uint8Array>): void {\n if (import.meta.env.DEV) {\n installDevErrorOverlay();\n }\n\n const root = decodeAppElementsPromise(createFromReadableStream<AppWireElements>(rscStream));\n const initialNavigationSnapshot = createClientNavigationRenderSnapshot(\n window.location.href,\n latestClientParams,\n );\n replaceHistoryStateWithoutNotify(\n createHistoryStateWithNavigationMetadata(window.history.state, {\n previousNextUrl: null,\n traversalIndex: currentHistoryTraversalIndex,\n }),\n \"\",\n window.location.href,\n );\n\n // In dev we route uncaught errors into the dev overlay rather than the\n // hard-nav recovery: the overlay is what the developer needs to see, and a\n // recovery nav would wipe it. In prod we keep the recovery hard-nav so the\n // user lands on a renderable URL with the actual error UI.\n const onUncaughtError = import.meta.env.DEV\n ? devOnUncaughtError\n : createOnUncaughtError(() => pendingNavigationRecoveryHref);\n const formState = consumeInitialFormState(getVinextBrowserGlobal());\n const hydrateRootOptions = import.meta.env.DEV\n ? createVinextHydrateRootOptions({\n formState,\n onCaughtError: devOnCaughtError,\n onUncaughtError,\n })\n : createVinextHydrateRootOptions({\n formState,\n onUncaughtError,\n });\n window.__VINEXT_RSC_ROOT__ = hydrateRootInTransition({\n children: createElement(BrowserRoot, {\n initialElements: root,\n initialNavigationSnapshot,\n }),\n container: document,\n hydrateRoot,\n options: hydrateRootOptions,\n startTransition,\n });\n\n const navigateRsc: NavigationRuntimeNavigate = async function navigateRsc(\n href: string,\n redirectDepth = 0,\n navigationKind: NavigationKind = \"navigate\",\n historyUpdateMode?: HistoryUpdateMode,\n previousNextUrlOverride?: string | null,\n programmaticTransition = false,\n traversalIntent?: HistoryTraversalIntent,\n ): Promise<void> {\n let pendingRouterState: PendingBrowserRouterState | null = null;\n // Hoist navId above try so the catch and finally blocks can reference it.\n const navId = browserNavigationController.beginNavigation();\n discardedServerActionRefreshScheduler.markNavigationStart();\n\n // Loop variables for inline redirect following. On a redirect, these are\n // updated and the loop continues without returning or re-entering navigateRsc,\n // so a single pendingRouterState spans all hops and isPending never flashes.\n let currentHref = href;\n let currentHistoryMode = historyUpdateMode;\n let currentPrevNextUrl = previousNextUrlOverride;\n let redirectCount = redirectDepth;\n let detachedNavigationCommits = false;\n const activeTraversalIntent =\n navigationKind === \"traverse\"\n ? (traversalIntent ??\n resolveHistoryTraversalIntent({\n currentHistoryIndex: currentHistoryTraversalIndex,\n historyState: window.history.state,\n }))\n : null;\n\n try {\n const shouldUsePendingRouterState = programmaticTransition;\n if (shouldUsePendingRouterState && hasBrowserRouterState()) {\n pendingRouterState = beginPendingBrowserRouterState();\n } else {\n await waitForBrowserRouterStateReady();\n if (!browserNavigationController.isCurrentNavigation(navId)) return;\n\n if (shouldUsePendingRouterState) {\n pendingRouterState = beginPendingBrowserRouterState();\n }\n }\n\n while (true) {\n const url = new URL(currentHref, window.location.origin);\n const requestState = getRequestState(\n navigationKind,\n url.pathname,\n currentPrevNextUrl,\n activeTraversalIntent?.historyState,\n );\n const requestInterceptionContext = requestState.interceptionContext;\n const requestPreviousNextUrl = requestState.previousNextUrl;\n if (navigationKind === \"refresh\") {\n syncCurrentHistoryStatePreviousNextUrl(requestPreviousNextUrl);\n }\n\n // Set this navigation as the pending pathname, overwriting any previous.\n // Pass navId so only this navigation (or a newer one) can clear it later.\n setPendingPathname(url.pathname, navId);\n\n const elementsAtNavStart = getBrowserRouterState().elements;\n const mountedSlotsHeader = getMountedSlotIdsHeader(elementsAtNavStart);\n const requestHeaders = createRscRequestHeaders({\n interceptionContext: requestInterceptionContext,\n renderMode:\n navigationKind === \"refresh\" ? APP_RSC_RENDER_MODE_REFRESH_PRESERVE_UI : undefined,\n });\n if (mountedSlotsHeader) {\n requestHeaders.set(VINEXT_MOUNTED_SLOTS_HEADER, mountedSlotsHeader);\n }\n const rscUrl = await createRscRequestUrl(url.pathname + url.search, requestHeaders);\n const cachedRoute = getVisitedResponse(\n rscUrl,\n requestInterceptionContext,\n mountedSlotsHeader,\n navigationKind,\n );\n if (cachedRoute) {\n const compatibilityDecision = resolveRscCompatibilityNavigationDecision({\n clientCompatibilityId: CLIENT_RSC_COMPATIBILITY_ID,\n currentHref,\n origin: window.location.origin,\n responseCompatibilityId: cachedRoute.response.compatibilityIdHeader,\n responseUrl: cachedRoute.response.url,\n });\n if (compatibilityDecision.kind === \"hard-navigate\") {\n browserNavigationController.performHardNavigation(\n compatibilityDecision.hardNavigationTarget,\n );\n return;\n }\n // Check stale-navigation before and after createFromFetch. The pre-check\n // avoids wasted parse work; the post-check catches supersessions that\n // occur during the await. createFromFetch on a buffered response is fast\n // but still async, so the window exists. The non-cached path (below) places\n // its heavyweight async steps (fetch, body.tee + createFromFetch on the\n // live RSC branch) between navId checks consistently; the cached path omits\n // the check between createClientNavigationRenderSnapshot (synchronous) and\n // createFromFetch because there is no await in that gap.\n if (!browserNavigationController.isCurrentNavigation(navId)) return;\n const cachedParams = cachedRoute.params;\n // createClientNavigationRenderSnapshot is synchronous (URL parsing + param\n // wrapping only) — no stale-navigation recheck needed between here and the\n // next await.\n const cachedNavigationSnapshot = createClientNavigationRenderSnapshot(\n currentHref,\n cachedParams,\n );\n const cachedPayload = decodeAppElementsPromise(\n createFromFetch<AppWireElements>(\n Promise.resolve(restoreRscResponse(cachedRoute.response)),\n ),\n );\n if (!browserNavigationController.isCurrentNavigation(navId)) return;\n await renderNavigationPayload(\n cachedPayload,\n cachedNavigationSnapshot,\n currentHref,\n navId,\n currentHistoryMode,\n cachedParams,\n requestPreviousNextUrl,\n detachedNavigationCommits ? null : pendingRouterState,\n VISITED_CACHE_APP_NAVIGATION_PAYLOAD_ORIGIN,\n toActionType(navigationKind),\n toOperationLane(navigationKind),\n activeTraversalIntent,\n );\n return;\n }\n\n // Continue using the slot state captured at navigation start for fetches\n // and prefetch compatibility decisions.\n\n let navResponse: Response | undefined;\n let navResponseUrl: string | null = null;\n if (navigationKind !== \"refresh\") {\n const prefetchedResponse = consumePrefetchResponse(\n rscUrl,\n requestInterceptionContext,\n mountedSlotsHeader,\n );\n if (prefetchedResponse) {\n navResponse = restoreRscResponse(prefetchedResponse, false);\n navResponseUrl = prefetchedResponse.url;\n }\n }\n\n if (!navResponse && navigationKind === \"navigate\") {\n const routeManifest = getBrowserRouteManifest();\n await learnOptimisticRouteTemplatesFromPrefetchCache({\n interceptionContext: requestInterceptionContext,\n mountedSlotsHeader,\n routeManifest,\n });\n if (!browserNavigationController.isCurrentNavigation(navId)) return;\n\n if (routeManifest !== null) {\n const optimisticPayload = resolveOptimisticNavigationPayload({\n basePath: __basePath,\n href: currentHref,\n interceptionContext: requestInterceptionContext,\n mountedSlotsHeader,\n routeManifest,\n templates: optimisticRouteTemplates,\n });\n\n if (optimisticPayload !== null) {\n detachedNavigationCommits = true;\n const optimisticNavigationSnapshot = createClientNavigationRenderSnapshot(\n currentHref,\n optimisticPayload.params,\n );\n // The optimistic shell is a detached commit for this navigation.\n // It uses the same navId gate as the real payload, while the real\n // payload skips pending-router-state reuse via\n // detachedNavigationCommits. That keeps late optimistic errors or\n // transitions from mutating a newer navigation or sharing mutable\n // pending state with the authoritative render.\n void renderNavigationPayload(\n Promise.resolve(optimisticPayload.elements),\n optimisticNavigationSnapshot,\n currentHref,\n navId,\n currentHistoryMode,\n optimisticPayload.params,\n requestPreviousNextUrl,\n null,\n FRESH_APP_NAVIGATION_PAYLOAD_ORIGIN,\n toActionType(navigationKind),\n toOperationLane(navigationKind),\n activeTraversalIntent,\n ).catch((error) => {\n if (browserNavigationController.isCurrentNavigation(navId)) {\n console.error(\"[vinext] Optimistic RSC navigation error:\", error);\n }\n });\n }\n }\n }\n\n if (!navResponse) {\n navResponse = await fetch(rscUrl, {\n headers: requestHeaders,\n credentials: \"include\",\n });\n }\n\n if (!browserNavigationController.isCurrentNavigation(navId)) return;\n\n // Any response that isn't a valid RSC payload (non-ok status,\n // missing/rewritten Content-Type, or missing body) means the server\n // returned something we cannot parse — typically an HTML error page\n // or a proxy-rewritten response. Parsing such a body as an RSC stream\n // throws a cryptic \"Connection closed\" error. Match Next.js behavior\n // (fetch-server-response.ts:211, `!isFlightResponse || !res.ok || !res.body`):\n // hard-navigate to the response URL so the server can render the correct\n // error page as HTML. The outer finally handles\n // settlePendingBrowserRouterState and clearPendingPathname on this\n // return path.\n //\n // Prefer the post-redirect response URL over `currentHref`: on a\n // redirect chain like `/old` → 307 → `/new` → 500, the browser's\n // fetch already followed the redirect, so `navResponse.url` is the\n // failing `/new` destination. Hard-navigating there directly avoids\n // bouncing off `/old` just to re-follow the same 307, which would\n // flash the wrong URL in the address bar and mis-key analytics.\n // Matches Next.js' `doMpaNavigation(responseUrl.toString())`. Falls\n // back to `currentHref` when no response URL is available.\n const navContentType = navResponse.headers.get(\"content-type\") ?? \"\";\n const isRscResponse = navContentType.startsWith(\"text/x-component\");\n if (!navResponse.ok || !isRscResponse || !navResponse.body) {\n const responseUrl = navResponseUrl ?? navResponse.url;\n browserNavigationController.performHardNavigation(\n resolveHardNavigationTargetFromRscResponse(\n responseUrl,\n currentHref,\n window.location.origin,\n ),\n );\n return;\n }\n\n const compatibilityDecision = resolveRscCompatibilityNavigationDecision({\n clientCompatibilityId: CLIENT_RSC_COMPATIBILITY_ID,\n currentHref,\n origin: window.location.origin,\n responseCompatibilityId: navResponse.headers.get(VINEXT_RSC_COMPATIBILITY_ID_HEADER),\n responseUrl: navResponseUrl ?? navResponse.url,\n });\n if (compatibilityDecision.kind === \"hard-navigate\") {\n browserNavigationController.performHardNavigation(\n compatibilityDecision.hardNavigationTarget,\n );\n return;\n }\n\n const redirectDecision = resolveRscRedirectLifecycleHop({\n currentHref,\n historyUpdateMode: currentHistoryMode ?? \"replace\",\n origin: window.location.origin,\n redirectDepth: redirectCount,\n requestPreviousNextUrl,\n responseUrl: navResponseUrl ?? navResponse.url,\n });\n\n if (redirectDecision.kind === \"terminal-hard-navigation\") {\n if (redirectDecision.reason === \"maxRedirectsExceeded\") {\n console.error(\n \"[vinext] Too many RSC redirects — aborting navigation to prevent infinite loop.\",\n );\n }\n browserNavigationController.performHardNavigation(redirectDecision.href);\n return;\n }\n\n if (redirectDecision.kind === \"follow\") {\n // Server-side redirect: keep the redirect chain inside this operation\n // and defer URL/history mutation to the eventual approved commit.\n // This keeps isPending true across all hops and avoids publishing a\n // destination URL before its RSC payload is lifecycle-approved.\n currentHref = redirectDecision.href;\n currentHistoryMode = redirectDecision.historyUpdateMode;\n currentPrevNextUrl = redirectDecision.previousNextUrl;\n redirectCount = redirectDecision.redirectDepth;\n continue;\n }\n\n // RSC redirect encoded as 200 + flight payload (the server's response\n // for `redirect()` thrown from a server component during RSC rendering;\n // see issue #1347 and `buildAppPageSpecialErrorResponse`). The flight\n // body carries the canonical `NEXT_REDIRECT;...` digest for clients\n // that decode it through React's RedirectBoundary, but vinext's\n // browser-navigation loop catches it ahead of decode via this\n // side-channel header so the redirect-following loop above can drain\n // the body and continue without bouncing through the catch path.\n // Reusing the same loop variables keeps `pendingRouterState` and the\n // outer `useTransition` pending state continuous across the hop —\n // matching the pre-1347 fetch-auto-follow-307 behavior.\n const flightRedirectTarget = navResponse.headers.get(VINEXT_RSC_REDIRECT_HEADER);\n if (flightRedirectTarget) {\n // Drain the response body so the underlying connection is released.\n // We do this best-effort: the destination's `.rsc` fetch on the next\n // loop iteration will replace this response entirely.\n void navResponse.body?.cancel().catch(() => {});\n const resolvedTarget = new URL(flightRedirectTarget, window.location.origin);\n if (resolvedTarget.origin !== window.location.origin) {\n browserNavigationController.performHardNavigation(resolvedTarget.href);\n return;\n }\n if (redirectCount >= MAX_RSC_REDIRECT_DEPTH) {\n console.error(\n \"[vinext] Too many RSC redirects — aborting navigation to prevent infinite loop.\",\n );\n browserNavigationController.performHardNavigation(resolvedTarget.href);\n return;\n }\n currentHref = `${resolvedTarget.pathname}${resolvedTarget.search}${resolvedTarget.hash}`;\n redirectCount += 1;\n continue;\n }\n\n // navParams falls back to {} on a missing or malformed header.\n const navParams: Record<string, string | string[]> =\n parseEncodedJsonHeader<Record<string, string | string[]>>(\n navResponse.headers.get(VINEXT_PARAMS_HEADER),\n ) ?? {};\n // Build snapshot from local params, not latestClientParams\n const navigationSnapshot = createClientNavigationRenderSnapshot(currentHref, navParams);\n\n // Tee the response body so React can consume it incrementally —\n // shell parses fast, and any Suspense boundary inside (e.g. the\n // route's loading.tsx) shows its fallback while the rest of the\n // RSC stream resolves. Buffering with `await response.arrayBuffer()`\n // here would block the commit until the page's slowest server\n // promise resolved, hiding the loading state entirely.\n //\n // The cache branch is read in the background so the visited-\n // response snapshot lands as soon as the full stream completes,\n // without holding up React's commit.\n const navBody = navResponse.body;\n if (!navBody) {\n // Already validated above (`!navResponse.body` triggers a hard\n // navigation), so this branch is unreachable — kept for type\n // narrowing only.\n return;\n }\n const [reactBranch, cacheBranch] = navBody.tee();\n const reactResponse = new Response(reactBranch, {\n status: navResponse.status,\n headers: navResponse.headers,\n });\n const cacheBufferPromise = new Response(cacheBranch).arrayBuffer();\n\n if (!browserNavigationController.isCurrentNavigation(navId)) return;\n\n const rscPayload = decodeAppElementsPromise(\n createFromFetch<AppWireElements>(Promise.resolve(reactResponse)),\n );\n\n if (!browserNavigationController.isCurrentNavigation(navId)) return;\n\n const renderOutcome = await renderNavigationPayload(\n rscPayload,\n navigationSnapshot,\n currentHref,\n navId,\n currentHistoryMode,\n navParams,\n requestPreviousNextUrl,\n detachedNavigationCommits ? null : pendingRouterState,\n FRESH_APP_NAVIGATION_PAYLOAD_ORIGIN,\n toActionType(navigationKind),\n toOperationLane(navigationKind),\n activeTraversalIntent,\n );\n if (renderOutcome !== \"committed\") return;\n // Don't cache the response if this navigation was superseded during\n // renderNavigationPayload's await — the elements were never dispatched.\n if (!browserNavigationController.isCurrentNavigation(navId)) return;\n // Store the visited response only after renderNavigationPayload succeeds.\n // If we stored it before and renderNavigationPayload threw, a future\n // back/forward navigation could replay a snapshot from a navigation that\n // never actually rendered successfully.\n const resolvedElements = await rscPayload;\n const metadata = AppElementsWire.readMetadata(resolvedElements);\n if (!isCacheRestorableAppPayloadMetadata(metadata)) {\n void cacheBufferPromise.catch(() => {});\n return;\n }\n void cacheBufferPromise\n .then((cacheBuffer) => {\n storeVisitedResponseSnapshot(\n rscUrl,\n resolveVisitedResponseInterceptionContext(\n requestInterceptionContext,\n metadata.interceptionContext,\n ),\n createCachedRscResponseSnapshot(navResponse, cacheBuffer, navResponseUrl),\n navParams,\n );\n })\n .catch(() => {});\n return;\n }\n } catch (error) {\n // Don't hard-navigate to a stale URL if this navigation was superseded by\n // a newer one — the newer navigation is already in flight and would be clobbered.\n if (!browserNavigationController.isCurrentNavigation(navId)) return;\n // Suppress the diagnostic when the page is unloading: a hard-nav or anchor\n // click tears down the document and aborts any in-flight RSC fetch, which\n // surfaces here as an error. The page is already going away, so the log\n // is just noise. Mirrors Next.js' isPageUnloading pattern.\n if (!isPageUnloading) {\n console.error(\"[vinext] RSC navigation error:\", error);\n }\n browserNavigationController.performHardNavigation(currentHref);\n } finally {\n // Single settlement site: covers normal return, early returns on stale-id\n // checks, and error paths. The finally runs even when the catch returns.\n // settlePendingBrowserRouterState is idempotent via the settled flag.\n browserNavigationController.finalizeNavigation(navId, pendingRouterState);\n discardedServerActionRefreshScheduler.markNavigationSettled();\n }\n };\n\n // Exposed through one typed runtime seam so next/navigation, Link, Form, and\n // the browser entry share a single App Router capability contract.\n registerNavigationRuntimeFunctions({\n clearNavigationCaches: clearClientNavigationCaches,\n commitHashNavigation: commitHashOnlyNavigation,\n navigate: navigateRsc,\n });\n\n if (\"scrollRestoration\" in history) {\n history.scrollRestoration = \"manual\";\n }\n\n // Note: This popstate handler runs for App Router (RSC navigation available).\n // It coordinates scroll restoration with the pending RSC navigation.\n // Pages Router scroll restoration is handled in shims/navigation.ts:1289 with\n // microtask-based deferral for compatibility with non-RSC navigation.\n // See: https://github.com/vercel/next.js/discussions/41934#discussioncomment-4602607\n const handlePopstate = createPopstateRestoreHandler({\n getActiveNavigationId: browserNavigationController.getActiveNavigationId.bind(\n browserNavigationController,\n ),\n getPendingNavigation: () => window.__VINEXT_RSC_PENDING__,\n getNavigate: () => getNavigationRuntime()?.functions.navigate,\n isCurrentNavigation: browserNavigationController.isCurrentNavigation.bind(\n browserNavigationController,\n ),\n notifyAppRouterTransitionStart: (href) => {\n notifyAppRouterTransitionStart(href, \"traverse\");\n },\n restorePopstateScrollPosition,\n setPendingNavigation: (pendingNavigation) => {\n window.__VINEXT_RSC_PENDING__ = pendingNavigation;\n },\n });\n\n window.addEventListener(\"popstate\", (event) => {\n // The browser has already applied the history entry by the time popstate\n // fires. App Router state does not include hashes, so matching the\n // committed pathname/search proves this traversal does not need a new RSC\n // payload. This covers both /page#target -> /page and /page -> /page#target.\n // Notify the transition start so observers still see the URL change, then\n // restore scroll directly and skip the RSC dispatch.\n const href = window.location.href;\n if (isSameAppRoutePopstateTarget(href)) {\n notifyAppRouterTransitionStart(href, \"traverse\");\n commitTraversalIndexFromHistoryState(event.state);\n restorePopstateScrollPosition(event.state);\n return;\n }\n handlePopstate(event);\n });\n\n if (import.meta.hot) {\n const handleRscUpdate = async (): Promise<void> => {\n try {\n // If BrowserRoot has been mounted before but isn't now, a render\n // error tore down the tree (e.g. a server route threw). HMR can't\n // dispatch into a missing setter, and waitForBrowserRouterStateReady\n // would block forever — the tree won't remount until the page reloads.\n // Trigger that reload so the user's fix actually lands without a\n // manual refresh. Cleared after a successful mount, so this only\n // fires once per teardown.\n if (\n browserRouterStateHasEverCommitted &&\n !browserNavigationController.hasBrowserRouterState()\n ) {\n window.location.reload();\n return;\n }\n // HMR can also fire before BrowserRoot's layout effect publishes\n // the browser router state (e.g. saving a file while the initial RSC\n // stream is still suspended). Wait for readiness, then re-check the\n // mounted state — readiness can race with cleanup, which nulls it again.\n // Skip silently when the tree is not currently mounted; the next\n // HMR push or full reload will reconcile.\n await waitForBrowserRouterStateReady();\n if (!browserNavigationController.hasBrowserRouterState()) {\n return;\n }\n clearClientNavigationCaches();\n const navigationSnapshot = createClientNavigationRenderSnapshot(\n window.location.href,\n latestClientParams,\n );\n // Clear stale errors from the dev overlay before dispatching the\n // fresh tree. If the new tree renders cleanly, the overlay stays\n // empty; if it throws again, devOnCaughtError/devOnUncaughtError\n // re-populates it. Without this, an old \"DropZone is not defined\"\n // error would linger after the developer fixed the bug.\n dismissOverlay();\n // Interception context on HMR re-renders is intentionally deferred:\n // preserving intercepted modal state across HMR reloads is out of scope\n // for the previousNextUrl mechanism.\n const hmrHeaders = createRscRequestHeaders();\n await browserNavigationController.hmrReplaceTree(\n decodeAppElementsPromise(\n createFromFetch<AppWireElements>(\n fetch(\n await createRscRequestUrl(\n window.location.pathname + window.location.search,\n hmrHeaders,\n ),\n { headers: hmrHeaders },\n ),\n ),\n ),\n navigationSnapshot,\n );\n } catch (error) {\n console.error(\"[vinext] RSC HMR error:\", error);\n }\n };\n\n import.meta.hot.on(\"rsc:update\", () => {\n void handleRscUpdate();\n });\n }\n}\n\nif (typeof document !== \"undefined\") {\n // Install `window.next` as early as possible so any client component that\n // synchronously dereferences it during hydration (or any third-party\n // library script tag that loads before the React tree mounts) sees the\n // expected shape. Mirrors Next.js's app-bootstrap.ts (line 13) which sets\n // `window.next = { version, appDir: true }` before the React runtime\n // initializes, and `app-router-instance.ts` (line 510) which assigns\n // `router: publicAppRouterInstance` at module load.\n installWindowNext({ appDir: true, router: appRouterInstance });\n\n window.addEventListener(\"pagehide\", () => {\n isPageUnloading = true;\n });\n // Reset on pageshow so a bfcache-restored document does not resume with\n // the flag stuck at true, which would silently swallow every subsequent\n // RSC navigation error for the lifetime of that tab. Matches Next.js'\n // fetch-server-response.ts handler pair.\n window.addEventListener(\"pageshow\", () => {\n isPageUnloading = false;\n });\n void main();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqJA,SAAS,aAAa,MAA+C;CACnE,OAAO,SAAS,aAAa,aAAa;;AAG5C,SAAS,gBAAgB,MAAqC;CAC5D,QAAQ,MAAR;EACE,KAAK,YACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,YACH,OAAO;EACT,SAEE,MAAM,IAAI,MAAM,uCAAuC,OAAOA,KAAY,CAAC;;;AAWjF,MAAM,kCAAkC;AACxC,MAAM,6BAA6B,IAAI;AACvC,MAAM,0BAA0B,KAAK;AACrC,MAAM,8BAA8B,6BAA6B;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YAA2B;GACjD,IAAI;IAQF,IACE,sCACA,CAAC,4BAA4B,uBAAuB,EACpD;KACA,OAAO,SAAS,QAAQ;KACxB;;IAQF,MAAM,gCAAgC;IACtC,IAAI,CAAC,4BAA4B,uBAAuB,EACtD;IAEF,6BAA6B;IAC7B,MAAM,qBAAqB,qCACzB,OAAO,SAAS,MAChB,mBACD;IAMD,gBAAgB;IAIhB,MAAM,aAAa,yBAAyB;IAC5C,MAAM,4BAA4B,eAChC,yBACE,gBACE,MACE,MAAM,oBACJ,OAAO,SAAS,WAAW,OAAO,SAAS,QAC3C,WACD,EACD,EAAE,SAAS,YAAY,CACxB,CACF,CACF,EACD,mBACD;YACM,OAAO;IACd,QAAQ,MAAM,2BAA2B,MAAM;;;EAInD,OAAO,KAAK,IAAI,GAAG,oBAAoB;GACrC,iBAAsB;IACtB;;;AAIN,IAAI,OAAO,aAAa,aAAa;CAQnC,kBAAkB;EAAE,QAAQ;EAAM,QAAQ;EAAmB,CAAC;CAE9D,OAAO,iBAAiB,kBAAkB;EACxC,kBAAkB;GAClB;CAKF,OAAO,iBAAiB,kBAAkB;EACxC,kBAAkB;GAClB;CACF,MAAW"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { normalizeMountedSlotsHeader } from "./app-mounted-slots-header.js";
|
|
2
1
|
import { APP_ARTIFACT_COMPATIBILITY_KEY, APP_CACHE_ENTRY_REUSE_PROOF_KEY, APP_INTERCEPTION_CONTEXT_KEY, APP_INTERCEPTION_KEY, APP_LAYOUT_FLAGS_KEY, APP_LAYOUT_IDS_KEY, APP_RENDER_OBSERVATION_KEY, APP_ROOT_LAYOUT_KEY, APP_ROUTE_KEY, APP_SLOT_BINDINGS_KEY, APP_UNMATCHED_SLOT_WIRE_VALUE, AppElementsWire, UNMATCHED_SLOT, buildOutgoingAppPayload, compareAppElementsSlotIds, isAppElementsRecord, normalizeAppElements, normalizeAppElementsSlotBindings, readAppElementsMetadata, withLayoutFlags } from "./app-elements-wire.js";
|
|
2
|
+
import { normalizeMountedSlotsHeader } from "./app-mounted-slots-header.js";
|
|
3
3
|
//#region src/server/app-elements.ts
|
|
4
4
|
const APP_PREFETCH_LOADING_SHELL_MARKER_KEY = "__prefetchLoadingShell";
|
|
5
5
|
function getMountedSlotIds(elements) {
|
|
@@ -51,14 +51,23 @@ type AppFallbackRendererOptions<TModule extends AppPageModule = AppPageModule> =
|
|
|
51
51
|
sanitizer: (error: Error) => Error;
|
|
52
52
|
ssrLoader: () => Promise<AppPageSsrHandler>;
|
|
53
53
|
};
|
|
54
|
+
type AppFallbackRendererCallContext = {
|
|
55
|
+
/**
|
|
56
|
+
* Whether the matched (or invoking) route opts into Next.js' edge runtime via
|
|
57
|
+
* `export const runtime = "edge"`. Propagated so boundary/error/not-found
|
|
58
|
+
* responses carry `x-edge-runtime: 1` for edge routes, matching the page
|
|
59
|
+
* render path. Defaults to `false` when no route is matched.
|
|
60
|
+
*/
|
|
61
|
+
isEdgeRuntime?: boolean;
|
|
62
|
+
};
|
|
54
63
|
type AppFallbackRenderer<TModule extends AppPageModule = AppPageModule> = {
|
|
55
|
-
renderErrorBoundary: (route: AppPageBoundaryRoute<TModule> | null, error: unknown, isRscRequest: boolean, request: Request, matchedParams: AppPageParams | undefined, scriptNonce: string | undefined, middlewareContext: AppPageMiddlewareContext) => Promise<Response | null>;
|
|
64
|
+
renderErrorBoundary: (route: AppPageBoundaryRoute<TModule> | null, error: unknown, isRscRequest: boolean, request: Request, matchedParams: AppPageParams | undefined, scriptNonce: string | undefined, middlewareContext: AppPageMiddlewareContext, callContext?: AppFallbackRendererCallContext) => Promise<Response | null>;
|
|
56
65
|
renderHttpAccessFallback: (route: AppPageBoundaryRoute<TModule> | null, statusCode: number, isRscRequest: boolean, request: Request, opts: {
|
|
57
66
|
boundaryComponent?: AppPageComponent | null;
|
|
58
67
|
layouts?: readonly (TModule | null | undefined)[] | null;
|
|
59
68
|
matchedParams?: AppPageParams;
|
|
60
|
-
}, scriptNonce: string | undefined, middlewareContext: AppPageMiddlewareContext) => Promise<Response | null>;
|
|
61
|
-
renderNotFound: (route: AppPageBoundaryRoute<TModule> | null, isRscRequest: boolean, request: Request, matchedParams: AppPageParams | undefined, scriptNonce: string | undefined, middlewareContext: AppPageMiddlewareContext) => Promise<Response | null>;
|
|
69
|
+
}, scriptNonce: string | undefined, middlewareContext: AppPageMiddlewareContext, callContext?: AppFallbackRendererCallContext) => Promise<Response | null>;
|
|
70
|
+
renderNotFound: (route: AppPageBoundaryRoute<TModule> | null, isRscRequest: boolean, request: Request, matchedParams: AppPageParams | undefined, scriptNonce: string | undefined, middlewareContext: AppPageMiddlewareContext, callContext?: AppFallbackRendererCallContext) => Promise<Response | null>;
|
|
62
71
|
};
|
|
63
72
|
declare function createAppFallbackRenderer<TModule extends AppPageModule>(options: AppFallbackRendererOptions<TModule>): AppFallbackRenderer<TModule>;
|
|
64
73
|
//#endregion
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { renderAppPageErrorBoundary, renderAppPageHttpAccessFallback } from "./app-page-boundary-render.js";
|
|
2
2
|
import { DEFAULT_GLOBAL_ERROR_MODULE } from "./default-global-error-module.js";
|
|
3
|
+
import { DEFAULT_NOT_FOUND_MODULE } from "./default-not-found-module.js";
|
|
3
4
|
//#region src/server/app-fallback-renderer.ts
|
|
4
5
|
const EMPTY_MW_CTX = {
|
|
5
6
|
headers: null,
|
|
@@ -9,8 +10,9 @@ function createAppFallbackRenderer(options) {
|
|
|
9
10
|
const { basePath = "", clearRequestContext, createRscOnErrorHandler: buildRscOnErrorHandler, fontProviders, getNavigationContext, globalErrorModule, globalNotFoundModule, makeThenableParams, metadataRoutes, resolveChildSegments, rootBoundaries, rscRenderer, sanitizer, ssrLoader } = options;
|
|
10
11
|
const { rootForbiddenModule, rootLayouts, rootNotFoundModule, rootUnauthorizedModule } = rootBoundaries;
|
|
11
12
|
const effectiveGlobalErrorModule = globalErrorModule ?? DEFAULT_GLOBAL_ERROR_MODULE;
|
|
13
|
+
const effectiveRootNotFoundModule = rootNotFoundModule ?? DEFAULT_NOT_FOUND_MODULE;
|
|
12
14
|
return {
|
|
13
|
-
renderHttpAccessFallback(route, statusCode, isRscRequest, request, opts, scriptNonce, middlewareContext) {
|
|
15
|
+
renderHttpAccessFallback(route, statusCode, isRscRequest, request, opts, scriptNonce, middlewareContext, callContext) {
|
|
14
16
|
if (statusCode === 404 && !!globalNotFoundModule && !route && !opts?.boundaryComponent) {
|
|
15
17
|
const globalNotFoundComponent = globalNotFoundModule?.default ?? null;
|
|
16
18
|
if (globalNotFoundComponent) return renderAppPageHttpAccessFallback({
|
|
@@ -25,6 +27,7 @@ function createAppFallbackRenderer(options) {
|
|
|
25
27
|
getFontStyles: fontProviders.getFontStyles,
|
|
26
28
|
getNavigationContext,
|
|
27
29
|
globalErrorModule: effectiveGlobalErrorModule,
|
|
30
|
+
isEdgeRuntime: callContext?.isEdgeRuntime,
|
|
28
31
|
isRscRequest,
|
|
29
32
|
layoutModules: [],
|
|
30
33
|
loadSsrHandler: ssrLoader,
|
|
@@ -58,6 +61,7 @@ function createAppFallbackRenderer(options) {
|
|
|
58
61
|
getFontStyles: fontProviders.getFontStyles,
|
|
59
62
|
getNavigationContext,
|
|
60
63
|
globalErrorModule: effectiveGlobalErrorModule,
|
|
64
|
+
isEdgeRuntime: callContext?.isEdgeRuntime,
|
|
61
65
|
isRscRequest,
|
|
62
66
|
layoutModules: opts?.layouts ?? null,
|
|
63
67
|
loadSsrHandler: ssrLoader,
|
|
@@ -69,7 +73,7 @@ function createAppFallbackRenderer(options) {
|
|
|
69
73
|
resolveChildSegments,
|
|
70
74
|
rootForbiddenModule,
|
|
71
75
|
rootLayouts,
|
|
72
|
-
rootNotFoundModule,
|
|
76
|
+
rootNotFoundModule: effectiveRootNotFoundModule,
|
|
73
77
|
rootUnauthorizedModule,
|
|
74
78
|
route,
|
|
75
79
|
renderToReadableStream: rscRenderer,
|
|
@@ -77,10 +81,10 @@ function createAppFallbackRenderer(options) {
|
|
|
77
81
|
statusCode
|
|
78
82
|
});
|
|
79
83
|
},
|
|
80
|
-
renderNotFound(route, isRscRequest, request, matchedParams, scriptNonce, middlewareContext) {
|
|
81
|
-
return this.renderHttpAccessFallback(route, 404, isRscRequest, request, { matchedParams }, scriptNonce, middlewareContext);
|
|
84
|
+
renderNotFound(route, isRscRequest, request, matchedParams, scriptNonce, middlewareContext, callContext) {
|
|
85
|
+
return this.renderHttpAccessFallback(route, 404, isRscRequest, request, { matchedParams }, scriptNonce, middlewareContext, callContext);
|
|
82
86
|
},
|
|
83
|
-
renderErrorBoundary(route, error, isRscRequest, request, matchedParams, scriptNonce, middlewareContext) {
|
|
87
|
+
renderErrorBoundary(route, error, isRscRequest, request, matchedParams, scriptNonce, middlewareContext, callContext) {
|
|
84
88
|
return renderAppPageErrorBoundary({
|
|
85
89
|
basePath,
|
|
86
90
|
buildFontLinkHeader: fontProviders.buildFontLinkHeader,
|
|
@@ -94,6 +98,7 @@ function createAppFallbackRenderer(options) {
|
|
|
94
98
|
getFontStyles: fontProviders.getFontStyles,
|
|
95
99
|
getNavigationContext,
|
|
96
100
|
globalErrorModule: effectiveGlobalErrorModule,
|
|
101
|
+
isEdgeRuntime: callContext?.isEdgeRuntime,
|
|
97
102
|
isRscRequest,
|
|
98
103
|
loadSsrHandler: ssrLoader,
|
|
99
104
|
makeThenableParams,
|