vinext 0.0.54 → 0.0.55

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.
Files changed (135) hide show
  1. package/README.md +1 -0
  2. package/dist/check.js +15 -3
  3. package/dist/check.js.map +1 -1
  4. package/dist/client/navigation-runtime.d.ts +1 -0
  5. package/dist/client/navigation-runtime.js +1 -1
  6. package/dist/client/navigation-runtime.js.map +1 -1
  7. package/dist/config/next-config.d.ts +14 -1
  8. package/dist/config/next-config.js +24 -4
  9. package/dist/config/next-config.js.map +1 -1
  10. package/dist/config/tsconfig-paths.d.ts +12 -3
  11. package/dist/config/tsconfig-paths.js +55 -24
  12. package/dist/config/tsconfig-paths.js.map +1 -1
  13. package/dist/entries/app-rsc-entry.d.ts +2 -1
  14. package/dist/entries/app-rsc-entry.js +12 -0
  15. package/dist/entries/app-rsc-entry.js.map +1 -1
  16. package/dist/entries/app-rsc-manifest.js +22 -5
  17. package/dist/entries/app-rsc-manifest.js.map +1 -1
  18. package/dist/entries/pages-server-entry.js +41 -4
  19. package/dist/entries/pages-server-entry.js.map +1 -1
  20. package/dist/index.js +81 -39
  21. package/dist/index.js.map +1 -1
  22. package/dist/plugins/import-meta-url.d.ts +16 -0
  23. package/dist/plugins/import-meta-url.js +193 -0
  24. package/dist/plugins/import-meta-url.js.map +1 -0
  25. package/dist/server/app-browser-action-result.d.ts +9 -16
  26. package/dist/server/app-browser-action-result.js +25 -14
  27. package/dist/server/app-browser-action-result.js.map +1 -1
  28. package/dist/server/app-browser-entry.js +171 -45
  29. package/dist/server/app-browser-entry.js.map +1 -1
  30. package/dist/server/app-browser-mpa-navigation.d.ts +16 -0
  31. package/dist/server/app-browser-mpa-navigation.js +36 -0
  32. package/dist/server/app-browser-mpa-navigation.js.map +1 -0
  33. package/dist/server/app-browser-popstate.d.ts +3 -1
  34. package/dist/server/app-browser-popstate.js +15 -1
  35. package/dist/server/app-browser-popstate.js.map +1 -1
  36. package/dist/server/app-browser-state.js +2 -1
  37. package/dist/server/app-browser-state.js.map +1 -1
  38. package/dist/server/app-layout-param-observation.d.ts +30 -0
  39. package/dist/server/app-layout-param-observation.js +130 -0
  40. package/dist/server/app-layout-param-observation.js.map +1 -0
  41. package/dist/server/app-page-boundary-render.js +2 -2
  42. package/dist/server/app-page-boundary-render.js.map +1 -1
  43. package/dist/server/app-page-dispatch.js +1 -1
  44. package/dist/server/app-page-params.d.ts +2 -1
  45. package/dist/server/app-page-params.js +14 -1
  46. package/dist/server/app-page-params.js.map +1 -1
  47. package/dist/server/app-page-probe.d.ts +12 -1
  48. package/dist/server/app-page-probe.js +116 -1
  49. package/dist/server/app-page-probe.js.map +1 -1
  50. package/dist/server/app-route-handler-response.js +1 -1
  51. package/dist/server/app-route-handler-response.js.map +1 -1
  52. package/dist/server/app-rsc-cache-busting.d.ts +3 -2
  53. package/dist/server/app-rsc-cache-busting.js +9 -7
  54. package/dist/server/app-rsc-cache-busting.js.map +1 -1
  55. package/dist/server/app-rsc-handler.js +11 -1
  56. package/dist/server/app-rsc-handler.js.map +1 -1
  57. package/dist/server/app-segment-config.d.ts +1 -1
  58. package/dist/server/app-segment-config.js +4 -1
  59. package/dist/server/app-segment-config.js.map +1 -1
  60. package/dist/server/app-server-action-execution.d.ts +5 -0
  61. package/dist/server/app-server-action-execution.js +198 -22
  62. package/dist/server/app-server-action-execution.js.map +1 -1
  63. package/dist/server/artifact-compatibility.d.ts +2 -1
  64. package/dist/server/artifact-compatibility.js +10 -1
  65. package/dist/server/artifact-compatibility.js.map +1 -1
  66. package/dist/server/client-reuse-manifest.d.ts +9 -4
  67. package/dist/server/client-reuse-manifest.js +2 -1
  68. package/dist/server/client-reuse-manifest.js.map +1 -1
  69. package/dist/server/dev-server.js +52 -10
  70. package/dist/server/dev-server.js.map +1 -1
  71. package/dist/server/document-initial-head.d.ts +7 -0
  72. package/dist/server/document-initial-head.js +35 -0
  73. package/dist/server/document-initial-head.js.map +1 -0
  74. package/dist/server/pages-document-initial-props.d.ts +84 -2
  75. package/dist/server/pages-document-initial-props.js +127 -1
  76. package/dist/server/pages-document-initial-props.js.map +1 -1
  77. package/dist/server/pages-node-compat.js +1 -1
  78. package/dist/server/pages-page-response.d.ts +14 -0
  79. package/dist/server/pages-page-response.js +31 -8
  80. package/dist/server/pages-page-response.js.map +1 -1
  81. package/dist/server/prod-server.js +13 -6
  82. package/dist/server/prod-server.js.map +1 -1
  83. package/dist/server/skip-cache-proof.d.ts +23 -2
  84. package/dist/server/skip-cache-proof.js +81 -12
  85. package/dist/server/skip-cache-proof.js.map +1 -1
  86. package/dist/server/static-layout-client-reuse-proof.d.ts +16 -0
  87. package/dist/server/static-layout-client-reuse-proof.js +35 -0
  88. package/dist/server/static-layout-client-reuse-proof.js.map +1 -0
  89. package/dist/shims/cache.d.ts +21 -1
  90. package/dist/shims/cache.js +101 -6
  91. package/dist/shims/cache.js.map +1 -1
  92. package/dist/shims/document.d.ts +6 -0
  93. package/dist/shims/document.js +7 -8
  94. package/dist/shims/document.js.map +1 -1
  95. package/dist/shims/error-boundary.d.ts +4 -4
  96. package/dist/shims/error-boundary.js +27 -28
  97. package/dist/shims/error-boundary.js.map +1 -1
  98. package/dist/shims/fetch-cache.d.ts +3 -1
  99. package/dist/shims/fetch-cache.js +16 -5
  100. package/dist/shims/fetch-cache.js.map +1 -1
  101. package/dist/shims/hash-scroll.d.ts +4 -1
  102. package/dist/shims/hash-scroll.js +13 -1
  103. package/dist/shims/hash-scroll.js.map +1 -1
  104. package/dist/shims/head-state.d.ts +1 -0
  105. package/dist/shims/head-state.js +18 -3
  106. package/dist/shims/head-state.js.map +1 -1
  107. package/dist/shims/head.d.ts +35 -1
  108. package/dist/shims/head.js +113 -14
  109. package/dist/shims/head.js.map +1 -1
  110. package/dist/shims/internal/pages-data-fetch-dedup.d.ts +56 -0
  111. package/dist/shims/internal/pages-data-fetch-dedup.js +70 -0
  112. package/dist/shims/internal/pages-data-fetch-dedup.js.map +1 -0
  113. package/dist/shims/link.js +28 -2
  114. package/dist/shims/link.js.map +1 -1
  115. package/dist/shims/navigation.d.ts +39 -1
  116. package/dist/shims/navigation.js +61 -13
  117. package/dist/shims/navigation.js.map +1 -1
  118. package/dist/shims/router.js +37 -17
  119. package/dist/shims/router.js.map +1 -1
  120. package/dist/shims/thenable-params.d.ts +5 -2
  121. package/dist/shims/thenable-params.js +25 -1
  122. package/dist/shims/thenable-params.js.map +1 -1
  123. package/dist/shims/unified-request-context.js +3 -0
  124. package/dist/shims/unified-request-context.js.map +1 -1
  125. package/dist/utils/client-build-manifest.d.ts +15 -0
  126. package/dist/utils/client-build-manifest.js +54 -0
  127. package/dist/utils/client-build-manifest.js.map +1 -0
  128. package/dist/utils/hash.js +1 -1
  129. package/dist/utils/hash.js.map +1 -1
  130. package/dist/utils/lazy-chunks.d.ts +1 -1
  131. package/dist/utils/lazy-chunks.js.map +1 -1
  132. package/dist/utils/vite-version.d.ts +11 -0
  133. package/dist/utils/vite-version.js +36 -0
  134. package/dist/utils/vite-version.js.map +1 -0
  135. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"pages-server-entry.js","names":[],"sources":["../../src/entries/pages-server-entry.ts"],"sourcesContent":["/**\n * Pages Router server entry generator.\n *\n * Generates the virtual SSR server entry module (`virtual:vinext-server-entry`).\n * This is the entry point for `vite build --ssr`. It handles SSR, API routes,\n * middleware, ISR, and i18n for the Pages Router.\n *\n * Extracted from index.ts.\n */\nimport { resolveEntryPath } from \"./runtime-entry-module.js\";\nimport { normalizePathSeparators } from \"../utils/path.js\";\nimport { pagesRouter, apiRouter, type Route } from \"../routing/pages-router.js\";\nimport { createValidFileMatcher } from \"../routing/file-matcher.js\";\nimport { type ResolvedNextConfig } from \"../config/next-config.js\";\nimport { isProxyFile } from \"../server/middleware.js\";\nimport { findFileWithExts } from \"./pages-entry-helpers.js\";\n\nconst _requestContextShimPath = resolveEntryPath(\"../shims/request-context.js\", import.meta.url);\nconst _middlewareRuntimePath = resolveEntryPath(\"../server/middleware-runtime.js\", import.meta.url);\nconst _routeTriePath = resolveEntryPath(\"../routing/route-trie.js\", import.meta.url);\nconst _pagesI18nPath = resolveEntryPath(\"../server/pages-i18n.js\", import.meta.url);\nconst _pagesPageResponsePath = resolveEntryPath(\n \"../server/pages-page-response.js\",\n import.meta.url,\n);\nconst _pagesPageDataPath = resolveEntryPath(\"../server/pages-page-data.js\", import.meta.url);\nconst _pagesPageMethodPath = resolveEntryPath(\"../server/pages-page-method.js\", import.meta.url);\nconst _pagesDataRoutePath = resolveEntryPath(\"../server/pages-data-route.js\", import.meta.url);\nconst _pagesDefault404Path = resolveEntryPath(\"../server/pages-default-404.js\", import.meta.url);\nconst _pagesNodeCompatPath = resolveEntryPath(\"../server/pages-node-compat.js\", import.meta.url);\nconst _pagesApiRoutePath = resolveEntryPath(\"../server/pages-api-route.js\", import.meta.url);\nconst _isrCachePath = resolveEntryPath(\"../server/isr-cache.js\", import.meta.url);\nconst _cspPath = resolveEntryPath(\"../server/csp.js\", import.meta.url);\nconst _serverGlobalsPath = resolveEntryPath(\"../server/server-globals.js\", import.meta.url);\n\n/**\n * Generate the virtual SSR server entry module.\n * This is the entry point for `vite build --ssr`.\n */\nexport async function generateServerEntry(\n pagesDir: string,\n nextConfig: ResolvedNextConfig,\n fileMatcher: ReturnType<typeof createValidFileMatcher>,\n middlewarePath: string | null,\n instrumentationPath: string | null,\n): Promise<string> {\n const pageRoutes = await pagesRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher);\n const apiRoutes = await apiRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher);\n\n // Generate import statements using absolute paths since virtual\n // modules don't have a real file location for relative resolution.\n const pageImports = pageRoutes.map((r: Route, i: number) => {\n const absPath = normalizePathSeparators(r.filePath);\n return `import * as page_${i} from ${JSON.stringify(absPath)};`;\n });\n\n const apiImports = apiRoutes.map((r: Route, i: number) => {\n const absPath = normalizePathSeparators(r.filePath);\n return `import * as api_${i} from ${JSON.stringify(absPath)};`;\n });\n\n // Build the route table — include filePath for SSR manifest lookup\n const pageRouteEntries = pageRoutes.map((r: Route, i: number) => {\n const absPath = normalizePathSeparators(r.filePath);\n return ` { pattern: ${JSON.stringify(r.pattern)}, patternParts: ${JSON.stringify(r.patternParts)}, isDynamic: ${r.isDynamic}, params: ${JSON.stringify(r.params)}, module: page_${i}, filePath: ${JSON.stringify(absPath)} }`;\n });\n\n const apiRouteEntries = apiRoutes.map(\n (r: Route, i: number) =>\n ` { pattern: ${JSON.stringify(r.pattern)}, patternParts: ${JSON.stringify(r.patternParts)}, isDynamic: ${r.isDynamic}, params: ${JSON.stringify(r.params)}, module: api_${i} }`,\n );\n\n // Check for _app, _document, and _error.\n const appFilePath = findFileWithExts(pagesDir, \"_app\", fileMatcher);\n const docFilePath = findFileWithExts(pagesDir, \"_document\", fileMatcher);\n const errorFilePath = findFileWithExts(pagesDir, \"_error\", fileMatcher);\n // Embed the resolved _app path (or null) so the runtime can look it up\n // in the SSR manifest and include any CSS/JS chunks `_app` brings in\n // (e.g. global stylesheets imported by `_app.tsx`) alongside the page's\n // own assets. Without this, `_app`-imported CSS is emitted by Vite but\n // never `<link>`ed from the rendered HTML — see LHF-5 cluster.\n const appAssetPathJson =\n appFilePath !== null ? JSON.stringify(normalizePathSeparators(appFilePath)) : \"null\";\n const appImportCode =\n appFilePath !== null\n ? `import { default as AppComponent } from ${JSON.stringify(normalizePathSeparators(appFilePath))};`\n : `const AppComponent = null;`;\n\n const docImportCode =\n docFilePath !== null\n ? `import { default as DocumentComponent } from ${JSON.stringify(normalizePathSeparators(docFilePath))};`\n : `const DocumentComponent = null;`;\n\n const errorAssetPathJson =\n errorFilePath !== null ? JSON.stringify(normalizePathSeparators(errorFilePath)) : \"null\";\n const errorImportCode =\n errorFilePath !== null\n ? `import * as ErrorPageModule from ${JSON.stringify(normalizePathSeparators(errorFilePath))};`\n : `const ErrorPageModule = null;`;\n\n // Serialize i18n config for embedding in the server entry\n const i18nConfigJson = nextConfig?.i18n\n ? JSON.stringify({\n locales: nextConfig.i18n.locales,\n defaultLocale: nextConfig.i18n.defaultLocale,\n localeDetection: nextConfig.i18n.localeDetection,\n domains: nextConfig.i18n.domains,\n })\n : \"null\";\n\n // Embed the resolved build ID at build time\n const buildIdJson = JSON.stringify(nextConfig?.buildId ?? null);\n\n // Serialize the full resolved config for the production server.\n // This embeds redirects, rewrites, headers, basePath, trailingSlash\n // so prod-server.ts can apply them without loading next.config.js at runtime.\n const vinextConfigJson = JSON.stringify({\n basePath: nextConfig?.basePath ?? \"\",\n assetPrefix: nextConfig?.assetPrefix ?? \"\",\n trailingSlash: nextConfig?.trailingSlash ?? false,\n redirects: nextConfig?.redirects ?? [],\n rewrites: nextConfig?.rewrites ?? { beforeFiles: [], afterFiles: [], fallback: [] },\n headers: nextConfig?.headers ?? [],\n expireTime: nextConfig?.expireTime,\n i18n: nextConfig?.i18n ?? null,\n // Mirrors Next.js `experimental.disableOptimizedLoading` — when false\n // (the default), page scripts are emitted with `defer` in <head>. See\n // `.nextjs-ref/packages/next/src/pages/_document.tsx` getScripts().\n disableOptimizedLoading: nextConfig?.disableOptimizedLoading === true,\n clientTraceMetadata: nextConfig?.clientTraceMetadata,\n images: {\n deviceSizes: nextConfig?.images?.deviceSizes,\n imageSizes: nextConfig?.images?.imageSizes,\n dangerouslyAllowSVG: nextConfig?.images?.dangerouslyAllowSVG,\n dangerouslyAllowLocalIP: nextConfig?.images?.dangerouslyAllowLocalIP,\n contentDispositionType: nextConfig?.images?.contentDispositionType,\n contentSecurityPolicy: nextConfig?.images?.contentSecurityPolicy,\n },\n });\n\n // Generate instrumentation code if instrumentation.ts exists.\n // For production (Cloudflare Workers), instrumentation.ts is bundled into the\n // Worker and register() is called as a top-level await at module evaluation time —\n // before any request is handled. This mirrors App Router behavior (generateRscEntry)\n // and matches Next.js semantics: register() runs once on startup in the process\n // that handles requests.\n //\n // The onRequestError handler is stored on globalThis so it is visible across\n // all code within the Worker (same global scope).\n const instrumentationImportCode = instrumentationPath\n ? `import * as _instrumentation from ${JSON.stringify(normalizePathSeparators(instrumentationPath))};`\n : \"\";\n\n const instrumentationInitCode = instrumentationPath\n ? `// Run instrumentation register() once at module evaluation time — before any\n// requests are handled. Matches Next.js semantics: register() is called once\n// on startup in the process that handles requests.\nif (typeof _instrumentation.register === \"function\") {\n await _instrumentation.register();\n}\n// Store the onRequestError handler on globalThis so it is visible to all\n// code within the Worker (same global scope).\nif (typeof _instrumentation.onRequestError === \"function\") {\n globalThis.__VINEXT_onRequestErrorHandler__ = _instrumentation.onRequestError;\n}`\n : \"\";\n\n // Generate middleware code if middleware.ts exists\n const middlewareImportCode = middlewarePath\n ? `import * as middlewareModule from ${JSON.stringify(normalizePathSeparators(middlewarePath))};`\n : \"\";\n\n // The matcher config is read from the middleware module at request time.\n // The generated entry only wires the user module into the shared runtime\n // helper; matcher, execution, waitUntil, and result shaping live in normal\n // TypeScript modules so dev/prod paths cannot drift.\n const middlewareExportCode = middlewarePath\n ? `\nexport async function runMiddleware(request, ctx, options) {\n // Auto-detect /_next/data/<buildId>/<page>.json requests so user-written\n // worker entries don't need to know about the data endpoint protocol.\n // Mismatched buildId → JSON 404 short-circuit. Matched → middleware sees\n // the normalized page path via the request URL, and the worker sees the\n // normalized URL via result.rewriteUrl (if middleware didn't already\n // rewrite to something else).\n const __dataNorm = __normalizePagesDataRequest(request);\n if (__dataNorm.notFoundResponse) {\n return { continue: false, response: __dataNorm.notFoundResponse };\n }\n const __result = await __runGeneratedMiddleware({\n basePath: vinextConfig.basePath,\n ctx,\n i18nConfig,\n isDataRequest: options?.isDataRequest === true || __dataNorm.isDataReq,\n isProxy: ${JSON.stringify(isProxyFile(middlewarePath))},\n module: middlewareModule,\n request: __dataNorm.request,\n trailingSlash: vinextConfig.trailingSlash,\n });\n if (__dataNorm.isDataReq && __result.continue && !__result.rewriteUrl && !__result.redirectUrl) {\n return { ...__result, rewriteUrl: __dataNorm.normalizedPathname + __dataNorm.search };\n }\n return __result;\n}\n`\n : `\nexport async function runMiddleware(request) {\n // Even without user middleware, the data-endpoint URL must be normalized so\n // the worker pipeline sees the page path. Mismatched buildId → JSON 404.\n const __dataNorm = __normalizePagesDataRequest(request);\n if (__dataNorm.notFoundResponse) {\n return { continue: false, response: __dataNorm.notFoundResponse };\n }\n if (__dataNorm.isDataReq) {\n return { continue: true, rewriteUrl: __dataNorm.normalizedPathname + __dataNorm.search };\n }\n return { continue: true };\n}\n`;\n\n // The server entry is a self-contained module that uses Web-standard APIs\n // (Request/Response, renderToReadableStream) so it runs on Cloudflare Workers.\n return `\nimport ${JSON.stringify(_serverGlobalsPath)};\nimport React from \"react\";\nimport { renderToReadableStream } from \"react-dom/server.edge\";\nimport { resetSSRHead, getSSRHeadHTML } from \"next/head\";\nimport { flushPreloads } from \"next/dynamic\";\nimport { setSSRContext, wrapWithRouterContext } from \"next/router\";\nimport { _runWithCacheState } from \"next/cache\";\nimport { runWithPrivateCache } from \"vinext/cache-runtime\";\nimport { ensureFetchPatch, runWithFetchCache } from \"vinext/fetch-cache\";\nimport { runWithRequestContext as _runWithUnifiedCtx, createRequestContext as _createUnifiedCtx } from \"vinext/unified-request-context\";\nimport \"vinext/router-state\";\nimport { runWithServerInsertedHTMLState } from \"vinext/navigation-state\";\nimport { runWithHeadState } from \"vinext/head-state\";\nimport \"vinext/i18n-state\";\nimport { setI18nContext } from \"vinext/i18n-context\";\nimport { createNonceAttribute as __createNonceAttribute, safeJsonStringify } from \"vinext/html\";\nimport { getSSRFontLinks as _getSSRFontLinks, getSSRFontStyles as _getSSRFontStylesGoogle, getSSRFontPreloads as _getSSRFontPreloadsGoogle } from \"next/font/google\";\nimport { getSSRFontStyles as _getSSRFontStylesLocal, getSSRFontPreloads as _getSSRFontPreloadsLocal } from \"next/font/local\";\nimport { sanitizeDestination as sanitizeDestinationLocal } from ${JSON.stringify(resolveEntryPath(\"../config/config-matchers.js\", import.meta.url))};\nimport { runWithExecutionContext as _runWithExecutionContext, getRequestExecutionContext as _getRequestExecutionContext } from ${JSON.stringify(_requestContextShimPath)};\nimport { runGeneratedMiddleware as __runGeneratedMiddleware } from ${JSON.stringify(_middlewareRuntimePath)};\nimport { buildRouteTrie as _buildRouteTrie, trieMatch as _trieMatch } from ${JSON.stringify(_routeTriePath)};\nimport { reportRequestError as _reportRequestError } from \"vinext/instrumentation\";\nimport { resolvePagesI18nRequest } from ${JSON.stringify(_pagesI18nPath)};\nimport { createPagesReqRes as __createPagesReqRes } from ${JSON.stringify(_pagesNodeCompatPath)};\nimport { handlePagesApiRoute as __handlePagesApiRoute } from ${JSON.stringify(_pagesApiRoutePath)};\nimport {\n isrGet as __sharedIsrGet,\n isrSet as __sharedIsrSet,\n isrCacheKey as __sharedIsrCacheKey,\n triggerBackgroundRegeneration as __sharedTriggerBackgroundRegeneration,\n} from ${JSON.stringify(_isrCachePath)};\nimport { getScriptNonceFromHeaderSources as __getScriptNonceFromHeaderSources } from ${JSON.stringify(_cspPath)};\nimport { resolvePagesPageData as __resolvePagesPageData } from ${JSON.stringify(_pagesPageDataPath)};\nimport { resolvePagesPageMethodResponse as __resolvePagesPageMethodResponse } from ${JSON.stringify(_pagesPageMethodPath)};\nimport { buildNextDataJsonResponse as __buildNextDataJsonResponse, buildNextDataNotFoundResponse as __buildNextDataNotFoundResponse, isNextDataPathname as __isNextDataPathname, parseNextDataPathname as __parseNextDataPathname } from ${JSON.stringify(_pagesDataRoutePath)};\nimport { buildDefaultPagesNotFoundResponse as __buildDefaultPagesNotFoundResponse } from ${JSON.stringify(_pagesDefault404Path)};\nimport { renderPagesPageResponse as __renderPagesPageResponse } from ${JSON.stringify(_pagesPageResponsePath)};\n${instrumentationImportCode}\n${middlewareImportCode}\n\n${instrumentationInitCode}\n\n// i18n config (embedded at build time)\nconst i18nConfig = ${i18nConfigJson};\n\n// Build ID (embedded at build time). Exported so the production server can\n// match _next/data requests against the embedded buildId without needing\n// to load next.config.js at runtime.\nexport const buildId = ${buildIdJson};\nconst __hasMiddleware = ${JSON.stringify(Boolean(middlewarePath))};\n\n// Full resolved config for production server (embedded at build time)\nexport const vinextConfig = ${vinextConfigJson};\n\n// Path to the user's pages/_app file (or null). Used to look up the\n// _app's CSS/JS chunks in the SSR manifest so any global styles imported\n// by _app are included in every page's <link rel=\"stylesheet\"> set.\nconst _appAssetPath = ${appAssetPathJson};\n\nfunction isrGet(key) {\n return __sharedIsrGet(key);\n}\nfunction isrSet(key, data, revalidateSeconds, tags, expireSeconds) {\n return __sharedIsrSet(key, data, revalidateSeconds, tags, expireSeconds);\n}\nfunction triggerBackgroundRegeneration(key, renderFn, errorContext) {\n return __sharedTriggerBackgroundRegeneration(key, renderFn, errorContext);\n}\nfunction isrCacheKey(router, pathname) {\n return __sharedIsrCacheKey(router, pathname, buildId || undefined);\n}\n\n/**\n * Detect and normalize /_next/data/<buildId>/<page>.json requests in one\n * place so user-written worker entries don't need to know about the data\n * endpoint protocol. Returns the normalized request (with the page path as\n * its URL), an isDataReq flag, and notFoundResponse when the buildId in\n * the URL does not match this server's buildId — callers should return that\n * response immediately so a stale client falls back to a hard navigation.\n */\nfunction __normalizePagesDataRequest(request) {\n const reqUrl = new URL(request.url);\n if (!__isNextDataPathname(reqUrl.pathname)) {\n return { isDataReq: false, request, normalizedPathname: null, search: \"\", notFoundResponse: null };\n }\n const dataMatch = buildId ? __parseNextDataPathname(reqUrl.pathname, buildId) : null;\n if (!dataMatch) {\n return {\n isDataReq: false,\n request,\n normalizedPathname: null,\n search: \"\",\n notFoundResponse: __buildNextDataNotFoundResponse(),\n };\n }\n const normalizedUrl = new URL(reqUrl);\n normalizedUrl.pathname = dataMatch.pagePathname;\n return {\n isDataReq: true,\n request: new Request(normalizedUrl, request),\n normalizedPathname: dataMatch.pagePathname,\n search: reqUrl.search,\n notFoundResponse: null,\n };\n}\n\nasync function renderToStringAsync(element) {\n const stream = await renderToReadableStream(element);\n await stream.allReady;\n return new Response(stream).text();\n}\n\nasync function renderIsrPassToStringAsync(element) {\n // The cache-fill render is a second render pass for the same request.\n // Reset render-scoped state so it cannot leak from the streamed response\n // render or affect async work that is still draining from that stream.\n // Keep request identity state (pathname/query/locale/executionContext)\n // intact: this second pass still belongs to the same request.\n return await runWithServerInsertedHTMLState(() =>\n runWithHeadState(() =>\n _runWithCacheState(() =>\n runWithPrivateCache(() => runWithFetchCache(async () => renderToStringAsync(element))),\n ),\n ),\n );\n}\n\n${pageImports.join(\"\\n\")}\n${apiImports.join(\"\\n\")}\n\n${appImportCode}\n${docImportCode}\n${errorImportCode}\n\nexport const pageRoutes = [\n${pageRouteEntries.join(\",\\n\")}\n];\nconst _pageRouteTrie = _buildRouteTrie(pageRoutes);\nconst _errorPageRoute = ErrorPageModule\n ? {\n pattern: \"/_error\",\n patternParts: [\"_error\"],\n isDynamic: false,\n params: [],\n module: ErrorPageModule,\n filePath: ${errorAssetPathJson},\n }\n : null;\n\nconst apiRoutes = [\n${apiRouteEntries.join(\",\\n\")}\n];\nconst _apiRouteTrie = _buildRouteTrie(apiRoutes);\n\nfunction matchRoute(url, routes) {\n const pathname = url.split(\"?\")[0];\n let normalizedUrl = pathname === \"/\" ? \"/\" : pathname.replace(/\\\\/$/, \"\");\n // NOTE: Do NOT decodeURIComponent here. The pathname is already decoded at\n // the entry point. Decoding again would create a double-decode vector.\n const urlParts = normalizedUrl.split(\"/\").filter(Boolean);\n const trie = routes === pageRoutes ? _pageRouteTrie : _apiRouteTrie;\n return _trieMatch(trie, urlParts);\n}\n\nexport function matchPageRoute(url, request) {\n const routeUrl = i18nConfig && request\n ? resolvePagesI18nRequest(\n url,\n i18nConfig,\n request.headers,\n new URL(request.url).hostname,\n vinextConfig.basePath,\n vinextConfig.trailingSlash,\n ).url\n : url;\n return matchRoute(routeUrl, pageRoutes);\n}\n\nfunction parseQuery(url) {\n // Per RFC 3986 only the first \"?\" separates path from query, so additional\n // \"?\" chars belong to the query string (e.g. /linker?href=/about?hello=world\n // has query \"href=/about?hello=world\"). split(\"?\")[1] would drop everything\n // after the second \"?\" and strip embedded query strings from values.\n const queryIndex = url.indexOf(\"?\");\n if (queryIndex === -1) return {};\n const hashIndex = url.indexOf(\"#\", queryIndex + 1);\n const qs = hashIndex === -1 ? url.slice(queryIndex + 1) : url.slice(queryIndex + 1, hashIndex);\n if (!qs) return {};\n const p = new URLSearchParams(qs);\n const q = {};\n for (const [k, v] of p) {\n if (k in q) {\n q[k] = Array.isArray(q[k]) ? q[k].concat(v) : [q[k], v];\n } else {\n q[k] = v;\n }\n }\n return q;\n}\n\nfunction mergeRouteParamsIntoQuery(query, params) {\n return Object.assign(query, params);\n}\n\nfunction patternToNextFormat(pattern) {\n // Match any non-/ param name. Non-greedy with lookahead prevents\n // the +/* suffix being consumed into the param name when the name\n // itself contains + or * internally (e.g. :c++lang → [c++lang]).\n return pattern\n .replace(/:([^\\\\/]+?)\\\\+(?=\\\\/|$)/g, \"[...$1]\")\n .replace(/:([^\\\\/]+?)\\\\*(?=\\\\/|$)/g, \"[[...$1]]\")\n .replace(/:([^\\\\/]+?)(?=\\\\/|$)/g, \"[$1]\");\n}\n\nfunction resolveSsrManifest(manifest) {\n // Fall back to embedded manifest (set by vinext:cloudflare-build for Workers)\n return (manifest && Object.keys(manifest).length > 0)\n ? manifest\n : (typeof globalThis !== \"undefined\" && globalThis.__VINEXT_SSR_MANIFEST__) || null;\n}\n\nfunction getManifestFilesForModule(manifest, moduleId) {\n if (!manifest || !moduleId) return null;\n\n var files = manifest[moduleId];\n if (files) return files;\n\n for (var key in manifest) {\n if (moduleId.endsWith(\"/\" + key) || moduleId === key) {\n return manifest[key];\n }\n }\n return null;\n}\n\nfunction collectAssetTags(manifest, moduleIds, scriptNonce) {\n const m = resolveSsrManifest(manifest);\n const tags = [];\n const seen = new Set();\n const nonceAttr = __createNonceAttribute(scriptNonce);\n // Mirrors Next.js \\`_document\\` behaviour: when \\`experimental.disableOptimizedLoading\\`\n // is false (the default), page scripts are emitted with \\`defer\\` in <head>. See\n // .nextjs-ref/packages/next/src/pages/_document.tsx getScripts() — \\`defer={!disableOptimizedLoading}\\`.\n // vinext always emits \\`type=\"module\"\\` (which already defers implicitly), but\n // upstream tests (e.g. test/e2e/optimized-loading) assert the literal \\`defer\\`\n // attribute, and adding it preserves parity without changing browser behaviour.\n const deferAttr = vinextConfig.disableOptimizedLoading ? \"\" : \" defer\";\n\n // Load the set of lazy chunk filenames (only reachable via dynamic imports).\n // These should NOT get <link rel=\"modulepreload\"> or <script type=\"module\">\n // tags — they are fetched on demand when the dynamic import() executes (e.g.\n // chunks behind React.lazy() or next/dynamic boundaries).\n var lazyChunks = (typeof globalThis !== \"undefined\" && globalThis.__VINEXT_LAZY_CHUNKS__) || null;\n var lazySet = lazyChunks && lazyChunks.length > 0 ? new Set(lazyChunks) : null;\n\n // Inject the client entry script if embedded by vinext:cloudflare-build\n if (typeof globalThis !== \"undefined\" && globalThis.__VINEXT_CLIENT_ENTRY__) {\n const entry = globalThis.__VINEXT_CLIENT_ENTRY__;\n seen.add(entry);\n tags.push('<link rel=\"modulepreload\"' + nonceAttr + ' href=\"/' + entry + '\" />');\n tags.push('<script type=\"module\"' + deferAttr + nonceAttr + ' src=\"/' + entry + '\" crossorigin></script>');\n }\n if (m) {\n // Always inject shared chunks (framework, vinext runtime, entry) and\n // page-specific chunks. The manifest maps module file paths to their\n // associated JS/CSS assets.\n //\n // For page-specific injection, the module IDs may be absolute paths\n // while the manifest uses relative paths. Try both the original ID\n // and a suffix match to find the correct manifest entry.\n var allFiles = [];\n\n if (moduleIds && moduleIds.length > 0) {\n // Collect assets for the requested page modules\n for (var mi = 0; mi < moduleIds.length; mi++) {\n var id = moduleIds[mi];\n var files = getManifestFilesForModule(m, id);\n if (files) {\n for (var fi = 0; fi < files.length; fi++) allFiles.push(files[fi]);\n }\n }\n\n // Also inject shared chunks that every page needs: framework,\n // vinext runtime, and the entry bootstrap. These are identified\n // by scanning all manifest values for chunk filenames containing\n // known prefixes.\n for (var key in m) {\n var vals = m[key];\n if (!vals) continue;\n for (var vi = 0; vi < vals.length; vi++) {\n var file = vals[vi];\n var basename = file.split(\"/\").pop() || \"\";\n if (\n basename.startsWith(\"framework-\") ||\n basename.startsWith(\"vinext-\") ||\n basename.includes(\"vinext-client-entry\") ||\n basename.includes(\"vinext-app-browser-entry\")\n ) {\n allFiles.push(file);\n }\n }\n }\n } else {\n // No specific modules — include all assets from manifest\n for (var akey in m) {\n var avals = m[akey];\n if (avals) {\n for (var ai = 0; ai < avals.length; ai++) allFiles.push(avals[ai]);\n }\n }\n }\n\n for (var ti = 0; ti < allFiles.length; ti++) {\n var tf = allFiles[ti];\n // Normalize: Vite's SSR manifest values include a leading '/'\n // (from base path), but we prepend '/' ourselves when building\n // href/src attributes. Strip any existing leading slash to avoid\n // producing protocol-relative URLs like \"//assets/chunk.js\".\n // This also ensures consistent keys for the seen-set dedup and\n // lazySet.has() checks (which use values without leading slash).\n if (tf.charAt(0) === '/') tf = tf.slice(1);\n if (seen.has(tf)) continue;\n seen.add(tf);\n if (tf.endsWith(\".css\")) {\n tags.push('<link rel=\"stylesheet\"' + nonceAttr + ' href=\"/' + tf + '\" />');\n } else if (tf.endsWith(\".js\")) {\n // Skip lazy chunks — they are behind dynamic import() boundaries\n // (React.lazy, next/dynamic) and should only be fetched on demand.\n if (lazySet && lazySet.has(tf)) continue;\n tags.push('<link rel=\"modulepreload\"' + nonceAttr + ' href=\"/' + tf + '\" />');\n tags.push('<script type=\"module\"' + deferAttr + nonceAttr + ' src=\"/' + tf + '\" crossorigin></script>');\n }\n }\n }\n return tags.join(\"\\\\n \");\n}\n\nfunction resolveClientModuleUrl(manifest, moduleId) {\n const files = getManifestFilesForModule(resolveSsrManifest(manifest), moduleId);\n if (!files) return undefined;\n for (var i = 0; i < files.length; i++) {\n var file = files[i];\n if (!file || !file.endsWith(\".js\")) continue;\n if (file.charAt(0) !== \"/\") file = \"/\" + file;\n return file;\n }\n return undefined;\n}\n\nexport async function renderPage(request, url, manifest, ctx, middlewareHeaders, options) {\n if (ctx) return _runWithExecutionContext(ctx, () => _renderPage(request, url, manifest, middlewareHeaders, options));\n return _renderPage(request, url, manifest, middlewareHeaders, options);\n}\n\nasync function _renderPage(request, url, manifest, middlewareHeaders, options) {\n let isDataReq = !!(options && options.isDataReq);\n // Auto-detect /_next/data/... requests by inspecting the incoming request\n // URL. The worker pipeline does not need to know about the data endpoint\n // protocol — when it forwards an unrewritten data URL as the url arg, we\n // normalize it to the page path here.\n if (!isDataReq) {\n const __dataNorm = __normalizePagesDataRequest(request);\n if (__dataNorm.notFoundResponse) return __dataNorm.notFoundResponse;\n if (__dataNorm.isDataReq) {\n isDataReq = true;\n if (url && url.startsWith(\"/_next/data/\")) {\n const __qs = url.includes(\"?\") ? url.slice(url.indexOf(\"?\")) : \"\";\n url = __dataNorm.normalizedPathname + __qs;\n }\n }\n }\n const statusCode = options && typeof options.statusCode === \"number\" ? options.statusCode : undefined;\n const asPath = options && typeof options.asPath === \"string\" ? options.asPath : undefined;\n const renderErrorPageOnMiss = !(options && options.renderErrorPageOnMiss === false);\n // Guard against infinite recursion when the user's custom 500/error page\n // itself throws during render. When this flag is set, the catch block below\n // returns the plain \"Internal Server Error\" text response instead of trying\n // to render an error page again. Fixes #1458.\n const isInternalErrorRender = !!(options && options.__isInternalErrorRender);\n const localeInfo = i18nConfig\n ? resolvePagesI18nRequest(\n url,\n i18nConfig,\n request.headers,\n new URL(request.url).hostname,\n vinextConfig.basePath,\n vinextConfig.trailingSlash,\n )\n : { locale: undefined, url, hadPrefix: false, domainLocale: undefined, redirectUrl: undefined };\n const locale = localeInfo.locale;\n const routeUrl = localeInfo.url;\n const currentDefaultLocale = i18nConfig\n ? (localeInfo.domainLocale ? localeInfo.domainLocale.defaultLocale : i18nConfig.defaultLocale)\n : undefined;\n const domainLocales = i18nConfig ? i18nConfig.domains : undefined;\n\n if (localeInfo.redirectUrl) {\n return new Response(null, { status: 307, headers: { Location: localeInfo.redirectUrl } });\n }\n\n // Internal error render path: caller has pinned a specific route (the\n // user's pages/500 or pages/_error) to render in response to an SSR throw.\n // Skip route matching so we don't accidentally double-route, and skip the\n // missing-route 404 fallback. See catch block below. Fixes #1458.\n let match = options && options.__forcedRoute\n ? { route: options.__forcedRoute, params: {} }\n : matchRoute(routeUrl, pageRoutes);\n let renderStatusCodeOverride = statusCode;\n let renderAsPath = asPath;\n if (!match) {\n if (isDataReq) {\n return __buildNextDataNotFoundResponse();\n }\n if (!renderErrorPageOnMiss) {\n return __buildDefaultPagesNotFoundResponse();\n }\n const notFoundMatch = matchRoute(\"/404\", pageRoutes);\n // matchRoute may match a catch-all (e.g. [...slug]); only use the explicit pages/404 route.\n if (notFoundMatch && notFoundMatch.route.pattern === \"/404\") {\n match = notFoundMatch;\n renderStatusCodeOverride = 404;\n renderAsPath = routeUrl;\n } else if (_errorPageRoute) {\n match = { route: _errorPageRoute, params: {} };\n renderStatusCodeOverride = 404;\n renderAsPath = routeUrl;\n } else {\n return __buildDefaultPagesNotFoundResponse();\n }\n }\n\n const { route, params } = match;\n const __uCtx = _createUnifiedCtx({\n executionContext: _getRequestExecutionContext(),\n });\n return _runWithUnifiedCtx(__uCtx, async () => {\n ensureFetchPatch();\n try {\n const routePattern = patternToNextFormat(route.pattern);\n const renderStatusCode = renderStatusCodeOverride ?? (routePattern === \"/404\" ? 404 : undefined);\n const query = mergeRouteParamsIntoQuery(parseQuery(routeUrl), params);\n if (typeof setSSRContext === \"function\") {\n setSSRContext({\n pathname: routePattern,\n query,\n asPath: renderAsPath || routeUrl,\n locale: locale,\n locales: i18nConfig ? i18nConfig.locales : undefined,\n defaultLocale: currentDefaultLocale,\n domainLocales: domainLocales,\n });\n }\n\n if (i18nConfig) {\n setI18nContext({\n locale: locale,\n locales: i18nConfig.locales,\n defaultLocale: currentDefaultLocale,\n domainLocales: domainLocales,\n hostname: new URL(request.url).hostname,\n });\n }\n\n const pageModule = route.module;\n const PageComponent = pageModule.default;\n if (!PageComponent) {\n return new Response(\"Page has no default export\", { status: 500 });\n }\n\n // Refs #1463: reject non-GET/HEAD methods on static (no\n // getServerSideProps) Pages routes with 405 + Allow: GET, HEAD.\n // Skip for error/status pages (/_error, /404, /500), data requests\n // (those go through the JSON envelope path and have their own shape),\n // and renders that are already an error-page miss-render override.\n // Mirrors Next.js's base-server.ts L2277 carve-outs.\n if (\n !isDataReq &&\n routePattern !== \"/_error\" &&\n routePattern !== \"/404\" &&\n routePattern !== \"/500\" &&\n renderStatusCodeOverride === undefined\n ) {\n const methodResponse = __resolvePagesPageMethodResponse({\n hasGetServerSideProps: typeof pageModule.getServerSideProps === \"function\",\n method: request.method,\n });\n if (methodResponse) {\n return methodResponse;\n }\n }\n\n const pageModuleUrl = resolveClientModuleUrl(manifest, route.filePath);\n const appModuleUrl = resolveClientModuleUrl(manifest, _appAssetPath);\n const scriptNonce = __getScriptNonceFromHeaderSources(request.headers, middlewareHeaders);\n // Build font Link header early so it's available for ISR cached responses too.\n // Font preloads are module-level state populated at import time and persist across requests.\n var _fontLinkHeader = \"\";\n var _allFp = [];\n try {\n var _fpGoogle = typeof _getSSRFontPreloadsGoogle === \"function\" ? _getSSRFontPreloadsGoogle() : [];\n var _fpLocal = typeof _getSSRFontPreloadsLocal === \"function\" ? _getSSRFontPreloadsLocal() : [];\n _allFp = _fpGoogle.concat(_fpLocal);\n if (_allFp.length > 0) {\n _fontLinkHeader = _allFp.map(function(p) { return \"<\" + p.href + \">; rel=preload; as=font; type=\" + p.type + \"; crossorigin\"; }).join(\", \");\n }\n } catch (e) { /* font preloads not available */ }\n const pageDataResult = await __resolvePagesPageData({\n isDataReq,\n applyRequestContexts() {\n if (typeof setSSRContext === \"function\") {\n setSSRContext({\n pathname: routePattern,\n query,\n asPath: renderAsPath || routeUrl,\n locale: locale,\n locales: i18nConfig ? i18nConfig.locales : undefined,\n defaultLocale: currentDefaultLocale,\n domainLocales: domainLocales,\n });\n }\n if (i18nConfig) {\n setI18nContext({\n locale: locale,\n locales: i18nConfig.locales,\n defaultLocale: currentDefaultLocale,\n domainLocales: domainLocales,\n hostname: new URL(request.url).hostname,\n });\n }\n },\n buildId,\n createGsspReqRes() {\n return __createPagesReqRes({ body: undefined, query, request, url: routeUrl });\n },\n createPageElement(currentPageProps) {\n var currentElement = AppComponent\n ? React.createElement(AppComponent, { Component: PageComponent, pageProps: currentPageProps })\n : React.createElement(PageComponent, currentPageProps);\n return wrapWithRouterContext(currentElement);\n },\n fontLinkHeader: _fontLinkHeader,\n i18n: {\n locale: locale,\n locales: i18nConfig ? i18nConfig.locales : undefined,\n defaultLocale: currentDefaultLocale,\n domainLocales: domainLocales,\n },\n isrCacheKey,\n isrGet,\n isrSet,\n expireSeconds: vinextConfig.expireTime,\n // The vinext build phase boots the prod server with VINEXT_PRERENDER=1\n // and fetches every statically-generated page through it. That hit is\n // the \"build\" prerender for revalidateReason; runtime hits are not.\n // Mirrors Next.js's \\`renderOpts.isBuildTimePrerendering\\`. See\n // \\`.nextjs-ref/packages/next/src/server/render.tsx\\` and\n // \\`packages/vinext/src/build/prerender.ts\\`.\n isBuildTimePrerendering: typeof process !== \"undefined\" && process.env && process.env.VINEXT_PRERENDER === \"1\",\n pageModule,\n params,\n query,\n renderIsrPassToStringAsync,\n route: {\n isDynamic: route.isDynamic,\n },\n routePattern,\n routeUrl,\n runInFreshUnifiedContext(callback) {\n var revalCtx = _createUnifiedCtx({\n executionContext: _getRequestExecutionContext(),\n });\n return _runWithUnifiedCtx(revalCtx, async () => {\n ensureFetchPatch();\n return callback();\n });\n },\n safeJsonStringify,\n sanitizeDestination: sanitizeDestinationLocal,\n scriptNonce,\n statusCode: renderStatusCode,\n triggerBackgroundRegeneration,\n vinext: {\n pageModuleUrl,\n appModuleUrl,\n hasMiddleware: __hasMiddleware,\n },\n });\n if (pageDataResult.kind === \"response\") {\n return pageDataResult.response;\n }\n let pageProps = pageDataResult.pageProps;\n if (routePattern === \"/_error\" && typeof renderStatusCode === \"number\") {\n pageProps = { ...pageProps, statusCode: renderStatusCode };\n }\n var gsspRes = pageDataResult.gsspRes;\n let isrRevalidateSeconds = pageDataResult.isrRevalidateSeconds;\n const isFallbackRender = pageDataResult.isFallback === true;\n\n // Republish the SSR context with isFallback flipped on so the page's\n // \\`useRouter().isFallback\\` returns true during render, matching Next.js's\n // \\`render.tsx\\` fallback shell. Without this, the page would still see\n // \\`isFallback: false\\` and run the non-fallback branch.\n if (isFallbackRender && typeof setSSRContext === \"function\") {\n setSSRContext({\n pathname: routePattern,\n query,\n asPath: renderAsPath || routeUrl,\n locale: locale,\n locales: i18nConfig ? i18nConfig.locales : undefined,\n defaultLocale: currentDefaultLocale,\n domainLocales: domainLocales,\n isFallback: true,\n });\n }\n\n // ── _next/data JSON envelope short-circuit ───────────────────────\n // For client-side navigations Next.js fetches /_next/data/<buildId>/<page>.json\n // and expects { pageProps } as JSON instead of the full HTML page. Skip\n // rendering the React tree and emit the JSON envelope directly via the\n // typed helper so the envelope shape stays in one place. Headers and\n // cookies set on the gsspRes by getServerSideProps are forwarded so\n // middleware/auth flows work the same as the HTML page.\n if (isDataReq) {\n const init = { headers: {} };\n if (gsspRes && typeof gsspRes.getHeaders === \"function\") {\n const gsspHeaders = gsspRes.getHeaders();\n for (const k of Object.keys(gsspHeaders)) {\n const v = gsspHeaders[k];\n if (v === undefined || v === null) continue;\n init.headers[k] = Array.isArray(v) ? v.join(\", \") : String(v);\n }\n }\n if (gsspRes) {\n // Default Cache-Control for gSSP-driven _next/data responses,\n // matching Next.js's pages-handler.ts (revalidate: 0 →\n // getCacheControlHeader). Skip when gSSP already set one via\n // res.setHeader (case-insensitive). Mirrors the HTML branch in\n // pages-page-response.ts and the dev-server branch. Fixes #1461.\n var hasUserCacheControl = false;\n for (const headerKey of Object.keys(init.headers)) {\n if (headerKey.toLowerCase() === \"cache-control\") {\n hasUserCacheControl = true;\n break;\n }\n }\n if (!hasUserCacheControl) {\n init.headers[\"Cache-Control\"] =\n \"private, no-cache, no-store, max-age=0, must-revalidate\";\n }\n }\n return __buildNextDataJsonResponse(pageProps, safeJsonStringify, init);\n }\n\n // Include both the matched page module and the global _app module\n // (if present). _app is wrapped around every page in Pages Router,\n // and any CSS/JS it imports must be linked from the rendered HTML\n // so the browser actually loads it. Without _app in this list, a\n // global stylesheet imported via import \"./globals.scss\" in\n // _app.tsx never reaches the page, producing the LHF-5 symptom\n // where styled elements render with the browser default colour.\n const pageModuleIds = [];\n if (route.filePath) pageModuleIds.push(route.filePath);\n if (_appAssetPath) pageModuleIds.push(_appAssetPath);\n const assetTags = collectAssetTags(manifest, pageModuleIds, scriptNonce);\n\n return __renderPagesPageResponse({\n assetTags,\n buildId,\n clearSsrContext() {\n if (typeof setSSRContext === \"function\") setSSRContext(null);\n },\n createPageElement(currentPageProps) {\n var currentElement;\n if (AppComponent) {\n currentElement = React.createElement(AppComponent, { Component: PageComponent, pageProps: currentPageProps });\n } else {\n currentElement = React.createElement(PageComponent, currentPageProps);\n }\n return wrapWithRouterContext(currentElement);\n },\n DocumentComponent,\n flushPreloads: typeof flushPreloads === \"function\" ? flushPreloads : undefined,\n fontLinkHeader: _fontLinkHeader,\n fontPreloads: _allFp,\n getFontLinks() {\n try {\n return typeof _getSSRFontLinks === \"function\" ? _getSSRFontLinks() : [];\n } catch (e) {\n return [];\n }\n },\n getFontStyles() {\n try {\n var allFontStyles = [];\n if (typeof _getSSRFontStylesGoogle === \"function\") allFontStyles.push(..._getSSRFontStylesGoogle());\n if (typeof _getSSRFontStylesLocal === \"function\") allFontStyles.push(..._getSSRFontStylesLocal());\n return allFontStyles;\n } catch (e) {\n return [];\n }\n },\n getSSRHeadHTML: typeof getSSRHeadHTML === \"function\" ? getSSRHeadHTML : undefined,\n clientTraceMetadata: vinextConfig.clientTraceMetadata,\n gsspRes,\n isrCacheKey,\n expireSeconds: vinextConfig.expireTime,\n isrRevalidateSeconds,\n isrSet,\n i18n: {\n locale: locale,\n locales: i18nConfig ? i18nConfig.locales : undefined,\n defaultLocale: currentDefaultLocale,\n domainLocales: domainLocales,\n },\n isFallback: isFallbackRender,\n pageProps,\n params,\n renderDocumentToString(element) {\n return renderToStringAsync(element);\n },\n renderToReadableStream(element) {\n return renderToReadableStream(element);\n },\n resetSSRHead: typeof resetSSRHead === \"function\" ? resetSSRHead : undefined,\n routePattern,\n routeUrl,\n safeJsonStringify,\n scriptNonce,\n statusCode: renderStatusCode,\n vinext: {\n pageModuleUrl,\n appModuleUrl,\n hasMiddleware: __hasMiddleware,\n },\n });\n } catch (e) {\n console.error(\"[vinext] SSR error:\", e);\n _reportRequestError(\n e instanceof Error ? e : new Error(String(e)),\n { path: url, method: request.method, headers: Object.fromEntries(request.headers.entries()) },\n { routerKind: \"Pages Router\", routePath: route.pattern, routeType: \"render\" },\n ).catch(() => { /* ignore reporting errors */ });\n // Data (_next/data) requests can't render HTML, and avoid recursion if\n // we're already in the middle of rendering the error page itself.\n // Mirrors Next.js base-server.ts which renders /500 (or _error) when\n // SSR throws. Fixes #1458.\n if (!isInternalErrorRender && !isDataReq) {\n // Look for an explicit pages/500.tsx first, then fall back to _error.\n // Only match the literal /500 pattern — never a catch-all/dynamic route.\n let errorRoute = null;\n for (var __i = 0; __i < pageRoutes.length; __i++) {\n if (pageRoutes[__i].pattern === \"/500\") {\n errorRoute = pageRoutes[__i];\n break;\n }\n }\n if (!errorRoute && _errorPageRoute) {\n errorRoute = _errorPageRoute;\n }\n if (errorRoute) {\n try {\n return await _renderPage(request, url, manifest, middlewareHeaders, {\n statusCode: 500,\n asPath: url,\n renderErrorPageOnMiss: false,\n __isInternalErrorRender: true,\n __forcedRoute: errorRoute,\n });\n } catch (errorPageErr) {\n console.error(\"[vinext] Error page render failed:\", errorPageErr);\n }\n }\n }\n return new Response(\"Internal Server Error\", { status: 500 });\n }\n });\n}\n\nexport async function handleApiRoute(request, url, ctx) {\n const match = matchRoute(url, apiRoutes);\n return __handlePagesApiRoute({\n ctx,\n match,\n request,\n url,\n reportRequestError(error, routePattern) {\n console.error(\"[vinext] API error:\", error);\n void _reportRequestError(\n error,\n { path: url, method: request.method, headers: Object.fromEntries(request.headers.entries()) },\n { routerKind: \"Pages Router\", routePath: rout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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAsoB5B,qBAAqB"}
1
+ {"version":3,"file":"pages-server-entry.js","names":[],"sources":["../../src/entries/pages-server-entry.ts"],"sourcesContent":["/**\n * Pages Router server entry generator.\n *\n * Generates the virtual SSR server entry module (`virtual:vinext-server-entry`).\n * This is the entry point for `vite build --ssr`. It handles SSR, API routes,\n * middleware, ISR, and i18n for the Pages Router.\n *\n * Extracted from index.ts.\n */\nimport { resolveEntryPath } from \"./runtime-entry-module.js\";\nimport { normalizePathSeparators } from \"../utils/path.js\";\nimport { pagesRouter, apiRouter, type Route } from \"../routing/pages-router.js\";\nimport { createValidFileMatcher } from \"../routing/file-matcher.js\";\nimport { type ResolvedNextConfig } from \"../config/next-config.js\";\nimport { isProxyFile } from \"../server/middleware.js\";\nimport { findFileWithExts } from \"./pages-entry-helpers.js\";\n\nconst _requestContextShimPath = resolveEntryPath(\"../shims/request-context.js\", import.meta.url);\nconst _middlewareRuntimePath = resolveEntryPath(\"../server/middleware-runtime.js\", import.meta.url);\nconst _routeTriePath = resolveEntryPath(\"../routing/route-trie.js\", import.meta.url);\nconst _pagesI18nPath = resolveEntryPath(\"../server/pages-i18n.js\", import.meta.url);\nconst _pagesPageResponsePath = resolveEntryPath(\n \"../server/pages-page-response.js\",\n import.meta.url,\n);\nconst _pagesPageDataPath = resolveEntryPath(\"../server/pages-page-data.js\", import.meta.url);\nconst _pagesPageMethodPath = resolveEntryPath(\"../server/pages-page-method.js\", import.meta.url);\nconst _pagesDataRoutePath = resolveEntryPath(\"../server/pages-data-route.js\", import.meta.url);\nconst _pagesDefault404Path = resolveEntryPath(\"../server/pages-default-404.js\", import.meta.url);\nconst _pagesNodeCompatPath = resolveEntryPath(\"../server/pages-node-compat.js\", import.meta.url);\nconst _pagesApiRoutePath = resolveEntryPath(\"../server/pages-api-route.js\", import.meta.url);\nconst _isrCachePath = resolveEntryPath(\"../server/isr-cache.js\", import.meta.url);\nconst _cspPath = resolveEntryPath(\"../server/csp.js\", import.meta.url);\nconst _serverGlobalsPath = resolveEntryPath(\"../server/server-globals.js\", import.meta.url);\n\n/**\n * Generate the virtual SSR server entry module.\n * This is the entry point for `vite build --ssr`.\n */\nexport async function generateServerEntry(\n pagesDir: string,\n nextConfig: ResolvedNextConfig,\n fileMatcher: ReturnType<typeof createValidFileMatcher>,\n middlewarePath: string | null,\n instrumentationPath: string | null,\n): Promise<string> {\n const pageRoutes = await pagesRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher);\n const apiRoutes = await apiRouter(pagesDir, nextConfig?.pageExtensions, fileMatcher);\n\n // Generate import statements using absolute paths since virtual\n // modules don't have a real file location for relative resolution.\n const pageImports = pageRoutes.map((r: Route, i: number) => {\n const absPath = normalizePathSeparators(r.filePath);\n return `import * as page_${i} from ${JSON.stringify(absPath)};`;\n });\n\n const apiImports = apiRoutes.map((r: Route, i: number) => {\n const absPath = normalizePathSeparators(r.filePath);\n return `import * as api_${i} from ${JSON.stringify(absPath)};`;\n });\n\n // Build the route table — include filePath for SSR manifest lookup\n const pageRouteEntries = pageRoutes.map((r: Route, i: number) => {\n const absPath = normalizePathSeparators(r.filePath);\n return ` { pattern: ${JSON.stringify(r.pattern)}, patternParts: ${JSON.stringify(r.patternParts)}, isDynamic: ${r.isDynamic}, params: ${JSON.stringify(r.params)}, module: page_${i}, filePath: ${JSON.stringify(absPath)} }`;\n });\n\n const apiRouteEntries = apiRoutes.map(\n (r: Route, i: number) =>\n ` { pattern: ${JSON.stringify(r.pattern)}, patternParts: ${JSON.stringify(r.patternParts)}, isDynamic: ${r.isDynamic}, params: ${JSON.stringify(r.params)}, module: api_${i} }`,\n );\n\n // Check for _app, _document, and _error.\n const appFilePath = findFileWithExts(pagesDir, \"_app\", fileMatcher);\n const docFilePath = findFileWithExts(pagesDir, \"_document\", fileMatcher);\n const errorFilePath = findFileWithExts(pagesDir, \"_error\", fileMatcher);\n // Embed the resolved _app path (or null) so the runtime can look it up\n // in the SSR manifest and include any CSS/JS chunks `_app` brings in\n // (e.g. global stylesheets imported by `_app.tsx`) alongside the page's\n // own assets. Without this, `_app`-imported CSS is emitted by Vite but\n // never `<link>`ed from the rendered HTML — see LHF-5 cluster.\n const appAssetPathJson =\n appFilePath !== null ? JSON.stringify(normalizePathSeparators(appFilePath)) : \"null\";\n const appImportCode =\n appFilePath !== null\n ? `import { default as AppComponent } from ${JSON.stringify(normalizePathSeparators(appFilePath))};`\n : `const AppComponent = null;`;\n\n const docImportCode =\n docFilePath !== null\n ? `import { default as DocumentComponent } from ${JSON.stringify(normalizePathSeparators(docFilePath))};`\n : `const DocumentComponent = null;`;\n\n const errorAssetPathJson =\n errorFilePath !== null ? JSON.stringify(normalizePathSeparators(errorFilePath)) : \"null\";\n const errorImportCode =\n errorFilePath !== null\n ? `import * as ErrorPageModule from ${JSON.stringify(normalizePathSeparators(errorFilePath))};`\n : `const ErrorPageModule = null;`;\n\n // Serialize i18n config for embedding in the server entry\n const i18nConfigJson = nextConfig?.i18n\n ? JSON.stringify({\n locales: nextConfig.i18n.locales,\n defaultLocale: nextConfig.i18n.defaultLocale,\n localeDetection: nextConfig.i18n.localeDetection,\n domains: nextConfig.i18n.domains,\n })\n : \"null\";\n\n // Embed the resolved build ID at build time\n const buildIdJson = JSON.stringify(nextConfig?.buildId ?? null);\n\n // Serialize the full resolved config for the production server.\n // This embeds redirects, rewrites, headers, basePath, trailingSlash\n // so prod-server.ts can apply them without loading next.config.js at runtime.\n const vinextConfigJson = JSON.stringify({\n basePath: nextConfig?.basePath ?? \"\",\n assetPrefix: nextConfig?.assetPrefix ?? \"\",\n trailingSlash: nextConfig?.trailingSlash ?? false,\n redirects: nextConfig?.redirects ?? [],\n rewrites: nextConfig?.rewrites ?? { beforeFiles: [], afterFiles: [], fallback: [] },\n headers: nextConfig?.headers ?? [],\n expireTime: nextConfig?.expireTime,\n cacheMaxMemorySize: nextConfig?.cacheMaxMemorySize,\n i18n: nextConfig?.i18n ?? null,\n // Mirrors Next.js `experimental.disableOptimizedLoading` — when false\n // (the default), page scripts are emitted with `defer` in <head>. See\n // `.nextjs-ref/packages/next/src/pages/_document.tsx` getScripts().\n disableOptimizedLoading: nextConfig?.disableOptimizedLoading === true,\n clientTraceMetadata: nextConfig?.clientTraceMetadata,\n images: {\n deviceSizes: nextConfig?.images?.deviceSizes,\n imageSizes: nextConfig?.images?.imageSizes,\n dangerouslyAllowSVG: nextConfig?.images?.dangerouslyAllowSVG,\n dangerouslyAllowLocalIP: nextConfig?.images?.dangerouslyAllowLocalIP,\n contentDispositionType: nextConfig?.images?.contentDispositionType,\n contentSecurityPolicy: nextConfig?.images?.contentSecurityPolicy,\n },\n });\n\n // Generate instrumentation code if instrumentation.ts exists.\n // For production (Cloudflare Workers), instrumentation.ts is bundled into the\n // Worker and register() is called as a top-level await at module evaluation time —\n // before any request is handled. This mirrors App Router behavior (generateRscEntry)\n // and matches Next.js semantics: register() runs once on startup in the process\n // that handles requests.\n //\n // The onRequestError handler is stored on globalThis so it is visible across\n // all code within the Worker (same global scope).\n const instrumentationImportCode = instrumentationPath\n ? `import * as _instrumentation from ${JSON.stringify(normalizePathSeparators(instrumentationPath))};`\n : \"\";\n\n const instrumentationInitCode = instrumentationPath\n ? `// Run instrumentation register() once at module evaluation time — before any\n// requests are handled. Matches Next.js semantics: register() is called once\n// on startup in the process that handles requests.\nif (typeof _instrumentation.register === \"function\") {\n await _instrumentation.register();\n}\n// Store the onRequestError handler on globalThis so it is visible to all\n// code within the Worker (same global scope).\nif (typeof _instrumentation.onRequestError === \"function\") {\n globalThis.__VINEXT_onRequestErrorHandler__ = _instrumentation.onRequestError;\n}`\n : \"\";\n\n // Generate middleware code if middleware.ts exists\n const middlewareImportCode = middlewarePath\n ? `import * as middlewareModule from ${JSON.stringify(normalizePathSeparators(middlewarePath))};`\n : \"\";\n\n // The matcher config is read from the middleware module at request time.\n // The generated entry only wires the user module into the shared runtime\n // helper; matcher, execution, waitUntil, and result shaping live in normal\n // TypeScript modules so dev/prod paths cannot drift.\n const middlewareExportCode = middlewarePath\n ? `\nexport async function runMiddleware(request, ctx, options) {\n // Auto-detect /_next/data/<buildId>/<page>.json requests so user-written\n // worker entries don't need to know about the data endpoint protocol.\n // Mismatched buildId → JSON 404 short-circuit. Matched → middleware sees\n // the normalized page path via the request URL, and the worker sees the\n // normalized URL via result.rewriteUrl (if middleware didn't already\n // rewrite to something else).\n const __dataNorm = __normalizePagesDataRequest(request);\n if (__dataNorm.notFoundResponse) {\n return { continue: false, response: __dataNorm.notFoundResponse };\n }\n const __result = await __runGeneratedMiddleware({\n basePath: vinextConfig.basePath,\n ctx,\n i18nConfig,\n isDataRequest: options?.isDataRequest === true || __dataNorm.isDataReq,\n isProxy: ${JSON.stringify(isProxyFile(middlewarePath))},\n module: middlewareModule,\n request: __dataNorm.request,\n trailingSlash: vinextConfig.trailingSlash,\n });\n if (__dataNorm.isDataReq && __result.continue && !__result.rewriteUrl && !__result.redirectUrl) {\n return { ...__result, rewriteUrl: __dataNorm.normalizedPathname + __dataNorm.search };\n }\n return __result;\n}\n`\n : `\nexport async function runMiddleware(request) {\n // Even without user middleware, the data-endpoint URL must be normalized so\n // the worker pipeline sees the page path. Mismatched buildId → JSON 404.\n const __dataNorm = __normalizePagesDataRequest(request);\n if (__dataNorm.notFoundResponse) {\n return { continue: false, response: __dataNorm.notFoundResponse };\n }\n if (__dataNorm.isDataReq) {\n return { continue: true, rewriteUrl: __dataNorm.normalizedPathname + __dataNorm.search };\n }\n return { continue: true };\n}\n`;\n\n // The server entry is a self-contained module that uses Web-standard APIs\n // (Request/Response, renderToReadableStream) so it runs on Cloudflare Workers.\n return `\nimport ${JSON.stringify(_serverGlobalsPath)};\nimport React from \"react\";\nimport { renderToReadableStream } from \"react-dom/server.edge\";\nimport { resetSSRHead, getSSRHeadHTML, setDocumentInitialHead } from \"next/head\";\nimport { flushPreloads } from \"next/dynamic\";\nimport { setSSRContext, wrapWithRouterContext } from \"next/router\";\nimport { _runWithCacheState, configureMemoryCacheHandler as __configureMemoryCacheHandler } from \"next/cache\";\nimport { runWithPrivateCache } from \"vinext/cache-runtime\";\nimport { ensureFetchPatch, runWithFetchCache } from \"vinext/fetch-cache\";\nimport { runWithRequestContext as _runWithUnifiedCtx, createRequestContext as _createUnifiedCtx } from \"vinext/unified-request-context\";\nimport \"vinext/router-state\";\nimport { runWithServerInsertedHTMLState } from \"vinext/navigation-state\";\nimport { runWithHeadState } from \"vinext/head-state\";\nimport \"vinext/i18n-state\";\nimport { setI18nContext } from \"vinext/i18n-context\";\nimport { createNonceAttribute as __createNonceAttribute, safeJsonStringify } from \"vinext/html\";\nimport { getSSRFontLinks as _getSSRFontLinks, getSSRFontStyles as _getSSRFontStylesGoogle, getSSRFontPreloads as _getSSRFontPreloadsGoogle } from \"next/font/google\";\nimport { getSSRFontStyles as _getSSRFontStylesLocal, getSSRFontPreloads as _getSSRFontPreloadsLocal } from \"next/font/local\";\nimport { sanitizeDestination as sanitizeDestinationLocal } from ${JSON.stringify(resolveEntryPath(\"../config/config-matchers.js\", import.meta.url))};\nimport { runWithExecutionContext as _runWithExecutionContext, getRequestExecutionContext as _getRequestExecutionContext } from ${JSON.stringify(_requestContextShimPath)};\nimport { runGeneratedMiddleware as __runGeneratedMiddleware } from ${JSON.stringify(_middlewareRuntimePath)};\nimport { buildRouteTrie as _buildRouteTrie, trieMatch as _trieMatch } from ${JSON.stringify(_routeTriePath)};\nimport { reportRequestError as _reportRequestError } from \"vinext/instrumentation\";\nimport { resolvePagesI18nRequest } from ${JSON.stringify(_pagesI18nPath)};\nimport { createPagesReqRes as __createPagesReqRes } from ${JSON.stringify(_pagesNodeCompatPath)};\nimport { handlePagesApiRoute as __handlePagesApiRoute } from ${JSON.stringify(_pagesApiRoutePath)};\nimport {\n isrGet as __sharedIsrGet,\n isrSet as __sharedIsrSet,\n isrCacheKey as __sharedIsrCacheKey,\n triggerBackgroundRegeneration as __sharedTriggerBackgroundRegeneration,\n} from ${JSON.stringify(_isrCachePath)};\nimport { getScriptNonceFromHeaderSources as __getScriptNonceFromHeaderSources } from ${JSON.stringify(_cspPath)};\nimport { resolvePagesPageData as __resolvePagesPageData } from ${JSON.stringify(_pagesPageDataPath)};\nimport { resolvePagesPageMethodResponse as __resolvePagesPageMethodResponse } from ${JSON.stringify(_pagesPageMethodPath)};\nimport { buildNextDataJsonResponse as __buildNextDataJsonResponse, buildNextDataNotFoundResponse as __buildNextDataNotFoundResponse, isNextDataPathname as __isNextDataPathname, parseNextDataPathname as __parseNextDataPathname } from ${JSON.stringify(_pagesDataRoutePath)};\nimport { buildDefaultPagesNotFoundResponse as __buildDefaultPagesNotFoundResponse } from ${JSON.stringify(_pagesDefault404Path)};\nimport { renderPagesPageResponse as __renderPagesPageResponse } from ${JSON.stringify(_pagesPageResponsePath)};\n${instrumentationImportCode}\n${middlewareImportCode}\n\n${instrumentationInitCode}\n\n// i18n config (embedded at build time)\nconst i18nConfig = ${i18nConfigJson};\n\n// Build ID (embedded at build time). Exported so the production server can\n// match _next/data requests against the embedded buildId without needing\n// to load next.config.js at runtime.\nexport const buildId = ${buildIdJson};\nconst __hasMiddleware = ${JSON.stringify(Boolean(middlewarePath))};\n\n// Full resolved config for production server (embedded at build time)\nexport const vinextConfig = ${vinextConfigJson};\n\n__configureMemoryCacheHandler({ cacheMaxMemorySize: vinextConfig.cacheMaxMemorySize });\n\n// Path to the user's pages/_app file (or null). Used to look up the\n// _app's CSS/JS chunks in the SSR manifest so any global styles imported\n// by _app are included in every page's <link rel=\"stylesheet\"> set.\nconst _appAssetPath = ${appAssetPathJson};\n\nfunction isrGet(key) {\n return __sharedIsrGet(key);\n}\nfunction isrSet(key, data, revalidateSeconds, tags, expireSeconds) {\n return __sharedIsrSet(key, data, revalidateSeconds, tags, expireSeconds);\n}\nfunction triggerBackgroundRegeneration(key, renderFn, errorContext) {\n return __sharedTriggerBackgroundRegeneration(key, renderFn, errorContext);\n}\nfunction isrCacheKey(router, pathname) {\n return __sharedIsrCacheKey(router, pathname, buildId || undefined);\n}\n\n/**\n * Detect and normalize /_next/data/<buildId>/<page>.json requests in one\n * place so user-written worker entries don't need to know about the data\n * endpoint protocol. Returns the normalized request (with the page path as\n * its URL), an isDataReq flag, and notFoundResponse when the buildId in\n * the URL does not match this server's buildId — callers should return that\n * response immediately so a stale client falls back to a hard navigation.\n */\nfunction __normalizePagesDataRequest(request) {\n const reqUrl = new URL(request.url);\n if (!__isNextDataPathname(reqUrl.pathname)) {\n return { isDataReq: false, request, normalizedPathname: null, search: \"\", notFoundResponse: null };\n }\n const dataMatch = buildId ? __parseNextDataPathname(reqUrl.pathname, buildId) : null;\n if (!dataMatch) {\n return {\n isDataReq: false,\n request,\n normalizedPathname: null,\n search: \"\",\n notFoundResponse: __buildNextDataNotFoundResponse(),\n };\n }\n const normalizedUrl = new URL(reqUrl);\n normalizedUrl.pathname = dataMatch.pagePathname;\n return {\n isDataReq: true,\n request: new Request(normalizedUrl, request),\n normalizedPathname: dataMatch.pagePathname,\n search: reqUrl.search,\n notFoundResponse: null,\n };\n}\n\nasync function renderToStringAsync(element) {\n const stream = await renderToReadableStream(element);\n await stream.allReady;\n return new Response(stream).text();\n}\n\nasync function renderIsrPassToStringAsync(element) {\n // The cache-fill render is a second render pass for the same request.\n // Reset render-scoped state so it cannot leak from the streamed response\n // render or affect async work that is still draining from that stream.\n // Keep request identity state (pathname/query/locale/executionContext)\n // intact: this second pass still belongs to the same request.\n return await runWithServerInsertedHTMLState(() =>\n runWithHeadState(() =>\n _runWithCacheState(() =>\n runWithPrivateCache(() => runWithFetchCache(async () => renderToStringAsync(element))),\n ),\n ),\n );\n}\n\n${pageImports.join(\"\\n\")}\n${apiImports.join(\"\\n\")}\n\n${appImportCode}\n${docImportCode}\n${errorImportCode}\n\nexport const pageRoutes = [\n${pageRouteEntries.join(\",\\n\")}\n];\nconst _pageRouteTrie = _buildRouteTrie(pageRoutes);\nconst _errorPageRoute = ErrorPageModule\n ? {\n pattern: \"/_error\",\n patternParts: [\"_error\"],\n isDynamic: false,\n params: [],\n module: ErrorPageModule,\n filePath: ${errorAssetPathJson},\n }\n : null;\n\nconst apiRoutes = [\n${apiRouteEntries.join(\",\\n\")}\n];\nconst _apiRouteTrie = _buildRouteTrie(apiRoutes);\n\nfunction matchRoute(url, routes) {\n const pathname = url.split(\"?\")[0];\n let normalizedUrl = pathname === \"/\" ? \"/\" : pathname.replace(/\\\\/$/, \"\");\n // NOTE: Do NOT decodeURIComponent here. The pathname is already decoded at\n // the entry point. Decoding again would create a double-decode vector.\n const urlParts = normalizedUrl.split(\"/\").filter(Boolean);\n const trie = routes === pageRoutes ? _pageRouteTrie : _apiRouteTrie;\n return _trieMatch(trie, urlParts);\n}\n\nexport function matchPageRoute(url, request) {\n const routeUrl = i18nConfig && request\n ? resolvePagesI18nRequest(\n url,\n i18nConfig,\n request.headers,\n new URL(request.url).hostname,\n vinextConfig.basePath,\n vinextConfig.trailingSlash,\n ).url\n : url;\n return matchRoute(routeUrl, pageRoutes);\n}\n\nfunction parseQuery(url) {\n // Per RFC 3986 only the first \"?\" separates path from query, so additional\n // \"?\" chars belong to the query string (e.g. /linker?href=/about?hello=world\n // has query \"href=/about?hello=world\"). split(\"?\")[1] would drop everything\n // after the second \"?\" and strip embedded query strings from values.\n const queryIndex = url.indexOf(\"?\");\n if (queryIndex === -1) return {};\n const hashIndex = url.indexOf(\"#\", queryIndex + 1);\n const qs = hashIndex === -1 ? url.slice(queryIndex + 1) : url.slice(queryIndex + 1, hashIndex);\n if (!qs) return {};\n const p = new URLSearchParams(qs);\n const q = {};\n for (const [k, v] of p) {\n if (k in q) {\n q[k] = Array.isArray(q[k]) ? q[k].concat(v) : [q[k], v];\n } else {\n q[k] = v;\n }\n }\n return q;\n}\n\nfunction mergeRouteParamsIntoQuery(query, params) {\n return Object.assign(query, params);\n}\n\nfunction patternToNextFormat(pattern) {\n // Match any non-/ param name. Non-greedy with lookahead prevents\n // the +/* suffix being consumed into the param name when the name\n // itself contains + or * internally (e.g. :c++lang → [c++lang]).\n return pattern\n .replace(/:([^\\\\/]+?)\\\\+(?=\\\\/|$)/g, \"[...$1]\")\n .replace(/:([^\\\\/]+?)\\\\*(?=\\\\/|$)/g, \"[[...$1]]\")\n .replace(/:([^\\\\/]+?)(?=\\\\/|$)/g, \"[$1]\");\n}\n\nfunction resolveSsrManifest(manifest) {\n // Fall back to embedded manifest (set by vinext:cloudflare-build for Workers)\n return (manifest && Object.keys(manifest).length > 0)\n ? manifest\n : (typeof globalThis !== \"undefined\" && globalThis.__VINEXT_SSR_MANIFEST__) || null;\n}\n\nfunction getManifestFilesForModule(manifest, moduleId) {\n if (!manifest || !moduleId) return null;\n\n var files = manifest[moduleId];\n if (files) return files;\n\n for (var key in manifest) {\n if (moduleId.endsWith(\"/\" + key) || moduleId === key) {\n return manifest[key];\n }\n }\n return null;\n}\n\nfunction collectAssetTags(manifest, moduleIds, scriptNonce) {\n const m = resolveSsrManifest(manifest);\n const tags = [];\n const seen = new Set();\n const nonceAttr = __createNonceAttribute(scriptNonce);\n // Mirrors Next.js \\`_document\\` behaviour: when \\`experimental.disableOptimizedLoading\\`\n // is false (the default), page scripts are emitted with \\`defer\\` in <head>. See\n // .nextjs-ref/packages/next/src/pages/_document.tsx getScripts() — \\`defer={!disableOptimizedLoading}\\`.\n // vinext always emits \\`type=\"module\"\\` (which already defers implicitly), but\n // upstream tests (e.g. test/e2e/optimized-loading) assert the literal \\`defer\\`\n // attribute, and adding it preserves parity without changing browser behaviour.\n const deferAttr = vinextConfig.disableOptimizedLoading ? \"\" : \" defer\";\n\n // Load the set of lazy chunk filenames (only reachable via dynamic imports).\n // These should NOT get <link rel=\"modulepreload\"> or <script type=\"module\">\n // tags — they are fetched on demand when the dynamic import() executes (e.g.\n // chunks behind React.lazy() or next/dynamic boundaries).\n var lazyChunks = (typeof globalThis !== \"undefined\" && globalThis.__VINEXT_LAZY_CHUNKS__) || null;\n var lazySet = lazyChunks && lazyChunks.length > 0 ? new Set(lazyChunks) : null;\n\n // Inject the client entry script if embedded by vinext:cloudflare-build\n if (typeof globalThis !== \"undefined\" && globalThis.__VINEXT_CLIENT_ENTRY__) {\n const entry = globalThis.__VINEXT_CLIENT_ENTRY__;\n seen.add(entry);\n tags.push('<link rel=\"modulepreload\"' + nonceAttr + ' href=\"/' + entry + '\" />');\n tags.push('<script type=\"module\"' + deferAttr + nonceAttr + ' src=\"/' + entry + '\" crossorigin></script>');\n }\n if (m) {\n // Always inject shared chunks (framework, vinext runtime, entry) and\n // page-specific chunks. The manifest maps module file paths to their\n // associated JS/CSS assets.\n //\n // For page-specific injection, the module IDs may be absolute paths\n // while the manifest uses relative paths. Try both the original ID\n // and a suffix match to find the correct manifest entry.\n var allFiles = [];\n\n if (moduleIds && moduleIds.length > 0) {\n // Collect assets for the requested page modules\n for (var mi = 0; mi < moduleIds.length; mi++) {\n var id = moduleIds[mi];\n var files = getManifestFilesForModule(m, id);\n if (files) {\n for (var fi = 0; fi < files.length; fi++) allFiles.push(files[fi]);\n }\n }\n\n // Also inject shared chunks that every page needs: framework,\n // vinext runtime, and the entry bootstrap. These are identified\n // by scanning all manifest values for chunk filenames containing\n // known prefixes.\n for (var key in m) {\n var vals = m[key];\n if (!vals) continue;\n for (var vi = 0; vi < vals.length; vi++) {\n var file = vals[vi];\n var basename = file.split(\"/\").pop() || \"\";\n if (\n basename.startsWith(\"framework-\") ||\n basename.startsWith(\"vinext-\") ||\n basename.includes(\"vinext-client-entry\") ||\n basename.includes(\"vinext-app-browser-entry\")\n ) {\n allFiles.push(file);\n }\n }\n }\n } else {\n // No specific modules — include all assets from manifest\n for (var akey in m) {\n var avals = m[akey];\n if (avals) {\n for (var ai = 0; ai < avals.length; ai++) allFiles.push(avals[ai]);\n }\n }\n }\n\n for (var ti = 0; ti < allFiles.length; ti++) {\n var tf = allFiles[ti];\n // Normalize: Vite's SSR manifest values include a leading '/'\n // (from base path), but we prepend '/' ourselves when building\n // href/src attributes. Strip any existing leading slash to avoid\n // producing protocol-relative URLs like \"//assets/chunk.js\".\n // This also ensures consistent keys for the seen-set dedup and\n // lazySet.has() checks (which use values without leading slash).\n if (tf.charAt(0) === '/') tf = tf.slice(1);\n if (seen.has(tf)) continue;\n seen.add(tf);\n if (tf.endsWith(\".css\")) {\n tags.push('<link rel=\"stylesheet\"' + nonceAttr + ' href=\"/' + tf + '\" />');\n } else if (tf.endsWith(\".js\")) {\n // Skip lazy chunks — they are behind dynamic import() boundaries\n // (React.lazy, next/dynamic) and should only be fetched on demand.\n if (lazySet && lazySet.has(tf)) continue;\n tags.push('<link rel=\"modulepreload\"' + nonceAttr + ' href=\"/' + tf + '\" />');\n tags.push('<script type=\"module\"' + deferAttr + nonceAttr + ' src=\"/' + tf + '\" crossorigin></script>');\n }\n }\n }\n return tags.join(\"\\\\n \");\n}\n\nfunction resolveClientModuleUrl(manifest, moduleId) {\n const files = getManifestFilesForModule(resolveSsrManifest(manifest), moduleId);\n if (!files) return undefined;\n for (var i = 0; i < files.length; i++) {\n var file = files[i];\n if (!file || !file.endsWith(\".js\")) continue;\n if (file.charAt(0) !== \"/\") file = \"/\" + file;\n return file;\n }\n return undefined;\n}\n\nexport async function renderPage(request, url, manifest, ctx, middlewareHeaders, options) {\n if (ctx) return _runWithExecutionContext(ctx, () => _renderPage(request, url, manifest, middlewareHeaders, options));\n return _renderPage(request, url, manifest, middlewareHeaders, options);\n}\n\nasync function _renderPage(request, url, manifest, middlewareHeaders, options) {\n let isDataReq = !!(options && options.isDataReq);\n // Auto-detect /_next/data/... requests by inspecting the incoming request\n // URL. The worker pipeline does not need to know about the data endpoint\n // protocol — when it forwards an unrewritten data URL as the url arg, we\n // normalize it to the page path here.\n if (!isDataReq) {\n const __dataNorm = __normalizePagesDataRequest(request);\n if (__dataNorm.notFoundResponse) return __dataNorm.notFoundResponse;\n if (__dataNorm.isDataReq) {\n isDataReq = true;\n if (url && url.startsWith(\"/_next/data/\")) {\n const __qs = url.includes(\"?\") ? url.slice(url.indexOf(\"?\")) : \"\";\n url = __dataNorm.normalizedPathname + __qs;\n }\n }\n }\n const statusCode = options && typeof options.statusCode === \"number\" ? options.statusCode : undefined;\n const asPath = options && typeof options.asPath === \"string\" ? options.asPath : undefined;\n const renderErrorPageOnMiss = !(options && options.renderErrorPageOnMiss === false);\n // Guard against infinite recursion when the user's custom 500/error page\n // itself throws during render. When this flag is set, the catch block below\n // returns the plain \"Internal Server Error\" text response instead of trying\n // to render an error page again. Fixes #1458.\n const isInternalErrorRender = !!(options && options.__isInternalErrorRender);\n const localeInfo = i18nConfig\n ? resolvePagesI18nRequest(\n url,\n i18nConfig,\n request.headers,\n new URL(request.url).hostname,\n vinextConfig.basePath,\n vinextConfig.trailingSlash,\n )\n : { locale: undefined, url, hadPrefix: false, domainLocale: undefined, redirectUrl: undefined };\n const locale = localeInfo.locale;\n const routeUrl = localeInfo.url;\n const currentDefaultLocale = i18nConfig\n ? (localeInfo.domainLocale ? localeInfo.domainLocale.defaultLocale : i18nConfig.defaultLocale)\n : undefined;\n const domainLocales = i18nConfig ? i18nConfig.domains : undefined;\n const i18nCacheVariant = i18nConfig\n ? (localeInfo.domainLocale\n ? \"domain:\" + String(localeInfo.domainLocale.domain).toLowerCase()\n : \"locale:\" + String(locale))\n : null;\n const pageIsrCacheKey = i18nCacheVariant\n ? (router, pathname) => isrCacheKey(router, pathname + \"::i18n=\" + encodeURIComponent(i18nCacheVariant))\n : isrCacheKey;\n\n if (localeInfo.redirectUrl) {\n return new Response(null, { status: 307, headers: { Location: localeInfo.redirectUrl } });\n }\n\n // Internal error render path: caller has pinned a specific route (the\n // user's pages/500 or pages/_error) to render in response to an SSR throw.\n // Skip route matching so we don't accidentally double-route, and skip the\n // missing-route 404 fallback. See catch block below. Fixes #1458.\n let match = options && options.__forcedRoute\n ? { route: options.__forcedRoute, params: {} }\n : matchRoute(routeUrl, pageRoutes);\n let renderStatusCodeOverride = statusCode;\n let renderAsPath = asPath;\n if (!match) {\n if (isDataReq) {\n return __buildNextDataNotFoundResponse();\n }\n if (!renderErrorPageOnMiss) {\n return __buildDefaultPagesNotFoundResponse();\n }\n const notFoundMatch = matchRoute(\"/404\", pageRoutes);\n // matchRoute may match a catch-all (e.g. [...slug]); only use the explicit pages/404 route.\n if (notFoundMatch && notFoundMatch.route.pattern === \"/404\") {\n match = notFoundMatch;\n renderStatusCodeOverride = 404;\n renderAsPath = routeUrl;\n } else if (_errorPageRoute) {\n match = { route: _errorPageRoute, params: {} };\n renderStatusCodeOverride = 404;\n renderAsPath = routeUrl;\n } else {\n return __buildDefaultPagesNotFoundResponse();\n }\n }\n\n const { route, params } = match;\n const __uCtx = _createUnifiedCtx({\n executionContext: _getRequestExecutionContext(),\n });\n return _runWithUnifiedCtx(__uCtx, async () => {\n ensureFetchPatch();\n try {\n const routePattern = patternToNextFormat(route.pattern);\n const renderStatusCode = renderStatusCodeOverride ?? (routePattern === \"/404\" ? 404 : undefined);\n const query = mergeRouteParamsIntoQuery(parseQuery(routeUrl), params);\n if (typeof setSSRContext === \"function\") {\n setSSRContext({\n pathname: routePattern,\n query,\n asPath: renderAsPath || routeUrl,\n locale: locale,\n locales: i18nConfig ? i18nConfig.locales : undefined,\n defaultLocale: currentDefaultLocale,\n domainLocales: domainLocales,\n });\n }\n\n if (i18nConfig) {\n setI18nContext({\n locale: locale,\n locales: i18nConfig.locales,\n defaultLocale: currentDefaultLocale,\n domainLocales: domainLocales,\n hostname: new URL(request.url).hostname,\n });\n }\n\n const pageModule = route.module;\n const PageComponent = pageModule.default;\n if (!PageComponent) {\n return new Response(\"Page has no default export\", { status: 500 });\n }\n\n // Refs #1463: reject non-GET/HEAD methods on static (no\n // getServerSideProps) Pages routes with 405 + Allow: GET, HEAD.\n // Skip for error/status pages (/_error, /404, /500), data requests\n // (those go through the JSON envelope path and have their own shape),\n // and renders that are already an error-page miss-render override.\n // Mirrors Next.js's base-server.ts L2277 carve-outs.\n if (\n !isDataReq &&\n routePattern !== \"/_error\" &&\n routePattern !== \"/404\" &&\n routePattern !== \"/500\" &&\n renderStatusCodeOverride === undefined\n ) {\n const methodResponse = __resolvePagesPageMethodResponse({\n hasGetServerSideProps: typeof pageModule.getServerSideProps === \"function\",\n method: request.method,\n });\n if (methodResponse) {\n return methodResponse;\n }\n }\n\n const pageModuleUrl = resolveClientModuleUrl(manifest, route.filePath);\n const appModuleUrl = resolveClientModuleUrl(manifest, _appAssetPath);\n const scriptNonce = __getScriptNonceFromHeaderSources(request.headers, middlewareHeaders);\n // Build font Link header early so it's available for ISR cached responses too.\n // Font preloads are module-level state populated at import time and persist across requests.\n var _fontLinkHeader = \"\";\n var _allFp = [];\n try {\n var _fpGoogle = typeof _getSSRFontPreloadsGoogle === \"function\" ? _getSSRFontPreloadsGoogle() : [];\n var _fpLocal = typeof _getSSRFontPreloadsLocal === \"function\" ? _getSSRFontPreloadsLocal() : [];\n _allFp = _fpGoogle.concat(_fpLocal);\n if (_allFp.length > 0) {\n _fontLinkHeader = _allFp.map(function(p) { return \"<\" + p.href + \">; rel=preload; as=font; type=\" + p.type + \"; crossorigin\"; }).join(\", \");\n }\n } catch (e) { /* font preloads not available */ }\n const pageDataResult = await __resolvePagesPageData({\n isDataReq,\n applyRequestContexts() {\n if (typeof setSSRContext === \"function\") {\n setSSRContext({\n pathname: routePattern,\n query,\n asPath: renderAsPath || routeUrl,\n locale: locale,\n locales: i18nConfig ? i18nConfig.locales : undefined,\n defaultLocale: currentDefaultLocale,\n domainLocales: domainLocales,\n });\n }\n if (i18nConfig) {\n setI18nContext({\n locale: locale,\n locales: i18nConfig.locales,\n defaultLocale: currentDefaultLocale,\n domainLocales: domainLocales,\n hostname: new URL(request.url).hostname,\n });\n }\n },\n buildId,\n createGsspReqRes() {\n return __createPagesReqRes({ body: undefined, query, request, url: routeUrl });\n },\n createPageElement(currentPageProps) {\n var currentElement = AppComponent\n ? React.createElement(AppComponent, { Component: PageComponent, pageProps: currentPageProps })\n : React.createElement(PageComponent, currentPageProps);\n return wrapWithRouterContext(currentElement);\n },\n fontLinkHeader: _fontLinkHeader,\n i18n: {\n locale: locale,\n locales: i18nConfig ? i18nConfig.locales : undefined,\n defaultLocale: currentDefaultLocale,\n domainLocales: domainLocales,\n },\n isrCacheKey: pageIsrCacheKey,\n isrGet,\n isrSet,\n expireSeconds: vinextConfig.expireTime,\n // The vinext build phase boots the prod server with VINEXT_PRERENDER=1\n // and fetches every statically-generated page through it. That hit is\n // the \"build\" prerender for revalidateReason; runtime hits are not.\n // Mirrors Next.js's \\`renderOpts.isBuildTimePrerendering\\`. See\n // \\`.nextjs-ref/packages/next/src/server/render.tsx\\` and\n // \\`packages/vinext/src/build/prerender.ts\\`.\n isBuildTimePrerendering: typeof process !== \"undefined\" && process.env && process.env.VINEXT_PRERENDER === \"1\",\n pageModule,\n params,\n query,\n renderIsrPassToStringAsync,\n route: {\n isDynamic: route.isDynamic,\n },\n routePattern,\n routeUrl,\n runInFreshUnifiedContext(callback) {\n var revalCtx = _createUnifiedCtx({\n executionContext: _getRequestExecutionContext(),\n });\n return _runWithUnifiedCtx(revalCtx, async () => {\n ensureFetchPatch();\n return callback();\n });\n },\n safeJsonStringify,\n sanitizeDestination: sanitizeDestinationLocal,\n scriptNonce,\n statusCode: renderStatusCode,\n triggerBackgroundRegeneration,\n vinext: {\n pageModuleUrl,\n appModuleUrl,\n hasMiddleware: __hasMiddleware,\n },\n });\n if (pageDataResult.kind === \"response\") {\n return pageDataResult.response;\n }\n let pageProps = pageDataResult.pageProps;\n if (routePattern === \"/_error\" && typeof renderStatusCode === \"number\") {\n pageProps = { ...pageProps, statusCode: renderStatusCode };\n }\n var gsspRes = pageDataResult.gsspRes;\n let isrRevalidateSeconds = pageDataResult.isrRevalidateSeconds;\n const isFallbackRender = pageDataResult.isFallback === true;\n\n // Republish the SSR context with isFallback flipped on so the page's\n // \\`useRouter().isFallback\\` returns true during render, matching Next.js's\n // \\`render.tsx\\` fallback shell. Without this, the page would still see\n // \\`isFallback: false\\` and run the non-fallback branch.\n if (isFallbackRender && typeof setSSRContext === \"function\") {\n setSSRContext({\n pathname: routePattern,\n query,\n asPath: renderAsPath || routeUrl,\n locale: locale,\n locales: i18nConfig ? i18nConfig.locales : undefined,\n defaultLocale: currentDefaultLocale,\n domainLocales: domainLocales,\n isFallback: true,\n });\n }\n\n // ── _next/data JSON envelope short-circuit ───────────────────────\n // For client-side navigations Next.js fetches /_next/data/<buildId>/<page>.json\n // and expects { pageProps } as JSON instead of the full HTML page. Skip\n // rendering the React tree and emit the JSON envelope directly via the\n // typed helper so the envelope shape stays in one place. Headers and\n // cookies set on the gsspRes by getServerSideProps are forwarded so\n // middleware/auth flows work the same as the HTML page.\n if (isDataReq) {\n const init = { headers: {} };\n if (gsspRes && typeof gsspRes.getHeaders === \"function\") {\n const gsspHeaders = gsspRes.getHeaders();\n for (const k of Object.keys(gsspHeaders)) {\n const v = gsspHeaders[k];\n if (v === undefined || v === null) continue;\n init.headers[k] = Array.isArray(v) ? v.join(\", \") : String(v);\n }\n }\n if (gsspRes) {\n // Default Cache-Control for gSSP-driven _next/data responses,\n // matching Next.js's pages-handler.ts (revalidate: 0 →\n // getCacheControlHeader). Skip when gSSP already set one via\n // res.setHeader (case-insensitive). Mirrors the HTML branch in\n // pages-page-response.ts and the dev-server branch. Fixes #1461.\n var hasUserCacheControl = false;\n for (const headerKey of Object.keys(init.headers)) {\n if (headerKey.toLowerCase() === \"cache-control\") {\n hasUserCacheControl = true;\n break;\n }\n }\n if (!hasUserCacheControl) {\n init.headers[\"Cache-Control\"] =\n \"private, no-cache, no-store, max-age=0, must-revalidate\";\n }\n }\n return __buildNextDataJsonResponse(pageProps, safeJsonStringify, init);\n }\n\n // Include both the matched page module and the global _app module\n // (if present). _app is wrapped around every page in Pages Router,\n // and any CSS/JS it imports must be linked from the rendered HTML\n // so the browser actually loads it. Without _app in this list, a\n // global stylesheet imported via import \"./globals.scss\" in\n // _app.tsx never reaches the page, producing the LHF-5 symptom\n // where styled elements render with the browser default colour.\n const pageModuleIds = [];\n if (route.filePath) pageModuleIds.push(route.filePath);\n if (_appAssetPath) pageModuleIds.push(_appAssetPath);\n const assetTags = collectAssetTags(manifest, pageModuleIds, scriptNonce);\n\n return __renderPagesPageResponse({\n assetTags,\n buildId,\n clearSsrContext() {\n if (typeof setSSRContext === \"function\") setSSRContext(null);\n },\n createPageElement(currentPageProps) {\n var currentElement;\n if (AppComponent) {\n currentElement = React.createElement(AppComponent, { Component: PageComponent, pageProps: currentPageProps });\n } else {\n currentElement = React.createElement(PageComponent, currentPageProps);\n }\n return wrapWithRouterContext(currentElement);\n },\n // Used by \\`_document.getInitialProps\\` -> \\`ctx.renderPage\\` to wrap\n // App/Component with user-provided enhancers (e.g. styled-components,\n // emotion). Falls back to identity when no enhancers are passed.\n // \\`pageProps\\` is captured from the closure (unlike \\`createPageElement\\`\n // which takes it as a param) — \\`enhancePageElement\\` is only ever invoked\n // for this one request with this one \\`pageProps\\`, so there is no value to\n // thread through; the renderPage contract only varies the enhancers.\n enhancePageElement(renderPageOpts) {\n var FinalApp = AppComponent;\n var FinalComp = PageComponent;\n if (renderPageOpts && typeof renderPageOpts.enhanceApp === \"function\" && FinalApp) {\n FinalApp = renderPageOpts.enhanceApp(FinalApp);\n }\n if (renderPageOpts && typeof renderPageOpts.enhanceComponent === \"function\") {\n FinalComp = renderPageOpts.enhanceComponent(FinalComp);\n }\n var enhancedElement;\n if (FinalApp) {\n enhancedElement = React.createElement(FinalApp, { Component: FinalComp, pageProps: pageProps });\n } else {\n enhancedElement = React.createElement(FinalComp, pageProps);\n }\n return wrapWithRouterContext(enhancedElement);\n },\n DocumentComponent,\n flushPreloads: typeof flushPreloads === \"function\" ? flushPreloads : undefined,\n fontLinkHeader: _fontLinkHeader,\n fontPreloads: _allFp,\n getFontLinks() {\n try {\n return typeof _getSSRFontLinks === \"function\" ? _getSSRFontLinks() : [];\n } catch (e) {\n return [];\n }\n },\n getFontStyles() {\n try {\n var allFontStyles = [];\n if (typeof _getSSRFontStylesGoogle === \"function\") allFontStyles.push(..._getSSRFontStylesGoogle());\n if (typeof _getSSRFontStylesLocal === \"function\") allFontStyles.push(..._getSSRFontStylesLocal());\n return allFontStyles;\n } catch (e) {\n return [];\n }\n },\n getSSRHeadHTML: typeof getSSRHeadHTML === \"function\" ? getSSRHeadHTML : undefined,\n clientTraceMetadata: vinextConfig.clientTraceMetadata,\n gsspRes,\n isrCacheKey: pageIsrCacheKey,\n expireSeconds: vinextConfig.expireTime,\n isrRevalidateSeconds,\n isrSet,\n i18n: {\n locale: locale,\n locales: i18nConfig ? i18nConfig.locales : undefined,\n defaultLocale: currentDefaultLocale,\n domainLocales: domainLocales,\n },\n isFallback: isFallbackRender,\n pageProps,\n params,\n renderDocumentToString(element) {\n return renderToStringAsync(element);\n },\n renderToReadableStream(element) {\n return renderToReadableStream(element);\n },\n resetSSRHead: typeof resetSSRHead === \"function\" ? resetSSRHead : undefined,\n setDocumentInitialHead:\n typeof setDocumentInitialHead === \"function\" ? setDocumentInitialHead : undefined,\n routePattern,\n routeUrl,\n safeJsonStringify,\n scriptNonce,\n statusCode: renderStatusCode,\n vinext: {\n pageModuleUrl,\n appModuleUrl,\n hasMiddleware: __hasMiddleware,\n },\n });\n } catch (e) {\n console.error(\"[vinext] SSR error:\", e);\n _reportRequestError(\n e instanceof Error ? e : new Error(String(e)),\n { path: url, method: request.method, headers: Object.fromEntries(request.headers.entries()) },\n { routerKind: \"Pages Router\", routePath: route.pattern, routeType: \"render\" },\n ).catch(() => { /* ignore reporting errors */ });\n // Data (_next/data) requests can't render HTML, and avoid recursion if\n // we're already in the middle of rendering the error page itself.\n // Mirrors Next.js base-server.ts which renders /500 (or _error) when\n // SSR throws. Fixes #1458.\n if (!isInternalErrorRender && !isDataReq) {\n // Look for an explicit pages/500.tsx first, then fall back to _error.\n // Only match the literal /500 pattern — never a catch-all/dynamic route.\n let errorRoute = null;\n for (var __i = 0; __i < pageRoutes.length; __i++) {\n if (pageRoutes[__i].pattern === \"/500\") {\n errorRoute = pageRoutes[__i];\n break;\n }\n }\n if (!errorRoute && _errorPageRoute) {\n errorRoute = _errorPageRoute;\n }\n if (errorRoute) {\n try {\n return await _renderPage(request, url, manifest, middlewareHeaders, {\n statusCode: 500,\n asPath: url,\n renderErrorPageOnMiss: false,\n __isInternalErrorRender: true,\n __forcedRoute: errorRoute,\n });\n } catch (errorPageErr) {\n console.error(\"[vinext] Error page render failed:\", errorPageErr);\n }\n }\n }\n return new Response(\"Internal Server Error\", { status: 500 });\n }\n });\n}\n\nexport async function handleApiRoute(request, url, ctx) {\n const match = matchRoute(url, apiRoutes);\n return __handlePagesApiRoute({\n ctx,\n match,\n request,\n url,\n reportRequestError(error, routePattern) {\n console.error(\"[vinext] API error:\", error);\n void _reportRequestError(\n error,\n { path: url, method: request.method, headers: Object.fromEntries(request.headers.entries()) },\n { routerKind: \"Pages Router\", routePath: routePattern, routeType: \"route\" },\n );\n },\n });\n}\n\n${middlewareExportCode}\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiBA,MAAM,0BAA0B,iBAAiB,+BAA+B,OAAO,KAAK,IAAI;AAChG,MAAM,yBAAyB,iBAAiB,mCAAmC,OAAO,KAAK,IAAI;AACnG,MAAM,iBAAiB,iBAAiB,4BAA4B,OAAO,KAAK,IAAI;AACpF,MAAM,iBAAiB,iBAAiB,2BAA2B,OAAO,KAAK,IAAI;AACnF,MAAM,yBAAyB,iBAC7B,oCACA,OAAO,KAAK,IACb;AACD,MAAM,qBAAqB,iBAAiB,gCAAgC,OAAO,KAAK,IAAI;AAC5F,MAAM,uBAAuB,iBAAiB,kCAAkC,OAAO,KAAK,IAAI;AAChG,MAAM,sBAAsB,iBA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RODUCTION_BUILD } from "./shims/constants.js";
33
33
  import { ASSET_PREFIX_URL_DIR, resolveAssetUrlPrefix, resolveAssetsDir } from "./utils/asset-prefix.js";
34
34
  import { RESOLVED_VIRTUAL_GOOGLE_FONTS, VIRTUAL_GOOGLE_FONTS, createGoogleFontsPlugin, createLocalFontsPlugin, generateGoogleFontsVirtualModule, parseStaticObjectLiteral } from "./plugins/fonts.js";
35
+ import { getViteMajorVersion } from "./utils/vite-version.js";
35
36
  import { findNextConfigPath, loadNextConfig, resolveNextConfig, resolveNextConfigInput } from "./config/next-config.js";
36
37
  import { isNextDataPathname, parseNextDataPathname } from "./server/pages-data-route.js";
37
38
  import { precompressAssets } from "./build/precompress.js";
38
39
  import { collectInlineCssManifest, injectInlineCssManifestGlobal } from "./build/inline-css.js";
39
- import { manifestFileWithBase, manifestFilesWithBase } from "./utils/manifest-paths.js";
40
+ import { manifestFilesWithBase } from "./utils/manifest-paths.js";
40
41
  import { asyncHooksStubPlugin } from "./plugins/async-hooks-stub.js";
41
42
  import { clientReferenceDedupPlugin } from "./plugins/client-reference-dedup.js";
42
43
  import { dataUrlCssPlugin } from "./plugins/css-data-url.js";
@@ -50,6 +51,7 @@ import { generateRouteTypes } from "./typegen.js";
50
51
  import { SSR_EXTERNAL_REACT_ENTRIES, VINEXT_OPTIMIZE_DEPS_EXCLUDE, mergeOptimizeDepsExclude } from "./plugins/rsc-client-shim-excludes.js";
51
52
  import { createServerExternalsManifestPlugin } from "./plugins/server-externals-manifest.js";
52
53
  import { computeLazyChunks } from "./utils/lazy-chunks.js";
54
+ import { findClientEntryFile, readClientBuildManifest } from "./utils/client-build-manifest.js";
53
55
  import { formatMissingCloudflarePluginError, hasWranglerConfig } from "./deploy.js";
54
56
  import { resolvePostcssStringPlugins } from "./plugins/postcss.js";
55
57
  import { buildSassPreprocessorOptions } from "./plugins/sass.js";
@@ -57,6 +59,7 @@ import { createClientCodeSplittingConfig, createClientManualChunks, createClient
57
59
  import { augmentSsrManifestFromBundle, relativeWithinRoot, tryRealpathSync } from "./build/ssr-manifest.js";
58
60
  import { stripServerExports } from "./plugins/strip-server-exports.js";
59
61
  import { removeConsoleCalls } from "./plugins/remove-console.js";
62
+ import { createImportMetaUrlPlugin } from "./plugins/import-meta-url.js";
60
63
  import { hasMdxFiles } from "./utils/mdx-scan.js";
61
64
  import { scanPublicFileRoutes } from "./utils/public-routes.js";
62
65
  import { staticExportApp, staticExportPages } from "./build/static-export.js";
@@ -75,6 +78,50 @@ function createRscCompatibilityId(nextConfig) {
75
78
  if (nextConfig.deploymentId) return nextConfig.deploymentId;
76
79
  return randomUUID();
77
80
  }
81
+ function hasModuleLevelUseServerDirective(body) {
82
+ for (const node of body) {
83
+ if (node.type !== "ExpressionStatement") break;
84
+ const directive = node.directive;
85
+ const expression = node.expression;
86
+ const value = typeof directive === "string" ? directive : expression?.type === "Literal" ? expression.value : void 0;
87
+ if (value === "use server") return true;
88
+ if (typeof value !== "string") break;
89
+ }
90
+ return false;
91
+ }
92
+ function hasServerOnlyMarkerImport(code) {
93
+ if (!code.includes("server-only")) return false;
94
+ let ast;
95
+ try {
96
+ ast = parseAst(code);
97
+ } catch {
98
+ return false;
99
+ }
100
+ if (hasModuleLevelUseServerDirective(ast.body)) return false;
101
+ function walk(node) {
102
+ if (!node) return false;
103
+ if (Array.isArray(node)) return node.some((child) => walk(child));
104
+ if (typeof node !== "object") return false;
105
+ if (node.type === "ImportDeclaration") {
106
+ if (node.source?.value === "server-only") return true;
107
+ }
108
+ if (node.type === "CallExpression") {
109
+ const call = node;
110
+ if (call.callee?.type === "Identifier" && call.callee.name === "require" && call.arguments?.[0]?.type === "Literal" && call.arguments[0].value === "server-only") return true;
111
+ }
112
+ for (const key of Object.keys(node)) {
113
+ if (key === "type" || key === "start" || key === "end" || key === "loc" || key === "parent") continue;
114
+ const value = node[key];
115
+ if (Array.isArray(value)) {
116
+ if (value.some((child) => child && typeof child === "object" && walk(child))) return true;
117
+ } else if (value && typeof value === "object" && "type" in value) {
118
+ if (walk(value)) return true;
119
+ }
120
+ }
121
+ return false;
122
+ }
123
+ return walk(ast.body);
124
+ }
78
125
  const __dirname = import.meta.dirname;
79
126
  function resolveOptionalDependency(projectRoot, specifier) {
80
127
  try {
@@ -194,27 +241,6 @@ function loadTsconfigPathAliases(configPath, projectRoot, seen = /* @__PURE__ */
194
241
  };
195
242
  }
196
243
  /**
197
- * Detect Vite major version at runtime by resolving from cwd.
198
- * The plugin may be installed in a workspace root with Vite 7 but used
199
- * by a project that has Vite 8 — so we resolve from cwd, not from
200
- * the plugin's own location.
201
- */
202
- function getViteMajorVersion() {
203
- try {
204
- const vitePkg = createRequire(path.join(process.cwd(), "package.json"))("vite/package.json");
205
- const viteMajor = parseInt(vitePkg?.version, 10);
206
- if (vitePkg?.name === "vite" && Number.isFinite(viteMajor)) return viteMajor;
207
- const bundledViteMajor = parseInt(vitePkg?.bundledVersions?.vite, 10);
208
- if (Number.isFinite(bundledViteMajor)) return bundledViteMajor;
209
- console.warn(`[vinext] Could not determine Vite major version from ${vitePkg?.name ?? "vite/package.json"}; assuming Vite 7`);
210
- return 7;
211
- } catch (error) {
212
- const message = error instanceof Error ? error.message : String(error);
213
- console.warn(`[vinext] Failed to resolve vite/package.json (${message}); assuming Vite 7`);
214
- return 7;
215
- }
216
- }
217
- /**
218
244
  * Read the vinext package version once at plugin load. Surfaced via
219
245
  * `process.env.__NEXT_VERSION` define so `window.next.version` lands a
220
246
  * real string instead of the `"vinext"` fallback. Resolved relative to
@@ -557,6 +583,7 @@ function vinext(options = {}) {
557
583
  }
558
584
  defines["process.env.__NEXT_ROUTER_BASEPATH"] = JSON.stringify(nextConfig.basePath);
559
585
  defines["process.env.__NEXT_CLIENT_ROUTER_STATIC_STALETIME"] = JSON.stringify(String(nextConfig.staleTimes.static));
586
+ defines["process.env.__VINEXT_PREFETCH_INLINING"] = JSON.stringify(nextConfig.prefetchInlining ? "true" : "false");
560
587
  defines["process.env.__VINEXT_TRAILING_SLASH"] = JSON.stringify(nextConfig.trailingSlash ? "true" : "false");
561
588
  defines["process.env.__VINEXT_IMAGE_REMOTE_PATTERNS"] = JSON.stringify(JSON.stringify(nextConfig.images?.remotePatterns ?? []));
562
589
  defines["process.env.__VINEXT_IMAGE_DOMAINS"] = JSON.stringify(JSON.stringify(nextConfig.images?.domains ?? []));
@@ -591,7 +618,7 @@ function vinext(options = {}) {
591
618
  defines["process.env.__VINEXT_DEPLOYMENT_ID"] = JSON.stringify(nextConfig.deploymentId ?? "");
592
619
  defines["process.env.NEXT_DEPLOYMENT_ID"] = nextConfig.deploymentId ? JSON.stringify(nextConfig.deploymentId) : "false";
593
620
  defines["process.env.__NEXT_VERSION"] = JSON.stringify(getVinextVersion());
594
- defines["process.env.__NEXT_APP_SHELLS"] = JSON.stringify(false);
621
+ defines["process.env.__NEXT_APP_SHELLS"] = JSON.stringify(nextConfig.appShells);
595
622
  for (const [key, value] of Object.entries(nextConfig.compilerDefine)) {
596
623
  if (key in defines) throw new Error(`The \`compiler.define\` option is configured to replace the \`${key}\` variable. This variable is either part of a built-in or is already configured.`);
597
624
  defines[key] = value;
@@ -938,6 +965,7 @@ function vinext(options = {}) {
938
965
  clientTraceMetadata: nextConfig?.clientTraceMetadata,
939
966
  assetPrefix: nextConfig?.assetPrefix,
940
967
  expireTime: nextConfig?.expireTime,
968
+ cacheMaxMemorySize: nextConfig?.cacheMaxMemorySize,
941
969
  inlineCss: nextConfig?.inlineCss,
942
970
  i18n: nextConfig?.i18n,
943
971
  hasPagesDir,
@@ -1464,6 +1492,21 @@ function vinext(options = {}) {
1464
1492
  };
1465
1493
  }
1466
1494
  },
1495
+ {
1496
+ name: "vinext:validate-server-only-client-imports",
1497
+ transform: {
1498
+ filter: {
1499
+ id: /\.(tsx?|jsx?|mjs)$/,
1500
+ code: "server-only"
1501
+ },
1502
+ handler(code, id) {
1503
+ if (this.environment?.name !== "client") return null;
1504
+ if (id.startsWith("\0")) return null;
1505
+ if (!hasServerOnlyMarkerImport(code)) return null;
1506
+ throw new Error(`You're importing a module that depends on "server-only". This API is only available in Server Components in the App Router, but this module is reachable from a client bundle.`);
1507
+ }
1508
+ }
1509
+ },
1467
1510
  {
1468
1511
  name: "vinext:strip-server-exports",
1469
1512
  transform: {
@@ -1681,6 +1724,7 @@ function vinext(options = {}) {
1681
1724
  }
1682
1725
  }
1683
1726
  },
1727
+ createImportMetaUrlPlugin({ getRoot: () => root }),
1684
1728
  createOgInlineFetchAssetsPlugin(),
1685
1729
  ogAssetsPlugin,
1686
1730
  createServerExternalsManifestPlugin(),
@@ -1896,16 +1940,17 @@ function vinext(options = {}) {
1896
1940
  const clientBase = envConfig.base ?? "/";
1897
1941
  let lazyChunksData = null;
1898
1942
  let clientEntryFile = null;
1899
- const buildManifestPath = path.join(clientDir, ".vite", "manifest.json");
1900
- if (fs.existsSync(buildManifestPath)) try {
1901
- const buildManifest = JSON.parse(fs.readFileSync(buildManifestPath, "utf-8"));
1902
- for (const [, value] of Object.entries(buildManifest)) if (value && value.isEntry && value.file) {
1903
- clientEntryFile = manifestFileWithBase(value.file, clientBase);
1904
- break;
1905
- }
1943
+ const buildManifest = readClientBuildManifest(path.join(clientDir, ".vite", "manifest.json"));
1944
+ if (buildManifest) {
1945
+ clientEntryFile = findClientEntryFile({
1946
+ buildManifest,
1947
+ clientDir,
1948
+ assetsSubdir: resolveAssetsDir(nextConfig?.assetPrefix),
1949
+ assetBase: clientBase
1950
+ }) ?? null;
1906
1951
  const lazy = manifestFilesWithBase(computeLazyChunks(buildManifest), clientBase);
1907
1952
  if (lazy.length > 0) lazyChunksData = lazy;
1908
- } catch {}
1953
+ }
1909
1954
  let ssrManifestData = null;
1910
1955
  const ssrManifestPath = path.join(clientDir, ".vite", "ssr-manifest.json");
1911
1956
  if (fs.existsSync(ssrManifestPath)) try {
@@ -1934,14 +1979,11 @@ function vinext(options = {}) {
1934
1979
  if (!workerOutDir) return;
1935
1980
  const workerEntry = path.join(workerOutDir, "index.js");
1936
1981
  if (!fs.existsSync(workerEntry)) return;
1937
- if (!clientEntryFile) {
1938
- const assetsSubdir = resolveAssetsDir(nextConfig?.assetPrefix);
1939
- const assetsDir = path.join(clientDir, assetsSubdir);
1940
- if (fs.existsSync(assetsDir)) {
1941
- const entry = fs.readdirSync(assetsDir).find((f) => (f.includes("vinext-client-entry") || f.includes("vinext-app-browser-entry")) && f.endsWith(".js"));
1942
- if (entry) clientEntryFile = manifestFileWithBase(`${assetsSubdir}/${entry}`, clientBase);
1943
- }
1944
- }
1982
+ if (!clientEntryFile) clientEntryFile = findClientEntryFile({
1983
+ clientDir,
1984
+ assetsSubdir: resolveAssetsDir(nextConfig?.assetPrefix),
1985
+ assetBase: clientBase
1986
+ }) ?? null;
1945
1987
  if (clientEntryFile || ssrManifestData || lazyChunksData) {
1946
1988
  let code = fs.readFileSync(workerEntry, "utf-8");
1947
1989
  const globals = [];