vinext 0.0.19 → 0.0.21

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 (71) hide show
  1. package/README.md +1 -1
  2. package/dist/check.d.ts.map +1 -1
  3. package/dist/check.js +2 -1
  4. package/dist/check.js.map +1 -1
  5. package/dist/cli.js +4 -4
  6. package/dist/cli.js.map +1 -1
  7. package/dist/config/next-config.d.ts +6 -0
  8. package/dist/config/next-config.d.ts.map +1 -1
  9. package/dist/config/next-config.js.map +1 -1
  10. package/dist/deploy.d.ts.map +1 -1
  11. package/dist/deploy.js +15 -1
  12. package/dist/deploy.js.map +1 -1
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +142 -18
  15. package/dist/index.js.map +1 -1
  16. package/dist/init.d.ts +9 -1
  17. package/dist/init.d.ts.map +1 -1
  18. package/dist/init.js +31 -2
  19. package/dist/init.js.map +1 -1
  20. package/dist/server/app-dev-server.d.ts.map +1 -1
  21. package/dist/server/app-dev-server.js +104 -13
  22. package/dist/server/app-dev-server.js.map +1 -1
  23. package/dist/server/dev-server.d.ts.map +1 -1
  24. package/dist/server/dev-server.js +31 -5
  25. package/dist/server/dev-server.js.map +1 -1
  26. package/dist/server/image-optimization.d.ts +17 -3
  27. package/dist/server/image-optimization.d.ts.map +1 -1
  28. package/dist/server/image-optimization.js +31 -13
  29. package/dist/server/image-optimization.js.map +1 -1
  30. package/dist/server/middleware.d.ts.map +1 -1
  31. package/dist/server/middleware.js +13 -4
  32. package/dist/server/middleware.js.map +1 -1
  33. package/dist/server/prod-server.d.ts.map +1 -1
  34. package/dist/server/prod-server.js +25 -8
  35. package/dist/server/prod-server.js.map +1 -1
  36. package/dist/shims/compat-router.d.ts +12 -0
  37. package/dist/shims/compat-router.d.ts.map +1 -0
  38. package/dist/shims/compat-router.js +23 -0
  39. package/dist/shims/compat-router.js.map +1 -0
  40. package/dist/shims/font-google.generated.d.ts.map +1 -1
  41. package/dist/shims/font-google.generated.js +1923 -1923
  42. package/dist/shims/font-google.generated.js.map +1 -1
  43. package/dist/shims/image.d.ts.map +1 -1
  44. package/dist/shims/image.js +16 -3
  45. package/dist/shims/image.js.map +1 -1
  46. package/dist/shims/link.d.ts.map +1 -1
  47. package/dist/shims/link.js +15 -13
  48. package/dist/shims/link.js.map +1 -1
  49. package/dist/shims/metadata.d.ts.map +1 -1
  50. package/dist/shims/metadata.js +15 -4
  51. package/dist/shims/metadata.js.map +1 -1
  52. package/dist/shims/navigation.d.ts +1 -0
  53. package/dist/shims/navigation.d.ts.map +1 -1
  54. package/dist/shims/navigation.js +16 -0
  55. package/dist/shims/navigation.js.map +1 -1
  56. package/dist/shims/router.d.ts +18 -0
  57. package/dist/shims/router.d.ts.map +1 -1
  58. package/dist/shims/router.js +63 -30
  59. package/dist/shims/router.js.map +1 -1
  60. package/dist/shims/script.d.ts.map +1 -1
  61. package/dist/shims/script.js +18 -18
  62. package/dist/shims/script.js.map +1 -1
  63. package/dist/shims/server.d.ts +11 -2
  64. package/dist/shims/server.d.ts.map +1 -1
  65. package/dist/shims/server.js +11 -2
  66. package/dist/shims/server.js.map +1 -1
  67. package/dist/utils/project.d.ts +12 -6
  68. package/dist/utils/project.d.ts.map +1 -1
  69. package/dist/utils/project.js +56 -21
  70. package/dist/utils/project.js.map +1 -1
  71. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"dev-server.d.ts","sourceRoot":"","sources":["../../src/server/dev-server.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,MAAM,CAAC;AAC1C,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACjE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,4BAA4B,CAAC;AAExD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAmK/D;;;;GAIG;AACH,wBAAgB,oBAAoB,CAClC,GAAG,EAAE,MAAM,EACX,UA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AAc,GACzB,MAAM,GAAG,IAAI,CA4Bf;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAC/B,GAAG,EAAE,eAAe,EACpB,UAAU,EAAE,cAAc,GACzB,MAAM,GAAG,IAAI,CAiBf;AAED;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,aAAa,EACrB,MAAM,EAAE,KAAK,EAAE,EACf,QAAQ,EAAE,MAAM,EAChB,UAAU,CAAC,EAAE,cAAc,GAAG,IAAI,IAGhC,KAAK,eAAe,EACpB,KAAK,cAAc,EACnB,KAAK,MAAM;AACX,wEAAwE;AACxE,aAAa,MAAM,KAClB,OAAO,CAAC,IAAI,CAAC,CAuhBjB"}
@@ -295,7 +295,7 @@ export function createSSRHandler(server, routes, pagesDir, i18nConfig) {
295
295
  });
296
296
  });
297
297
  if (!isValidPath) {
298
- await renderErrorPage(server, req, res, url, pagesDir, 404);
298
+ await renderErrorPage(server, req, res, url, pagesDir, 404, routerShim.wrapWithRouterContext);
299
299
  return;
300
300
  }
301
301
  }
@@ -336,7 +336,7 @@ export function createSSRHandler(server, routes, pagesDir, i18nConfig) {
336
336
  return;
337
337
  }
338
338
  if (result && "notFound" in result && result.notFound) {
339
- await renderErrorPage(server, req, res, url, pagesDir, 404);
339
+ await renderErrorPage(server, req, res, url, pagesDir, 404, routerShim.wrapWithRouterContext);
340
340
  return;
341
341
  }
342
342
  }
@@ -439,7 +439,7 @@ export function createSSRHandler(server, routes, pagesDir, i18nConfig) {
439
439
  return;
440
440
  }
441
441
  if (result && "notFound" in result && result.notFound) {
442
- await renderErrorPage(server, req, res, url, pagesDir, 404);
442
+ await renderErrorPage(server, req, res, url, pagesDir, 404, routerShim.wrapWithRouterContext);
443
443
  return;
444
444
  }
445
445
  // Extract revalidate period for ISR caching after render
@@ -465,6 +465,9 @@ export function createSSRHandler(server, routes, pagesDir, i18nConfig) {
465
465
  // React is CJS and the ESModulesEvaluator doesn't define `module`.
466
466
  const createElement = React.createElement;
467
467
  let element;
468
+ // wrapWithRouterContext wraps the element in RouterContext.Provider so that
469
+ // next/compat/router's useRouter() returns the real router.
470
+ const wrapWithRouterContext = routerShim.wrapWithRouterContext;
468
471
  if (AppComponent) {
469
472
  element = createElement(AppComponent, {
470
473
  Component: PageComponent,
@@ -474,6 +477,9 @@ export function createSSRHandler(server, routes, pagesDir, i18nConfig) {
474
477
  else {
475
478
  element = createElement(PageComponent, pageProps);
476
479
  }
480
+ if (wrapWithRouterContext) {
481
+ element = wrapWithRouterContext(element);
482
+ }
477
483
  // Reset SSR head collector before rendering so <Head> tags are captured
478
484
  const headShim = await server.ssrLoadModule("next/head");
479
485
  if (typeof headShim.resetSSRHead === "function") {
@@ -547,6 +553,7 @@ export function createSSRHandler(server, routes, pagesDir, i18nConfig) {
547
553
  <script type="module">
548
554
  import React from "react";
549
555
  import { hydrateRoot } from "react-dom/client";
556
+ import { wrapWithRouterContext } from "next/router";
550
557
 
551
558
  const nextData = window.__NEXT_DATA__;
552
559
  const { pageProps } = nextData.props;
@@ -565,6 +572,7 @@ async function hydrate() {
565
572
  : `
566
573
  element = React.createElement(PageComponent, pageProps);
567
574
  `}
575
+ element = wrapWithRouterContext(element);
568
576
  const root = hydrateRoot(document.getElementById("__next"), element);
569
577
  window.__VINEXT_ROOT__ = root;
570
578
  }
@@ -636,9 +644,12 @@ hydrate();
636
644
  // For ISR, re-render synchronously to get the complete HTML string.
637
645
  // This runs after the stream is already sent, so it doesn't affect TTFB.
638
646
  if (isrRevalidateSeconds !== null && isrRevalidateSeconds > 0) {
639
- const isrElement = AppComponent
647
+ let isrElement = AppComponent
640
648
  ? createElement(AppComponent, { Component: pageModule.default, pageProps })
641
649
  : createElement(pageModule.default, pageProps);
650
+ if (wrapWithRouterContext) {
651
+ isrElement = wrapWithRouterContext(isrElement);
652
+ }
642
653
  const isrBodyHtml = await renderToStringAsync(isrElement);
643
654
  const isrHtml = `<!DOCTYPE html><html><head></head><body><div id="__next">${isrBodyHtml}</div>${allScripts}</body></html>`;
644
655
  const cacheKey = isrCacheKey("pages", url.split("?")[0]);
@@ -687,7 +698,7 @@ hydrate();
687
698
  * - 500: pages/500.tsx -> pages/_error.tsx -> default
688
699
  * - other: pages/_error.tsx -> default
689
700
  */
690
- async function renderErrorPage(server, _req, res, url, pagesDir, statusCode) {
701
+ async function renderErrorPage(server, _req, res, url, pagesDir, statusCode, wrapWithRouterContext) {
691
702
  // Try specific status page first, then _error, then fallback
692
703
  const candidates = statusCode === 404
693
704
  ? ["404", "_error"]
@@ -717,6 +728,18 @@ async function renderErrorPage(server, _req, res, url, pagesDir, statusCode) {
717
728
  }
718
729
  const createElement = React.createElement;
719
730
  const errorProps = { statusCode };
731
+ // If the caller didn't supply wrapWithRouterContext, load it now.
732
+ // ssrLoadModule caches internally so the cost is negligible.
733
+ let wrapFn = wrapWithRouterContext;
734
+ if (!wrapFn) {
735
+ try {
736
+ const errRouterShim = await server.ssrLoadModule("next/router");
737
+ wrapFn = errRouterShim.wrapWithRouterContext;
738
+ }
739
+ catch {
740
+ // router shim not available — continue without it
741
+ }
742
+ }
720
743
  let element;
721
744
  if (AppComponent) {
722
745
  element = createElement(AppComponent, {
@@ -727,6 +750,9 @@ async function renderErrorPage(server, _req, res, url, pagesDir, statusCode) {
727
750
  else {
728
751
  element = createElement(ErrorComponent, errorProps);
729
752
  }
753
+ if (wrapFn) {
754
+ element = wrapFn(element);
755
+ }
730
756
  const bodyHtml = await renderToStringAsync(element);
731
757
  // Try custom _document
732
758
  let html;
@@ -1 +1 @@
1
- {"version":3,"file":"dev-server.js","sourceRoot":"","sources":["../../src/server/dev-server.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAE7E,OAAO,EACL,MAAM,EACN,MAAM,EACN,WAAW,EACX,oBAAoB,EACpB,6BAA6B,EAC7B,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,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G,UAAU,MAAM,UAAU,KAAK,GAAG,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,uBAAuB,EAAE,CAAC,CAAC;AAChG,CAAC","sourcesContent":["import type { ViteDevServer } from \"vite\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { Route } from \"../routing/pages-router.js\";\nimport { matchRoute, patternToNextFormat } from \"../routing/pages-router.js\";\nimport type { NextI18nConfig } from \"../config/next-config.js\";\nimport {\n isrGet,\n isrSet,\n isrCacheKey,\n buildPagesCacheValue,\n triggerBackgroundRegeneration,\n setRevalidateDuration,\n getRevalidateDuration,\n} from \"./isr-cache.js\";\nimport type { CachedPagesValue } from \"../shims/cache.js\";\nimport { runWithFetchCache } from \"../shims/fetch-cache.js\";\nimport { _runWithCacheState } from \"../shims/cache.js\";\nimport { runWithPrivateCache } from \"../shims/cache-runtime.js\";\n// Import server-only state modules to register ALS-backed accessors.\n// These modules must be imported before any rendering occurs.\nimport { runWithRouterState } from \"../shims/router-state.js\";\nimport { runWithHeadState } from \"../shims/head-state.js\";\nimport { reportRequestError } from \"./instrumentation.js\";\nimport { safeJsonStringify } from \"./html.js\";\nimport { parseQueryString as parseQuery } from \"../utils/query.js\";\nimport path from \"node:path\";\nimport fs from \"node:fs\";\nimport React from \"react\";\nimport { renderToReadableStream } from \"react-dom/server.edge\";\n\nconst PAGE_EXTENSIONS = [\".tsx\", \".ts\", \".jsx\", \".js\"];\n\n/**\n * Render a React element to a string using renderToReadableStream.\n *\n * Uses the edge-compatible Web Streams API. Waits for all Suspense\n * boundaries to resolve via stream.allReady before collecting output.\n * Used for _document rendering and error pages (small, non-streaming).\n */\nasync function renderToStringAsync(element: React.ReactElement): Promise<string> {\n const stream = await renderToReadableStream(element);\n await stream.allReady;\n return new Response(stream).text();\n}\n\n/** Body placeholder used to split the document shell for streaming. */\nconst STREAM_BODY_MARKER = \"<!--VINEXT_STREAM_BODY-->\";\n\n/**\n * Stream a Pages Router page response using progressive SSR.\n *\n * Sends the HTML shell (head, layout, Suspense fallbacks) immediately\n * when the React shell is ready, then streams Suspense content as it\n * resolves. This gives the browser content to render while slow data\n * loads are still in flight.\n *\n * `__NEXT_DATA__` and the hydration script are appended after the body\n * stream completes (the data is known before rendering starts, but\n * deferring them reduces TTFB and lets the browser start parsing the\n * shell sooner).\n */\nasync function streamPageToResponse(\n res: ServerResponse,\n element: React.ReactElement,\n options: {\n url: string;\n server: ViteDevServer;\n fontHeadHTML: string;\n scripts: string;\n DocumentComponent: React.ComponentType | null;\n statusCode?: number;\n extraHeaders?: Record<string, string>;\n /** Called after renderToReadableStream resolves (shell ready) to collect head HTML */\n getHeadHTML: () => string;\n },\n): Promise<void> {\n const {\n url,\n server,\n fontHeadHTML,\n scripts,\n DocumentComponent,\n statusCode = 200,\n extraHeaders,\n getHeadHTML,\n } = options;\n\n // Start the React body stream FIRST — the promise resolves when the\n // shell is ready (synchronous content outside Suspense boundaries).\n // This triggers the render which populates <Head> tags.\n const bodyStream = await renderToReadableStream(element);\n\n // Now that the shell has rendered, collect head HTML\n const headHTML = getHeadHTML();\n\n // Build the document shell with a placeholder for the body\n let shellTemplate: string;\n\n if (DocumentComponent) {\n const docElement = React.createElement(DocumentComponent);\n let docHtml = await renderToStringAsync(docElement);\n // Replace __NEXT_MAIN__ with our stream marker\n docHtml = docHtml.replace(\"__NEXT_MAIN__\", STREAM_BODY_MARKER);\n // Inject head tags\n if (headHTML || fontHeadHTML) {\n docHtml = docHtml.replace(\"</head>\", ` ${fontHeadHTML}${headHTML}\\n</head>`);\n }\n // Inject scripts: replace placeholder or append before </body>\n docHtml = docHtml.replace(\"<!-- __NEXT_SCRIPTS__ -->\", scripts);\n if (!docHtml.includes(\"__NEXT_DATA__\")) {\n docHtml = docHtml.replace(\"</body>\", ` ${scripts}\\n</body>`);\n }\n shellTemplate = docHtml;\n } else {\n shellTemplate = `<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n ${fontHeadHTML}${headHTML}\n</head>\n<body>\n <div id=\"__next\">${STREAM_BODY_MARKER}</div>\n ${scripts}\n</body>\n</html>`;\n }\n\n // Apply Vite's HTML transforms (injects HMR client, etc.) on the full\n // shell template, then split at the body marker.\n const transformedShell = await server.transformIndexHtml(url, shellTemplate);\n const markerIdx = transformedShell.indexOf(STREAM_BODY_MARKER);\n const prefix = transformedShell.slice(0, markerIdx);\n const suffix = transformedShell.slice(markerIdx + STREAM_BODY_MARKER.length);\n\n // Send headers and start streaming\n const headers: Record<string, string> = {\n \"Content-Type\": \"text/html\",\n \"Transfer-Encoding\": \"chunked\",\n ...extraHeaders,\n };\n res.writeHead(statusCode, headers);\n\n // Write the document prefix (head, opening body)\n res.write(prefix);\n\n // Pipe the React body stream through (Suspense content streams progressively)\n const reader = bodyStream.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n res.write(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n // Write the document suffix (closing tags, scripts)\n res.end(suffix);\n}\n\n/** Check if a file exists with any page extension (tsx, ts, jsx, js). */\nfunction findFileWithExtensions(basePath: string): boolean {\n return PAGE_EXTENSIONS.some((ext) => fs.existsSync(basePath + ext));\n}\n\n/**\n * Extract locale prefix from a URL path.\n * e.g. /fr/about -> { locale: \"fr\", url: \"/about\", hadPrefix: true }\n * /about -> { locale: \"en\", url: \"/about\", hadPrefix: false } (defaultLocale)\n */\nexport function extractLocaleFromUrl(\n url: string,\n i18nConfig: NextI18nConfig,\n): { locale: string; url: string; hadPrefix: boolean } {\n const pathname = url.split(\"?\")[0];\n const parts = pathname.split(\"/\").filter(Boolean);\n const query = url.includes(\"?\") ? url.slice(url.indexOf(\"?\")) : \"\";\n\n if (parts.length > 0 && i18nConfig.locales.includes(parts[0])) {\n const locale = parts[0];\n const rest = \"/\" + parts.slice(1).join(\"/\");\n return { locale, url: (rest || \"/\") + query, hadPrefix: true };\n }\n\n return { locale: i18nConfig.defaultLocale, url, hadPrefix: false };\n}\n\n/**\n * Detect the preferred locale from the Accept-Language header.\n * Returns the best matching locale or null.\n */\nexport function detectLocaleFromHeaders(\n req: IncomingMessage,\n i18nConfig: NextI18nConfig,\n): string | null {\n const acceptLang = req.headers[\"accept-language\"];\n if (!acceptLang) return null;\n\n // Parse Accept-Language: en-US,en;q=0.9,fr;q=0.8\n const langs = acceptLang\n .split(\",\")\n .map((part) => {\n const [lang, qPart] = part.trim().split(\";\");\n const q = qPart ? parseFloat(qPart.replace(\"q=\", \"\")) : 1;\n return { lang: lang.trim().toLowerCase(), q };\n })\n .sort((a, b) => b.q - a.q);\n\n for (const { lang } of langs) {\n // Exact match\n const exactMatch = i18nConfig.locales.find((l) => l.toLowerCase() === lang);\n if (exactMatch) return exactMatch;\n\n // Prefix match (e.g. \"en-US\" matches \"en\")\n const prefix = lang.split(\"-\")[0];\n const prefixMatch = i18nConfig.locales.find(\n (l) => l.toLowerCase() === prefix || l.toLowerCase().startsWith(prefix + \"-\"),\n );\n if (prefixMatch) return prefixMatch;\n }\n\n return null;\n}\n\n/**\n * Parse the NEXT_LOCALE cookie from a request.\n * Returns the cookie value if it matches a configured locale, otherwise null.\n */\nexport function parseCookieLocale(\n req: IncomingMessage,\n i18nConfig: NextI18nConfig,\n): string | null {\n const cookieHeader = req.headers.cookie;\n if (!cookieHeader) return null;\n\n // Simple cookie parsing — find NEXT_LOCALE=value\n const match = cookieHeader.match(/(?:^|;\\s*)NEXT_LOCALE=([^;]*)/);\n if (!match) return null;\n\n let value: string;\n try {\n value = decodeURIComponent(match[1].trim());\n } catch {\n return null;\n }\n // Only return if it's a valid configured locale\n if (i18nConfig.locales.includes(value)) return value;\n return null;\n}\n\n/**\n * Create an SSR request handler for the Pages Router.\n *\n * For each request:\n * 1. Match the URL against discovered routes\n * 2. Load the page module via Vite's SSR module loader\n * 3. Call getServerSideProps/getStaticProps if present\n * 4. Render the component to HTML\n * 5. Wrap in _document shell and send response\n */\nexport function createSSRHandler(\n server: ViteDevServer,\n routes: Route[],\n pagesDir: string,\n i18nConfig?: NextI18nConfig | null,\n) {\n return async (\n req: IncomingMessage,\n res: ServerResponse,\n url: string,\n /** Status code override — propagated from middleware rewrite status. */\n statusCode?: number,\n ): Promise<void> => {\n // --- i18n: extract locale from URL prefix ---\n let locale: string | undefined;\n let localeStrippedUrl = url;\n\n if (i18nConfig) {\n const parsed = extractLocaleFromUrl(url, i18nConfig);\n locale = parsed.locale;\n localeStrippedUrl = parsed.url;\n\n // If no locale prefix, check NEXT_LOCALE cookie first, then Accept-Language\n if (!parsed.hadPrefix) {\n const cookieLocale = parseCookieLocale(req, i18nConfig);\n if (cookieLocale && cookieLocale !== i18nConfig.defaultLocale) {\n // NEXT_LOCALE cookie overrides Accept-Language — redirect to cookie locale\n const redirectUrl = `/${cookieLocale}${url === \"/\" ? \"\" : url}`;\n res.writeHead(307, { Location: redirectUrl });\n res.end();\n return;\n }\n // If no cookie or cookie matches default, fall through to Accept-Language detection\n if (!cookieLocale && i18nConfig.localeDetection !== false) {\n const detectedLocale = detectLocaleFromHeaders(req, i18nConfig);\n if (detectedLocale && detectedLocale !== i18nConfig.defaultLocale) {\n const redirectUrl = `/${detectedLocale}${url === \"/\" ? \"\" : url}`;\n res.writeHead(307, { Location: redirectUrl });\n res.end();\n return;\n }\n }\n }\n }\n\n const match = matchRoute(localeStrippedUrl, routes);\n\n if (!match) {\n // No route matched — try to render custom 404 page\n await renderErrorPage(server, req, res, url, pagesDir, 404);\n return;\n }\n\n const { route, params } = match;\n\n // Wrap the entire request in nested AsyncLocalStorage.run() scopes to\n // ensure per-request isolation for all state modules.\n return runWithRouterState(() =>\n runWithHeadState(() =>\n _runWithCacheState(() =>\n runWithPrivateCache(() =>\n runWithFetchCache(async () => {\n try {\n // Set SSR context for the router shim so useRouter() returns\n // the correct URL and params during server-side rendering.\n const routerShim = await server.ssrLoadModule(\"next/router\");\n if (typeof routerShim.setSSRContext === \"function\") {\n routerShim.setSSRContext({\n pathname: localeStrippedUrl.split(\"?\")[0],\n query: { ...params, ...parseQuery(url) },\n asPath: url,\n locale: locale ?? i18nConfig?.defaultLocale,\n locales: i18nConfig?.locales,\n defaultLocale: i18nConfig?.defaultLocale,\n });\n }\n\n // Set globalThis locale info for Link component locale prop support during SSR\n if (i18nConfig) {\n (globalThis as any).__VINEXT_LOCALE__ = locale ?? i18nConfig.defaultLocale;\n (globalThis as any).__VINEXT_LOCALES__ = i18nConfig.locales;\n (globalThis as any).__VINEXT_DEFAULT_LOCALE__ = i18nConfig.defaultLocale;\n }\n\n // Load the page module through Vite's SSR pipeline\n // This gives us HMR and transform support for free\n const pageModule = await server.ssrLoadModule(route.filePath);\n\n // Get the page component (default export)\n const PageComponent = pageModule.default;\n if (!PageComponent) {\n console.error(`[vinext] Page ${route.filePath} has no default export`);\n res.statusCode = 500;\n res.end(\"Page has no default export\");\n return;\n }\n\n // Collect page props via data fetching methods\n let pageProps: Record<string, unknown> = {};\n let isrRevalidateSeconds: number | null = null;\n\n // Handle getStaticPaths for dynamic routes: validate the path\n // and respect fallback: false (return 404 for unlisted paths).\n if (typeof pageModule.getStaticPaths === \"function\" && route.isDynamic) {\n const pathsResult = await pageModule.getStaticPaths({\n locales: i18nConfig?.locales ?? [],\n defaultLocale: i18nConfig?.defaultLocale ?? \"\",\n });\n const fallback = pathsResult?.fallback ?? false;\n\n if (fallback === false) {\n // Only allow paths explicitly listed in getStaticPaths\n const paths: Array<{ params: Record<string, string | string[]> }> =\n pathsResult?.paths ?? [];\n const isValidPath = paths.some((p: { params: Record<string, string | string[]> }) => {\n return Object.entries(p.params).every(([key, val]) => {\n const actual = params[key];\n if (Array.isArray(val)) {\n return Array.isArray(actual) && val.join(\"/\") === actual.join(\"/\");\n }\n return String(val) === String(actual);\n });\n });\n\n if (!isValidPath) {\n await renderErrorPage(server, req, res, url, pagesDir, 404);\n return;\n }\n }\n // fallback: true or \"blocking\" — always SSR on-demand.\n // In dev mode, Next.js does the same (no fallback shell).\n // In production, both modes SSR on-demand with caching.\n // The difference is that fallback:true could serve a shell first,\n // but since we always have data available via SSR, we render fully.\n }\n\n if (typeof pageModule.getServerSideProps === \"function\") {\n const context = {\n params,\n req,\n res,\n query: parseQuery(url),\n resolvedUrl: localeStrippedUrl,\n locale: locale ?? i18nConfig?.defaultLocale,\n locales: i18nConfig?.locales,\n defaultLocale: i18nConfig?.defaultLocale,\n };\n const result = await pageModule.getServerSideProps(context);\n if (result && \"props\" in result) {\n pageProps = result.props;\n }\n if (result && \"redirect\" in result) {\n const { redirect } = result;\n const status = redirect.statusCode ?? (redirect.permanent ? 308 : 307);\n // Sanitize destination to prevent open redirect via protocol-relative URLs.\n // Also normalize backslashes — browsers treat \\ as / in URL contexts.\n let dest = redirect.destination;\n if (!dest.startsWith(\"http://\") && !dest.startsWith(\"https://\")) {\n dest = dest.replace(/^[\\\\/]+/, \"/\");\n }\n res.writeHead(status, {\n Location: dest,\n });\n res.end();\n return;\n }\n if (result && \"notFound\" in result && result.notFound) {\n await renderErrorPage(server, req, res, url, pagesDir, 404);\n return;\n }\n }\n // Collect font preloads early so ISR cached responses can include\n // the Link header (font preloads are module-level state that persists\n // across requests after the font modules are first loaded).\n let earlyFontLinkHeader = \"\";\n try {\n const earlyPreloads: Array<{ href: string; type: string }> = [];\n const fontGoogleEarly = await server.ssrLoadModule(\"next/font/google\");\n if (typeof fontGoogleEarly.getSSRFontPreloads === \"function\") {\n earlyPreloads.push(...fontGoogleEarly.getSSRFontPreloads());\n }\n const fontLocalEarly = await server.ssrLoadModule(\"next/font/local\");\n if (typeof fontLocalEarly.getSSRFontPreloads === \"function\") {\n earlyPreloads.push(...fontLocalEarly.getSSRFontPreloads());\n }\n if (earlyPreloads.length > 0) {\n earlyFontLinkHeader = earlyPreloads\n .map((p) => `<${p.href}>; rel=preload; as=font; type=${p.type}; crossorigin`)\n .join(\", \");\n }\n } catch {\n // Font modules not loaded yet — skip\n }\n\n if (typeof pageModule.getStaticProps === \"function\") {\n // Check ISR cache before calling getStaticProps\n const cacheKey = isrCacheKey(\"pages\", url.split(\"?\")[0]);\n const cached = await isrGet(cacheKey);\n\n if (cached && !cached.isStale && cached.value.value?.kind === \"PAGES\") {\n // Fresh cache hit — serve directly\n const cachedPage = cached.value.value as CachedPagesValue;\n const cachedHtml = cachedPage.html;\n const transformedHtml = await server.transformIndexHtml(url, cachedHtml);\n const revalidateSecs = getRevalidateDuration(cacheKey) ?? 60;\n const hitHeaders: Record<string, string> = {\n \"Content-Type\": \"text/html\",\n \"X-Vinext-Cache\": \"HIT\",\n \"Cache-Control\": `s-maxage=${revalidateSecs}, stale-while-revalidate`,\n };\n if (earlyFontLinkHeader) hitHeaders[\"Link\"] = earlyFontLinkHeader;\n res.writeHead(200, hitHeaders);\n res.end(transformedHtml);\n return;\n }\n\n if (cached && cached.isStale && cached.value.value?.kind === \"PAGES\") {\n // Stale hit — serve stale immediately, trigger background regen\n const cachedPage = cached.value.value as CachedPagesValue;\n const cachedHtml = cachedPage.html;\n const transformedHtml = await server.transformIndexHtml(url, cachedHtml);\n\n // Trigger background regeneration: re-run getStaticProps and\n // update the cache so the next request is a HIT with fresh data.\n triggerBackgroundRegeneration(cacheKey, async () => {\n const freshResult = await pageModule.getStaticProps({ params });\n if (freshResult && \"props\" in freshResult) {\n const revalidate = typeof freshResult.revalidate === \"number\" ? freshResult.revalidate : 0;\n if (revalidate > 0) {\n await isrSet(cacheKey, buildPagesCacheValue(cachedHtml, freshResult.props), revalidate);\n }\n }\n });\n\n const revalidateSecs = getRevalidateDuration(cacheKey) ?? 60;\n const staleHeaders: Record<string, string> = {\n \"Content-Type\": \"text/html\",\n \"X-Vinext-Cache\": \"STALE\",\n \"Cache-Control\": `s-maxage=${revalidateSecs}, stale-while-revalidate`,\n };\n if (earlyFontLinkHeader) staleHeaders[\"Link\"] = earlyFontLinkHeader;\n res.writeHead(200, staleHeaders);\n res.end(transformedHtml);\n return;\n }\n\n // Cache miss — call getStaticProps normally\n const context = {\n params,\n locale: locale ?? i18nConfig?.defaultLocale,\n locales: i18nConfig?.locales,\n defaultLocale: i18nConfig?.defaultLocale,\n };\n const result = await pageModule.getStaticProps(context);\n if (result && \"props\" in result) {\n pageProps = result.props;\n }\n if (result && \"redirect\" in result) {\n const { redirect } = result;\n const status = redirect.statusCode ?? (redirect.permanent ? 308 : 307);\n // Sanitize destination to prevent open redirect via protocol-relative URLs.\n // Also normalize backslashes — browsers treat \\ as / in URL contexts.\n let dest = redirect.destination;\n if (!dest.startsWith(\"http://\") && !dest.startsWith(\"https://\")) {\n dest = dest.replace(/^[\\\\/]+/, \"/\");\n }\n res.writeHead(status, {\n Location: dest,\n });\n res.end();\n return;\n }\n if (result && \"notFound\" in result && result.notFound) {\n await renderErrorPage(server, req, res, url, pagesDir, 404);\n return;\n }\n\n // Extract revalidate period for ISR caching after render\n if (typeof result?.revalidate === \"number\" && result.revalidate > 0) {\n isrRevalidateSeconds = result.revalidate;\n }\n }\n\n // Try to load _app.tsx if it exists\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let AppComponent: any = null;\n const appPath = path.join(pagesDir, \"_app\");\n if (findFileWithExtensions(appPath)) {\n try {\n const appModule = await server.ssrLoadModule(appPath);\n AppComponent = appModule.default ?? null;\n } catch {\n // _app exists but failed to load\n }\n }\n\n // React and ReactDOMServer are imported at the top level as native Node\n // modules. They must NOT go through Vite's SSR module runner because\n // React is CJS and the ESModulesEvaluator doesn't define `module`.\n const createElement = React.createElement;\n let element: React.ReactElement;\n\n if (AppComponent) {\n element = createElement(AppComponent, {\n Component: PageComponent,\n pageProps,\n });\n } else {\n element = createElement(PageComponent, pageProps);\n }\n\n // Reset SSR head collector before rendering so <Head> tags are captured\n const headShim = await server.ssrLoadModule(\"next/head\");\n if (typeof headShim.resetSSRHead === \"function\") {\n headShim.resetSSRHead();\n }\n\n // Flush any pending dynamic() preloads so components are ready\n const dynamicShim = await server.ssrLoadModule(\"next/dynamic\");\n if (typeof dynamicShim.flushPreloads === \"function\") {\n await dynamicShim.flushPreloads();\n }\n\n // Collect any <Head> tags that were rendered during data fetching\n // (shell head tags — Suspense children's head tags arrive late,\n // matching Next.js behavior)\n\n // Collect SSR font links (Google Fonts <link> tags) and font class styles\n let fontHeadHTML = \"\";\n const allFontStyles: string[] = [];\n const allFontPreloads: Array<{ href: string; type: string }> = [];\n try {\n const fontGoogle = await server.ssrLoadModule(\"next/font/google\");\n if (typeof fontGoogle.getSSRFontLinks === \"function\") {\n const fontUrls = fontGoogle.getSSRFontLinks();\n for (const fontUrl of fontUrls) {\n const safeFontUrl = fontUrl.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\");\n fontHeadHTML += `<link rel=\"stylesheet\" href=\"${safeFontUrl}\" />\\n `;\n }\n }\n if (typeof fontGoogle.getSSRFontStyles === \"function\") {\n allFontStyles.push(...fontGoogle.getSSRFontStyles());\n }\n // Collect preloads from self-hosted Google fonts\n if (typeof fontGoogle.getSSRFontPreloads === \"function\") {\n allFontPreloads.push(...fontGoogle.getSSRFontPreloads());\n }\n } catch {\n // next/font/google not used — skip\n }\n try {\n const fontLocal = await server.ssrLoadModule(\"next/font/local\");\n if (typeof fontLocal.getSSRFontStyles === \"function\") {\n allFontStyles.push(...fontLocal.getSSRFontStyles());\n }\n // Collect preloads from local font files\n if (typeof fontLocal.getSSRFontPreloads === \"function\") {\n allFontPreloads.push(...fontLocal.getSSRFontPreloads());\n }\n } catch {\n // next/font/local not used — skip\n }\n // Emit <link rel=\"preload\"> for all collected font files (Google + local)\n for (const { href, type } of allFontPreloads) {\n // Escape href/type to prevent HTML attribute injection (defense-in-depth;\n // Vite-resolved asset paths should never contain special chars).\n const safeHref = href.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\");\n const safeType = type.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\");\n fontHeadHTML += `<link rel=\"preload\" href=\"${safeHref}\" as=\"font\" type=\"${safeType}\" crossorigin />\\n `;\n }\n if (allFontStyles.length > 0) {\n fontHeadHTML += `<style data-vinext-fonts>${allFontStyles.join(\"\\n\")}</style>\\n `;\n }\n\n // Convert absolute file paths to Vite-servable URLs (relative to root)\n const viteRoot = server.config.root;\n const pageModuleUrl = \"/\" + path.relative(viteRoot, route.filePath);\n const appModuleUrl = AppComponent\n ? \"/\" + path.relative(viteRoot, path.join(pagesDir, \"_app\"))\n : null;\n\n // Hydration entry: inline script that imports the page and hydrates.\n // Stores the React root and page loader for client-side navigation.\n const hydrationScript = `\n<script type=\"module\">\nimport React from \"react\";\nimport { hydrateRoot } from \"react-dom/client\";\n\nconst nextData = window.__NEXT_DATA__;\nconst { pageProps } = nextData.props;\n\nasync function hydrate() {\n const pageModule = await import(\"${pageModuleUrl}\");\n const PageComponent = pageModule.default;\n let element;\n ${\n appModuleUrl\n ? `\n const appModule = await import(\"${appModuleUrl}\");\n const AppComponent = appModule.default;\n window.__VINEXT_APP__ = AppComponent;\n element = React.createElement(AppComponent, { Component: PageComponent, pageProps });\n `\n : `\n element = React.createElement(PageComponent, pageProps);\n `\n }\n const root = hydrateRoot(document.getElementById(\"__next\"), element);\n window.__VINEXT_ROOT__ = root;\n}\nhydrate();\n</script>`;\n\n const nextDataScript = `<script>window.__NEXT_DATA__ = ${safeJsonStringify({\n props: { pageProps },\n page: patternToNextFormat(route.pattern),\n query: params,\n isFallback: false,\n locale: locale ?? i18nConfig?.defaultLocale,\n locales: i18nConfig?.locales,\n defaultLocale: i18nConfig?.defaultLocale,\n // Include module URLs so client navigation can import pages directly\n __vinext: {\n pageModuleUrl,\n appModuleUrl,\n },\n })}${i18nConfig ? `;window.__VINEXT_LOCALE__=${safeJsonStringify(locale ?? i18nConfig.defaultLocale)};window.__VINEXT_LOCALES__=${safeJsonStringify(i18nConfig.locales)};window.__VINEXT_DEFAULT_LOCALE__=${safeJsonStringify(i18nConfig.defaultLocale)}` : \"\"}</script>`;\n\n // Try to load custom _document.tsx\n const docPath = path.join(pagesDir, \"_document\");\n let DocumentComponent: any = null;\n if (findFileWithExtensions(docPath)) {\n try {\n const docModule = await server.ssrLoadModule(docPath);\n DocumentComponent = docModule.default ?? null;\n } catch {\n // _document exists but failed to load\n }\n }\n\n const allScripts = `${nextDataScript}\\n ${hydrationScript}`;\n\n // Build cache headers for ISR responses\n const extraHeaders: Record<string, string> = {};\n if (isrRevalidateSeconds) {\n extraHeaders[\"Cache-Control\"] = `s-maxage=${isrRevalidateSeconds}, stale-while-revalidate`;\n extraHeaders[\"X-Vinext-Cache\"] = \"MISS\";\n }\n\n // Set HTTP Link header for font preloading.\n // This lets the browser (and CDN) start fetching font files before parsing HTML.\n if (allFontPreloads.length > 0) {\n extraHeaders[\"Link\"] = allFontPreloads\n .map((p) => `<${p.href}>; rel=preload; as=font; type=${p.type}; crossorigin`)\n .join(\", \");\n }\n\n // Stream the page using progressive SSR.\n // The shell (layouts, non-suspended content) arrives immediately.\n // Suspense content streams in as it resolves.\n await streamPageToResponse(res, element, {\n url,\n server,\n fontHeadHTML,\n scripts: allScripts,\n DocumentComponent,\n statusCode,\n extraHeaders,\n // Collect head HTML AFTER the shell renders (inside streamPageToResponse,\n // after renderToReadableStream resolves). Head tags from Suspense\n // children arrive late — this matches Next.js behavior.\n getHeadHTML: () => typeof headShim.getSSRHeadHTML === \"function\"\n ? headShim.getSSRHeadHTML()\n : \"\",\n });\n\n // Clear SSR context after rendering\n if (typeof routerShim.setSSRContext === \"function\") {\n routerShim.setSSRContext(null);\n }\n\n // If ISR is enabled, we need the full HTML for caching.\n // For ISR, re-render synchronously to get the complete HTML string.\n // This runs after the stream is already sent, so it doesn't affect TTFB.\n if (isrRevalidateSeconds !== null && isrRevalidateSeconds > 0) {\n const isrElement = AppComponent\n ? createElement(AppComponent, { Component: pageModule.default, pageProps })\n : createElement(pageModule.default, pageProps);\n const isrBodyHtml = await renderToStringAsync(isrElement);\n const isrHtml = `<!DOCTYPE html><html><head></head><body><div id=\"__next\">${isrBodyHtml}</div>${allScripts}</body></html>`;\n const cacheKey = isrCacheKey(\"pages\", url.split(\"?\")[0]);\n await isrSet(\n cacheKey,\n buildPagesCacheValue(isrHtml, pageProps),\n isrRevalidateSeconds,\n );\n setRevalidateDuration(cacheKey, isrRevalidateSeconds);\n }\n } catch (e) {\n // Let Vite fix the stack trace for better dev experience\n server.ssrFixStacktrace(e as Error);\n console.error(e);\n // Report error via instrumentation hook if registered\n reportRequestError(\n e instanceof Error ? e : new Error(String(e)),\n {\n path: url,\n method: req.method ?? \"GET\",\n headers: Object.fromEntries(\n Object.entries(req.headers).map(([k, v]) => [k, Array.isArray(v) ? v.join(\", \") : String(v ?? \"\")]),\n ),\n },\n { routerKind: \"Pages Router\", routePath: route.pattern, routeType: \"render\" },\n ).catch(() => { /* ignore reporting errors */ });\n // Try to render custom 500 error page\n try {\n await renderErrorPage(server, req, res, url, pagesDir, 500);\n } catch (fallbackErr) {\n // If error page itself fails, fall back to plain text.\n // This is a dev-only code path (prod uses prod-server.ts), so\n // include the error message for debugging.\n res.statusCode = 500;\n res.end(`Internal Server Error: ${(fallbackErr as Error).message}`);\n }\n } finally {\n // Cleanup is handled by ALS scope unwinding —\n // each runWith*() scope is automatically cleaned up when it exits.\n }\n }) // end runWithFetchCache\n ) // end runWithPrivateCache\n ) // end _runWithCacheState\n ) // end runWithHeadState\n ); // end runWithRouterState\n };\n}\n\n/**\n * Render a custom error page (404.tsx, 500.tsx, or _error.tsx).\n *\n * Next.js resolution order:\n * - 404: pages/404.tsx -> pages/_error.tsx -> default\n * - 500: pages/500.tsx -> pages/_error.tsx -> default\n * - other: pages/_error.tsx -> default\n */\nasync function renderErrorPage(\n server: ViteDevServer,\n _req: IncomingMessage,\n res: ServerResponse,\n url: string,\n pagesDir: string,\n statusCode: number,\n): Promise<void> {\n // Try specific status page first, then _error, then fallback\n const candidates =\n statusCode === 404\n ? [\"404\", \"_error\"]\n : statusCode === 500\n ? [\"500\", \"_error\"]\n : [\"_error\"];\n\n for (const candidate of candidates) {\n try {\n const candidatePath = path.join(pagesDir, candidate);\n if (!findFileWithExtensions(candidatePath)) continue;\n\n const errorModule = await server.ssrLoadModule(candidatePath);\n const ErrorComponent = errorModule.default;\n if (!ErrorComponent) continue;\n\n // Try to load _app.tsx to wrap the error page\n let AppComponent: any = null;\n const appPathErr = path.join(pagesDir, \"_app\");\n if (findFileWithExtensions(appPathErr)) {\n try {\n const appModule = await server.ssrLoadModule(appPathErr);\n AppComponent = appModule.default ?? null;\n } catch {\n // _app exists but failed to load\n }\n }\n\n const createElement = React.createElement;\n const errorProps = { statusCode };\n\n let element: React.ReactElement;\n if (AppComponent) {\n element = createElement(AppComponent, {\n Component: ErrorComponent,\n pageProps: errorProps,\n });\n } else {\n element = createElement(ErrorComponent, errorProps);\n }\n\n const bodyHtml = await renderToStringAsync(element);\n\n // Try custom _document\n let html: string;\n let DocumentComponent: any = null;\n const docPathErr = path.join(pagesDir, \"_document\");\n if (findFileWithExtensions(docPathErr)) {\n try {\n const docModule = await server.ssrLoadModule(docPathErr);\n DocumentComponent = docModule.default ?? null;\n } catch {\n // _document exists but failed to load\n }\n }\n\n if (DocumentComponent) {\n const docElement = createElement(DocumentComponent);\n let docHtml = await renderToStringAsync(docElement);\n docHtml = docHtml.replace(\"__NEXT_MAIN__\", bodyHtml);\n docHtml = docHtml.replace(\"<!-- __NEXT_SCRIPTS__ -->\", \"\");\n html = docHtml;\n } else {\n html = `<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n</head>\n<body>\n <div id=\"__next\">${bodyHtml}</div>\n</body>\n</html>`;\n }\n\n const transformedHtml = await server.transformIndexHtml(url, html);\n res.writeHead(statusCode, { \"Content-Type\": \"text/html\" });\n res.end(transformedHtml);\n return;\n } catch {\n // This candidate doesn't exist, try next\n continue;\n }\n }\n\n // No custom error page found — use plain text fallback\n res.writeHead(statusCode, { \"Content-Type\": \"text/plain\" });\n res.end(`${statusCode} - ${statusCode === 404 ? \"Page not found\" : \"Internal Server Error\"}`);\n}\n\n\n"]}
1
+ {"version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erResponse } from \"node:http\";\nimport type { Route } from \"../routing/pages-router.js\";\nimport { matchRoute, patternToNextFormat } from \"../routing/pages-router.js\";\nimport type { NextI18nConfig } from \"../config/next-config.js\";\nimport {\n isrGet,\n isrSet,\n isrCacheKey,\n buildPagesCacheValue,\n triggerBackgroundRegeneration,\n setRevalidateDuration,\n getRevalidateDuration,\n} from \"./isr-cache.js\";\nimport type { CachedPagesValue } from \"../shims/cache.js\";\nimport { runWithFetchCache } from \"../shims/fetch-cache.js\";\nimport { _runWithCacheState } from \"../shims/cache.js\";\nimport { runWithPrivateCache } from \"../shims/cache-runtime.js\";\n// Import server-only state modules to register ALS-backed accessors.\n// These modules must be imported before any rendering occurs.\nimport { runWithRouterState } from \"../shims/router-state.js\";\nimport { runWithHeadState } from \"../shims/head-state.js\";\nimport { reportRequestError } from \"./instrumentation.js\";\nimport { safeJsonStringify } from \"./html.js\";\nimport { parseQueryString as parseQuery } from \"../utils/query.js\";\nimport path from \"node:path\";\nimport fs from \"node:fs\";\nimport React from \"react\";\nimport { renderToReadableStream } from \"react-dom/server.edge\";\n\nconst PAGE_EXTENSIONS = [\".tsx\", \".ts\", \".jsx\", \".js\"];\n\n/**\n * Render a React element to a string using renderToReadableStream.\n *\n * Uses the edge-compatible Web Streams API. Waits for all Suspense\n * boundaries to resolve via stream.allReady before collecting output.\n * Used for _document rendering and error pages (small, non-streaming).\n */\nasync function renderToStringAsync(element: React.ReactElement): Promise<string> {\n const stream = await renderToReadableStream(element);\n await stream.allReady;\n return new Response(stream).text();\n}\n\n/** Body placeholder used to split the document shell for streaming. */\nconst STREAM_BODY_MARKER = \"<!--VINEXT_STREAM_BODY-->\";\n\n/**\n * Stream a Pages Router page response using progressive SSR.\n *\n * Sends the HTML shell (head, layout, Suspense fallbacks) immediately\n * when the React shell is ready, then streams Suspense content as it\n * resolves. This gives the browser content to render while slow data\n * loads are still in flight.\n *\n * `__NEXT_DATA__` and the hydration script are appended after the body\n * stream completes (the data is known before rendering starts, but\n * deferring them reduces TTFB and lets the browser start parsing the\n * shell sooner).\n */\nasync function streamPageToResponse(\n res: ServerResponse,\n element: React.ReactElement,\n options: {\n url: string;\n server: ViteDevServer;\n fontHeadHTML: string;\n scripts: string;\n DocumentComponent: React.ComponentType | null;\n statusCode?: number;\n extraHeaders?: Record<string, string>;\n /** Called after renderToReadableStream resolves (shell ready) to collect head HTML */\n getHeadHTML: () => string;\n },\n): Promise<void> {\n const {\n url,\n server,\n fontHeadHTML,\n scripts,\n DocumentComponent,\n statusCode = 200,\n extraHeaders,\n getHeadHTML,\n } = options;\n\n // Start the React body stream FIRST — the promise resolves when the\n // shell is ready (synchronous content outside Suspense boundaries).\n // This triggers the render which populates <Head> tags.\n const bodyStream = await renderToReadableStream(element);\n\n // Now that the shell has rendered, collect head HTML\n const headHTML = getHeadHTML();\n\n // Build the document shell with a placeholder for the body\n let shellTemplate: string;\n\n if (DocumentComponent) {\n const docElement = React.createElement(DocumentComponent);\n let docHtml = await renderToStringAsync(docElement);\n // Replace __NEXT_MAIN__ with our stream marker\n docHtml = docHtml.replace(\"__NEXT_MAIN__\", STREAM_BODY_MARKER);\n // Inject head tags\n if (headHTML || fontHeadHTML) {\n docHtml = docHtml.replace(\"</head>\", ` ${fontHeadHTML}${headHTML}\\n</head>`);\n }\n // Inject scripts: replace placeholder or append before </body>\n docHtml = docHtml.replace(\"<!-- __NEXT_SCRIPTS__ -->\", scripts);\n if (!docHtml.includes(\"__NEXT_DATA__\")) {\n docHtml = docHtml.replace(\"</body>\", ` ${scripts}\\n</body>`);\n }\n shellTemplate = docHtml;\n } else {\n shellTemplate = `<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n ${fontHeadHTML}${headHTML}\n</head>\n<body>\n <div id=\"__next\">${STREAM_BODY_MARKER}</div>\n ${scripts}\n</body>\n</html>`;\n }\n\n // Apply Vite's HTML transforms (injects HMR client, etc.) on the full\n // shell template, then split at the body marker.\n const transformedShell = await server.transformIndexHtml(url, shellTemplate);\n const markerIdx = transformedShell.indexOf(STREAM_BODY_MARKER);\n const prefix = transformedShell.slice(0, markerIdx);\n const suffix = transformedShell.slice(markerIdx + STREAM_BODY_MARKER.length);\n\n // Send headers and start streaming\n const headers: Record<string, string> = {\n \"Content-Type\": \"text/html\",\n \"Transfer-Encoding\": \"chunked\",\n ...extraHeaders,\n };\n res.writeHead(statusCode, headers);\n\n // Write the document prefix (head, opening body)\n res.write(prefix);\n\n // Pipe the React body stream through (Suspense content streams progressively)\n const reader = bodyStream.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n res.write(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n // Write the document suffix (closing tags, scripts)\n res.end(suffix);\n}\n\n/** Check if a file exists with any page extension (tsx, ts, jsx, js). */\nfunction findFileWithExtensions(basePath: string): boolean {\n return PAGE_EXTENSIONS.some((ext) => fs.existsSync(basePath + ext));\n}\n\n/**\n * Extract locale prefix from a URL path.\n * e.g. /fr/about -> { locale: \"fr\", url: \"/about\", hadPrefix: true }\n * /about -> { locale: \"en\", url: \"/about\", hadPrefix: false } (defaultLocale)\n */\nexport function extractLocaleFromUrl(\n url: string,\n i18nConfig: NextI18nConfig,\n): { locale: string; url: string; hadPrefix: boolean } {\n const pathname = url.split(\"?\")[0];\n const parts = pathname.split(\"/\").filter(Boolean);\n const query = url.includes(\"?\") ? url.slice(url.indexOf(\"?\")) : \"\";\n\n if (parts.length > 0 && i18nConfig.locales.includes(parts[0])) {\n const locale = parts[0];\n const rest = \"/\" + parts.slice(1).join(\"/\");\n return { locale, url: (rest || \"/\") + query, hadPrefix: true };\n }\n\n return { locale: i18nConfig.defaultLocale, url, hadPrefix: false };\n}\n\n/**\n * Detect the preferred locale from the Accept-Language header.\n * Returns the best matching locale or null.\n */\nexport function detectLocaleFromHeaders(\n req: IncomingMessage,\n i18nConfig: NextI18nConfig,\n): string | null {\n const acceptLang = req.headers[\"accept-language\"];\n if (!acceptLang) return null;\n\n // Parse Accept-Language: en-US,en;q=0.9,fr;q=0.8\n const langs = acceptLang\n .split(\",\")\n .map((part) => {\n const [lang, qPart] = part.trim().split(\";\");\n const q = qPart ? parseFloat(qPart.replace(\"q=\", \"\")) : 1;\n return { lang: lang.trim().toLowerCase(), q };\n })\n .sort((a, b) => b.q - a.q);\n\n for (const { lang } of langs) {\n // Exact match\n const exactMatch = i18nConfig.locales.find((l) => l.toLowerCase() === lang);\n if (exactMatch) return exactMatch;\n\n // Prefix match (e.g. \"en-US\" matches \"en\")\n const prefix = lang.split(\"-\")[0];\n const prefixMatch = i18nConfig.locales.find(\n (l) => l.toLowerCase() === prefix || l.toLowerCase().startsWith(prefix + \"-\"),\n );\n if (prefixMatch) return prefixMatch;\n }\n\n return null;\n}\n\n/**\n * Parse the NEXT_LOCALE cookie from a request.\n * Returns the cookie value if it matches a configured locale, otherwise null.\n */\nexport function parseCookieLocale(\n req: IncomingMessage,\n i18nConfig: NextI18nConfig,\n): string | null {\n const cookieHeader = req.headers.cookie;\n if (!cookieHeader) return null;\n\n // Simple cookie parsing — find NEXT_LOCALE=value\n const match = cookieHeader.match(/(?:^|;\\s*)NEXT_LOCALE=([^;]*)/);\n if (!match) return null;\n\n let value: string;\n try {\n value = decodeURIComponent(match[1].trim());\n } catch {\n return null;\n }\n // Only return if it's a valid configured locale\n if (i18nConfig.locales.includes(value)) return value;\n return null;\n}\n\n/**\n * Create an SSR request handler for the Pages Router.\n *\n * For each request:\n * 1. Match the URL against discovered routes\n * 2. Load the page module via Vite's SSR module loader\n * 3. Call getServerSideProps/getStaticProps if present\n * 4. Render the component to HTML\n * 5. Wrap in _document shell and send response\n */\nexport function createSSRHandler(\n server: ViteDevServer,\n routes: Route[],\n pagesDir: string,\n i18nConfig?: NextI18nConfig | null,\n) {\n return async (\n req: IncomingMessage,\n res: ServerResponse,\n url: string,\n /** Status code override — propagated from middleware rewrite status. */\n statusCode?: number,\n ): Promise<void> => {\n // --- i18n: extract locale from URL prefix ---\n let locale: string | undefined;\n let localeStrippedUrl = url;\n\n if (i18nConfig) {\n const parsed = extractLocaleFromUrl(url, i18nConfig);\n locale = parsed.locale;\n localeStrippedUrl = parsed.url;\n\n // If no locale prefix, check NEXT_LOCALE cookie first, then Accept-Language\n if (!parsed.hadPrefix) {\n const cookieLocale = parseCookieLocale(req, i18nConfig);\n if (cookieLocale && cookieLocale !== i18nConfig.defaultLocale) {\n // NEXT_LOCALE cookie overrides Accept-Language — redirect to cookie locale\n const redirectUrl = `/${cookieLocale}${url === \"/\" ? \"\" : url}`;\n res.writeHead(307, { Location: redirectUrl });\n res.end();\n return;\n }\n // If no cookie or cookie matches default, fall through to Accept-Language detection\n if (!cookieLocale && i18nConfig.localeDetection !== false) {\n const detectedLocale = detectLocaleFromHeaders(req, i18nConfig);\n if (detectedLocale && detectedLocale !== i18nConfig.defaultLocale) {\n const redirectUrl = `/${detectedLocale}${url === \"/\" ? \"\" : url}`;\n res.writeHead(307, { Location: redirectUrl });\n res.end();\n return;\n }\n }\n }\n }\n\n const match = matchRoute(localeStrippedUrl, routes);\n\n if (!match) {\n // No route matched — try to render custom 404 page\n await renderErrorPage(server, req, res, url, pagesDir, 404);\n return;\n }\n\n const { route, params } = match;\n\n // Wrap the entire request in nested AsyncLocalStorage.run() scopes to\n // ensure per-request isolation for all state modules.\n return runWithRouterState(() =>\n runWithHeadState(() =>\n _runWithCacheState(() =>\n runWithPrivateCache(() =>\n runWithFetchCache(async () => {\n try {\n // Set SSR context for the router shim so useRouter() returns\n // the correct URL and params during server-side rendering.\n const routerShim = await server.ssrLoadModule(\"next/router\");\n if (typeof routerShim.setSSRContext === \"function\") {\n routerShim.setSSRContext({\n pathname: localeStrippedUrl.split(\"?\")[0],\n query: { ...params, ...parseQuery(url) },\n asPath: url,\n locale: locale ?? i18nConfig?.defaultLocale,\n locales: i18nConfig?.locales,\n defaultLocale: i18nConfig?.defaultLocale,\n });\n }\n\n // Set globalThis locale info for Link component locale prop support during SSR\n if (i18nConfig) {\n (globalThis as any).__VINEXT_LOCALE__ = locale ?? i18nConfig.defaultLocale;\n (globalThis as any).__VINEXT_LOCALES__ = i18nConfig.locales;\n (globalThis as any).__VINEXT_DEFAULT_LOCALE__ = i18nConfig.defaultLocale;\n }\n\n // Load the page module through Vite's SSR pipeline\n // This gives us HMR and transform support for free\n const pageModule = await server.ssrLoadModule(route.filePath);\n\n // Get the page component (default export)\n const PageComponent = pageModule.default;\n if (!PageComponent) {\n console.error(`[vinext] Page ${route.filePath} has no default export`);\n res.statusCode = 500;\n res.end(\"Page has no default export\");\n return;\n }\n\n // Collect page props via data fetching methods\n let pageProps: Record<string, unknown> = {};\n let isrRevalidateSeconds: number | null = null;\n\n // Handle getStaticPaths for dynamic routes: validate the path\n // and respect fallback: false (return 404 for unlisted paths).\n if (typeof pageModule.getStaticPaths === \"function\" && route.isDynamic) {\n const pathsResult = await pageModule.getStaticPaths({\n locales: i18nConfig?.locales ?? [],\n defaultLocale: i18nConfig?.defaultLocale ?? \"\",\n });\n const fallback = pathsResult?.fallback ?? false;\n\n if (fallback === false) {\n // Only allow paths explicitly listed in getStaticPaths\n const paths: Array<{ params: Record<string, string | string[]> }> =\n pathsResult?.paths ?? [];\n const isValidPath = paths.some((p: { params: Record<string, string | string[]> }) => {\n return Object.entries(p.params).every(([key, val]) => {\n const actual = params[key];\n if (Array.isArray(val)) {\n return Array.isArray(actual) && val.join(\"/\") === actual.join(\"/\");\n }\n return String(val) === String(actual);\n });\n });\n\n if (!isValidPath) {\n await renderErrorPage(server, req, res, url, pagesDir, 404, routerShim.wrapWithRouterContext);\n return;\n }\n }\n // fallback: true or \"blocking\" — always SSR on-demand.\n // In dev mode, Next.js does the same (no fallback shell).\n // In production, both modes SSR on-demand with caching.\n // The difference is that fallback:true could serve a shell first,\n // but since we always have data available via SSR, we render fully.\n }\n\n if (typeof pageModule.getServerSideProps === \"function\") {\n const context = {\n params,\n req,\n res,\n query: parseQuery(url),\n resolvedUrl: localeStrippedUrl,\n locale: locale ?? i18nConfig?.defaultLocale,\n locales: i18nConfig?.locales,\n defaultLocale: i18nConfig?.defaultLocale,\n };\n const result = await pageModule.getServerSideProps(context);\n if (result && \"props\" in result) {\n pageProps = result.props;\n }\n if (result && \"redirect\" in result) {\n const { redirect } = result;\n const status = redirect.statusCode ?? (redirect.permanent ? 308 : 307);\n // Sanitize destination to prevent open redirect via protocol-relative URLs.\n // Also normalize backslashes — browsers treat \\ as / in URL contexts.\n let dest = redirect.destination;\n if (!dest.startsWith(\"http://\") && !dest.startsWith(\"https://\")) {\n dest = dest.replace(/^[\\\\/]+/, \"/\");\n }\n res.writeHead(status, {\n Location: dest,\n });\n res.end();\n return;\n }\n if (result && \"notFound\" in result && result.notFound) {\n await renderErrorPage(server, req, res, url, pagesDir, 404, routerShim.wrapWithRouterContext);\n return;\n }\n }\n // Collect font preloads early so ISR cached responses can include\n // the Link header (font preloads are module-level state that persists\n // across requests after the font modules are first loaded).\n let earlyFontLinkHeader = \"\";\n try {\n const earlyPreloads: Array<{ href: string; type: string }> = [];\n const fontGoogleEarly = await server.ssrLoadModule(\"next/font/google\");\n if (typeof fontGoogleEarly.getSSRFontPreloads === \"function\") {\n earlyPreloads.push(...fontGoogleEarly.getSSRFontPreloads());\n }\n const fontLocalEarly = await server.ssrLoadModule(\"next/font/local\");\n if (typeof fontLocalEarly.getSSRFontPreloads === \"function\") {\n earlyPreloads.push(...fontLocalEarly.getSSRFontPreloads());\n }\n if (earlyPreloads.length > 0) {\n earlyFontLinkHeader = earlyPreloads\n .map((p) => `<${p.href}>; rel=preload; as=font; type=${p.type}; crossorigin`)\n .join(\", \");\n }\n } catch {\n // Font modules not loaded yet — skip\n }\n\n if (typeof pageModule.getStaticProps === \"function\") {\n // Check ISR cache before calling getStaticProps\n const cacheKey = isrCacheKey(\"pages\", url.split(\"?\")[0]);\n const cached = await isrGet(cacheKey);\n\n if (cached && !cached.isStale && cached.value.value?.kind === \"PAGES\") {\n // Fresh cache hit — serve directly\n const cachedPage = cached.value.value as CachedPagesValue;\n const cachedHtml = cachedPage.html;\n const transformedHtml = await server.transformIndexHtml(url, cachedHtml);\n const revalidateSecs = getRevalidateDuration(cacheKey) ?? 60;\n const hitHeaders: Record<string, string> = {\n \"Content-Type\": \"text/html\",\n \"X-Vinext-Cache\": \"HIT\",\n \"Cache-Control\": `s-maxage=${revalidateSecs}, stale-while-revalidate`,\n };\n if (earlyFontLinkHeader) hitHeaders[\"Link\"] = earlyFontLinkHeader;\n res.writeHead(200, hitHeaders);\n res.end(transformedHtml);\n return;\n }\n\n if (cached && cached.isStale && cached.value.value?.kind === \"PAGES\") {\n // Stale hit — serve stale immediately, trigger background regen\n const cachedPage = cached.value.value as CachedPagesValue;\n const cachedHtml = cachedPage.html;\n const transformedHtml = await server.transformIndexHtml(url, cachedHtml);\n\n // Trigger background regeneration: re-run getStaticProps and\n // update the cache so the next request is a HIT with fresh data.\n triggerBackgroundRegeneration(cacheKey, async () => {\n const freshResult = await pageModule.getStaticProps({ params });\n if (freshResult && \"props\" in freshResult) {\n const revalidate = typeof freshResult.revalidate === \"number\" ? freshResult.revalidate : 0;\n if (revalidate > 0) {\n await isrSet(cacheKey, buildPagesCacheValue(cachedHtml, freshResult.props), revalidate);\n }\n }\n });\n\n const revalidateSecs = getRevalidateDuration(cacheKey) ?? 60;\n const staleHeaders: Record<string, string> = {\n \"Content-Type\": \"text/html\",\n \"X-Vinext-Cache\": \"STALE\",\n \"Cache-Control\": `s-maxage=${revalidateSecs}, stale-while-revalidate`,\n };\n if (earlyFontLinkHeader) staleHeaders[\"Link\"] = earlyFontLinkHeader;\n res.writeHead(200, staleHeaders);\n res.end(transformedHtml);\n return;\n }\n\n // Cache miss — call getStaticProps normally\n const context = {\n params,\n locale: locale ?? i18nConfig?.defaultLocale,\n locales: i18nConfig?.locales,\n defaultLocale: i18nConfig?.defaultLocale,\n };\n const result = await pageModule.getStaticProps(context);\n if (result && \"props\" in result) {\n pageProps = result.props;\n }\n if (result && \"redirect\" in result) {\n const { redirect } = result;\n const status = redirect.statusCode ?? (redirect.permanent ? 308 : 307);\n // Sanitize destination to prevent open redirect via protocol-relative URLs.\n // Also normalize backslashes — browsers treat \\ as / in URL contexts.\n let dest = redirect.destination;\n if (!dest.startsWith(\"http://\") && !dest.startsWith(\"https://\")) {\n dest = dest.replace(/^[\\\\/]+/, \"/\");\n }\n res.writeHead(status, {\n Location: dest,\n });\n res.end();\n return;\n }\n if (result && \"notFound\" in result && result.notFound) {\n await renderErrorPage(server, req, res, url, pagesDir, 404, routerShim.wrapWithRouterContext);\n return;\n }\n\n // Extract revalidate period for ISR caching after render\n if (typeof result?.revalidate === \"number\" && result.revalidate > 0) {\n isrRevalidateSeconds = result.revalidate;\n }\n }\n\n // Try to load _app.tsx if it exists\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let AppComponent: any = null;\n const appPath = path.join(pagesDir, \"_app\");\n if (findFileWithExtensions(appPath)) {\n try {\n const appModule = await server.ssrLoadModule(appPath);\n AppComponent = appModule.default ?? null;\n } catch {\n // _app exists but failed to load\n }\n }\n\n // React and ReactDOMServer are imported at the top level as native Node\n // modules. They must NOT go through Vite's SSR module runner because\n // React is CJS and the ESModulesEvaluator doesn't define `module`.\n const createElement = React.createElement;\n let element: React.ReactElement;\n\n // wrapWithRouterContext wraps the element in RouterContext.Provider so that\n // next/compat/router's useRouter() returns the real router.\n const wrapWithRouterContext = routerShim.wrapWithRouterContext;\n\n if (AppComponent) {\n element = createElement(AppComponent, {\n Component: PageComponent,\n pageProps,\n });\n } else {\n element = createElement(PageComponent, pageProps);\n }\n\n if (wrapWithRouterContext) {\n element = wrapWithRouterContext(element);\n }\n\n // Reset SSR head collector before rendering so <Head> tags are captured\n const headShim = await server.ssrLoadModule(\"next/head\");\n if (typeof headShim.resetSSRHead === \"function\") {\n headShim.resetSSRHead();\n }\n\n // Flush any pending dynamic() preloads so components are ready\n const dynamicShim = await server.ssrLoadModule(\"next/dynamic\");\n if (typeof dynamicShim.flushPreloads === \"function\") {\n await dynamicShim.flushPreloads();\n }\n\n // Collect any <Head> tags that were rendered during data fetching\n // (shell head tags — Suspense children's head tags arrive late,\n // matching Next.js behavior)\n\n // Collect SSR font links (Google Fonts <link> tags) and font class styles\n let fontHeadHTML = \"\";\n const allFontStyles: string[] = [];\n const allFontPreloads: Array<{ href: string; type: string }> = [];\n try {\n const fontGoogle = await server.ssrLoadModule(\"next/font/google\");\n if (typeof fontGoogle.getSSRFontLinks === \"function\") {\n const fontUrls = fontGoogle.getSSRFontLinks();\n for (const fontUrl of fontUrls) {\n const safeFontUrl = fontUrl.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\");\n fontHeadHTML += `<link rel=\"stylesheet\" href=\"${safeFontUrl}\" />\\n `;\n }\n }\n if (typeof fontGoogle.getSSRFontStyles === \"function\") {\n allFontStyles.push(...fontGoogle.getSSRFontStyles());\n }\n // Collect preloads from self-hosted Google fonts\n if (typeof fontGoogle.getSSRFontPreloads === \"function\") {\n allFontPreloads.push(...fontGoogle.getSSRFontPreloads());\n }\n } catch {\n // next/font/google not used — skip\n }\n try {\n const fontLocal = await server.ssrLoadModule(\"next/font/local\");\n if (typeof fontLocal.getSSRFontStyles === \"function\") {\n allFontStyles.push(...fontLocal.getSSRFontStyles());\n }\n // Collect preloads from local font files\n if (typeof fontLocal.getSSRFontPreloads === \"function\") {\n allFontPreloads.push(...fontLocal.getSSRFontPreloads());\n }\n } catch {\n // next/font/local not used — skip\n }\n // Emit <link rel=\"preload\"> for all collected font files (Google + local)\n for (const { href, type } of allFontPreloads) {\n // Escape href/type to prevent HTML attribute injection (defense-in-depth;\n // Vite-resolved asset paths should never contain special chars).\n const safeHref = href.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\");\n const safeType = type.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\");\n fontHeadHTML += `<link rel=\"preload\" href=\"${safeHref}\" as=\"font\" type=\"${safeType}\" crossorigin />\\n `;\n }\n if (allFontStyles.length > 0) {\n fontHeadHTML += `<style data-vinext-fonts>${allFontStyles.join(\"\\n\")}</style>\\n `;\n }\n\n // Convert absolute file paths to Vite-servable URLs (relative to root)\n const viteRoot = server.config.root;\n const pageModuleUrl = \"/\" + path.relative(viteRoot, route.filePath);\n const appModuleUrl = AppComponent\n ? \"/\" + path.relative(viteRoot, path.join(pagesDir, \"_app\"))\n : null;\n\n // Hydration entry: inline script that imports the page and hydrates.\n // Stores the React root and page loader for client-side navigation.\n const hydrationScript = `\n<script type=\"module\">\nimport React from \"react\";\nimport { hydrateRoot } from \"react-dom/client\";\nimport { wrapWithRouterContext } from \"next/router\";\n\nconst nextData = window.__NEXT_DATA__;\nconst { pageProps } = nextData.props;\n\nasync function hydrate() {\n const pageModule = await import(\"${pageModuleUrl}\");\n const PageComponent = pageModule.default;\n let element;\n ${\n appModuleUrl\n ? `\n const appModule = await import(\"${appModuleUrl}\");\n const AppComponent = appModule.default;\n window.__VINEXT_APP__ = AppComponent;\n element = React.createElement(AppComponent, { Component: PageComponent, pageProps });\n `\n : `\n element = React.createElement(PageComponent, pageProps);\n `\n }\n element = wrapWithRouterContext(element);\n const root = hydrateRoot(document.getElementById(\"__next\"), element);\n window.__VINEXT_ROOT__ = root;\n}\nhydrate();\n</script>`;\n\n const nextDataScript = `<script>window.__NEXT_DATA__ = ${safeJsonStringify({\n props: { pageProps },\n page: patternToNextFormat(route.pattern),\n query: params,\n isFallback: false,\n locale: locale ?? i18nConfig?.defaultLocale,\n locales: i18nConfig?.locales,\n defaultLocale: i18nConfig?.defaultLocale,\n // Include module URLs so client navigation can import pages directly\n __vinext: {\n pageModuleUrl,\n appModuleUrl,\n },\n })}${i18nConfig ? `;window.__VINEXT_LOCALE__=${safeJsonStringify(locale ?? i18nConfig.defaultLocale)};window.__VINEXT_LOCALES__=${safeJsonStringify(i18nConfig.locales)};window.__VINEXT_DEFAULT_LOCALE__=${safeJsonStringify(i18nConfig.defaultLocale)}` : \"\"}</script>`;\n\n // Try to load custom _document.tsx\n const docPath = path.join(pagesDir, \"_document\");\n let DocumentComponent: any = null;\n if (findFileWithExtensions(docPath)) {\n try {\n const docModule = await server.ssrLoadModule(docPath);\n DocumentComponent = docModule.default ?? null;\n } catch {\n // _document exists but failed to load\n }\n }\n\n const allScripts = `${nextDataScript}\\n ${hydrationScript}`;\n\n // Build cache headers for ISR responses\n const extraHeaders: Record<string, string> = {};\n if (isrRevalidateSeconds) {\n extraHeaders[\"Cache-Control\"] = `s-maxage=${isrRevalidateSeconds}, stale-while-revalidate`;\n extraHeaders[\"X-Vinext-Cache\"] = \"MISS\";\n }\n\n // Set HTTP Link header for font preloading.\n // This lets the browser (and CDN) start fetching font files before parsing HTML.\n if (allFontPreloads.length > 0) {\n extraHeaders[\"Link\"] = allFontPreloads\n .map((p) => `<${p.href}>; rel=preload; as=font; type=${p.type}; crossorigin`)\n .join(\", \");\n }\n\n // Stream the page using progressive SSR.\n // The shell (layouts, non-suspended content) arrives immediately.\n // Suspense content streams in as it resolves.\n await streamPageToResponse(res, element, {\n url,\n server,\n fontHeadHTML,\n scripts: allScripts,\n DocumentComponent,\n statusCode,\n extraHeaders,\n // Collect head HTML AFTER the shell renders (inside streamPageToResponse,\n // after renderToReadableStream resolves). Head tags from Suspense\n // children arrive late — this matches Next.js behavior.\n getHeadHTML: () => typeof headShim.getSSRHeadHTML === \"function\"\n ? headShim.getSSRHeadHTML()\n : \"\",\n });\n\n // Clear SSR context after rendering\n if (typeof routerShim.setSSRContext === \"function\") {\n routerShim.setSSRContext(null);\n }\n\n // If ISR is enabled, we need the full HTML for caching.\n // For ISR, re-render synchronously to get the complete HTML string.\n // This runs after the stream is already sent, so it doesn't affect TTFB.\n if (isrRevalidateSeconds !== null && isrRevalidateSeconds > 0) {\n let isrElement = AppComponent\n ? createElement(AppComponent, { Component: pageModule.default, pageProps })\n : createElement(pageModule.default, pageProps);\n if (wrapWithRouterContext) {\n isrElement = wrapWithRouterContext(isrElement);\n }\n const isrBodyHtml = await renderToStringAsync(isrElement);\n const isrHtml = `<!DOCTYPE html><html><head></head><body><div id=\"__next\">${isrBodyHtml}</div>${allScripts}</body></html>`;\n const cacheKey = isrCacheKey(\"pages\", url.split(\"?\")[0]);\n await isrSet(\n cacheKey,\n buildPagesCacheValue(isrHtml, pageProps),\n isrRevalidateSeconds,\n );\n setRevalidateDuration(cacheKey, isrRevalidateSeconds);\n }\n } catch (e) {\n // Let Vite fix the stack trace for better dev experience\n server.ssrFixStacktrace(e as Error);\n console.error(e);\n // Report error via instrumentation hook if registered\n reportRequestError(\n e instanceof Error ? e : new Error(String(e)),\n {\n path: url,\n method: req.method ?? \"GET\",\n headers: Object.fromEntries(\n Object.entries(req.headers).map(([k, v]) => [k, Array.isArray(v) ? v.join(\", \") : String(v ?? \"\")]),\n ),\n },\n { routerKind: \"Pages Router\", routePath: route.pattern, routeType: \"render\" },\n ).catch(() => { /* ignore reporting errors */ });\n // Try to render custom 500 error page\n try {\n await renderErrorPage(server, req, res, url, pagesDir, 500);\n } catch (fallbackErr) {\n // If error page itself fails, fall back to plain text.\n // This is a dev-only code path (prod uses prod-server.ts), so\n // include the error message for debugging.\n res.statusCode = 500;\n res.end(`Internal Server Error: ${(fallbackErr as Error).message}`);\n }\n } finally {\n // Cleanup is handled by ALS scope unwinding —\n // each runWith*() scope is automatically cleaned up when it exits.\n }\n }) // end runWithFetchCache\n ) // end runWithPrivateCache\n ) // end _runWithCacheState\n ) // end runWithHeadState\n ); // end runWithRouterState\n };\n}\n\n/**\n * Render a custom error page (404.tsx, 500.tsx, or _error.tsx).\n *\n * Next.js resolution order:\n * - 404: pages/404.tsx -> pages/_error.tsx -> default\n * - 500: pages/500.tsx -> pages/_error.tsx -> default\n * - other: pages/_error.tsx -> default\n */\nasync function renderErrorPage(\n server: ViteDevServer,\n _req: IncomingMessage,\n res: ServerResponse,\n url: string,\n pagesDir: string,\n statusCode: number,\n wrapWithRouterContext?: ((el: React.ReactElement) => React.ReactElement) | null,\n): Promise<void> {\n // Try specific status page first, then _error, then fallback\n const candidates =\n statusCode === 404\n ? [\"404\", \"_error\"]\n : statusCode === 500\n ? [\"500\", \"_error\"]\n : [\"_error\"];\n\n for (const candidate of candidates) {\n try {\n const candidatePath = path.join(pagesDir, candidate);\n if (!findFileWithExtensions(candidatePath)) continue;\n\n const errorModule = await server.ssrLoadModule(candidatePath);\n const ErrorComponent = errorModule.default;\n if (!ErrorComponent) continue;\n\n // Try to load _app.tsx to wrap the error page\n let AppComponent: any = null;\n const appPathErr = path.join(pagesDir, \"_app\");\n if (findFileWithExtensions(appPathErr)) {\n try {\n const appModule = await server.ssrLoadModule(appPathErr);\n AppComponent = appModule.default ?? null;\n } catch {\n // _app exists but failed to load\n }\n }\n\n const createElement = React.createElement;\n const errorProps = { statusCode };\n\n // If the caller didn't supply wrapWithRouterContext, load it now.\n // ssrLoadModule caches internally so the cost is negligible.\n let wrapFn = wrapWithRouterContext;\n if (!wrapFn) {\n try {\n const errRouterShim = await server.ssrLoadModule(\"next/router\");\n wrapFn = errRouterShim.wrapWithRouterContext;\n } catch {\n // router shim not available — continue without it\n }\n }\n\n let element: React.ReactElement;\n if (AppComponent) {\n element = createElement(AppComponent, {\n Component: ErrorComponent,\n pageProps: errorProps,\n });\n } else {\n element = createElement(ErrorComponent, errorProps);\n }\n\n if (wrapFn) {\n element = wrapFn(element);\n }\n\n const bodyHtml = await renderToStringAsync(element);\n\n // Try custom _document\n let html: string;\n let DocumentComponent: any = null;\n const docPathErr = path.join(pagesDir, \"_document\");\n if (findFileWithExtensions(docPathErr)) {\n try {\n const docModule = await server.ssrLoadModule(docPathErr);\n DocumentComponent = docModule.default ?? null;\n } catch {\n // _document exists but failed to load\n }\n }\n\n if (DocumentComponent) {\n const docElement = createElement(DocumentComponent);\n let docHtml = await renderToStringAsync(docElement);\n docHtml = docHtml.replace(\"__NEXT_MAIN__\", bodyHtml);\n docHtml = docHtml.replace(\"<!-- __NEXT_SCRIPTS__ -->\", \"\");\n html = docHtml;\n } else {\n html = `<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n</head>\n<body>\n <div id=\"__next\">${bodyHtml}</div>\n</body>\n</html>`;\n }\n\n const transformedHtml = await server.transformIndexHtml(url, html);\n res.writeHead(statusCode, { \"Content-Type\": \"text/html\" });\n res.end(transformedHtml);\n return;\n } catch {\n // This candidate doesn't exist, try next\n continue;\n }\n }\n\n // No custom error page found — use plain text fallback\n res.writeHead(statusCode, { \"Content-Type\": \"text/plain\" });\n res.end(`${statusCode} - ${statusCode === 404 ? \"Page not found\" : \"Internal Server Error\"}`);\n}\n\n\n"]}
@@ -13,9 +13,23 @@
13
13
  * Security: All image responses include Content-Security-Policy and
14
14
  * X-Content-Type-Options headers to prevent XSS via SVG or Content-Type
15
15
  * spoofing. SVG content is blocked by default (following Next.js behavior).
16
+ * When `dangerouslyAllowSVG` is enabled in next.config.js, SVGs are served
17
+ * as-is (no transformation) with security headers applied.
16
18
  */
17
19
  /** The pathname that triggers image optimization. */
18
20
  export declare const IMAGE_OPTIMIZATION_PATH = "/_vinext/image";
21
+ /**
22
+ * Image security configuration from next.config.js `images` section.
23
+ * Controls SVG handling and security headers for the image endpoint.
24
+ */
25
+ export interface ImageConfig {
26
+ /** Allow SVG through the image optimization endpoint. Default: false. */
27
+ dangerouslyAllowSVG?: boolean;
28
+ /** Content-Disposition header value. Default: "inline". */
29
+ contentDispositionType?: "inline" | "attachment";
30
+ /** Content-Security-Policy header value. Default: "script-src 'none'; frame-src 'none'; sandbox;" */
31
+ contentSecurityPolicy?: string;
32
+ }
19
33
  /**
20
34
  * Next.js default device sizes and image sizes.
21
35
  * These are the allowed widths for image optimization when no custom
@@ -58,9 +72,9 @@ export declare const IMAGE_CACHE_CONTROL = "public, max-age=31536000, immutable"
58
72
  export declare const IMAGE_CONTENT_SECURITY_POLICY = "script-src 'none'; frame-src 'none'; sandbox;";
59
73
  /**
60
74
  * Check if a Content-Type header value is a safe image type.
61
- * Returns false for SVG, HTML, or any non-image type.
75
+ * Returns false for SVG (unless dangerouslyAllowSVG is true), HTML, or any non-image type.
62
76
  */
63
- export declare function isSafeImageContentType(contentType: string | null): boolean;
77
+ export declare function isSafeImageContentType(contentType: string | null, dangerouslyAllowSVG?: boolean): boolean;
64
78
  /**
65
79
  * Handlers for image optimization I/O operations.
66
80
  * Workers provide these callbacks to adapt their specific bindings.
@@ -82,5 +96,5 @@ export interface ImageHandlers {
82
96
  * handlers, optionally transforms it, and returns the response with appropriate
83
97
  * cache headers.
84
98
  */
85
- export declare function handleImageOptimization(request: Request, handlers: ImageHandlers, allowedWidths?: number[]): Promise<Response>;
99
+ export declare function handleImageOptimization(request: Request, handlers: ImageHandlers, allowedWidths?: number[], imageConfig?: ImageConfig): Promise<Response>;
86
100
  //# sourceMappingURL=image-optimization.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"image-optimization.d.ts","sourceRoot":"","sources":["../../src/server/image-optimization.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,qDAAqD;AACrD,eAAO,MAAM,uBAAuB,mBAAmB,CAAC;AAExD;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,UAAgD,CAAC;AAClF,eAAO,MAAM,mBAAmB,UAAsC,CAAC;AASvE;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAC9B,GAAG,EAAE,GAAG,EACR,aAAa,CAAC,EAAE,MAAM,EAAE,GACvB;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAqC7D;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAKxE;AAED;;;GAGG;AACH,eAAO,MAAM,mBAAmB,wCAAwC,CAAC;AAEzE;;;;;GAKG;AACH,eAAO,MAAM,6BAA6B,kDAAkD,CAAC;A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QAAQ,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAqC7D;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAKxE;AAED;;;GAGG;AACH,eAAO,MAAM,mBAAmB,wCAAwC,CAAC;AAEzE;;;;;GAKG;AACH,eAAO,MAAM,6BAA6B,kDAAkD,CAAC;AAmB7F;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,EAAE,mBAAmB,UAAQ,GAAG,OAAO,CAOvG;AAcD;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC5B,6EAA6E;IAC7E,UAAU,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;IAClE,+DAA+D;IAC/D,cAAc,CAAC,EAAE,CACf,IAAI,EAAE,cAAc,EACpB,OAAO,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,KACxD,OAAO,CAAC,QAAQ,CAAC,CAAC;CACxB;AAED;;;;;;GAMG;AACH,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,OAAO,EAChB,QAAQ,EAAE,aAAa,EACvB,aAAa,CAAC,EAAE,MAAM,EAAE,EACxB,WAAW,CAAC,EAAE,WAAW,GACxB,OAAO,CAAC,QAAQ,CAAC,CAuEnB"}
@@ -13,6 +13,8 @@
13
13
  * Security: All image responses include Content-Security-Policy and
14
14
  * X-Content-Type-Options headers to prevent XSS via SVG or Content-Type
15
15
  * spoofing. SVG content is blocked by default (following Next.js behavior).
16
+ * When `dangerouslyAllowSVG` is enabled in next.config.js, SVGs are served
17
+ * as-is (no transformation) with security headers applied.
16
18
  */
17
19
  /** The pathname that triggers image optimization. */
18
20
  export const IMAGE_OPTIMIZATION_PATH = "/_vinext/image";
@@ -123,24 +125,29 @@ const SAFE_IMAGE_CONTENT_TYPES = new Set([
123
125
  ]);
124
126
  /**
125
127
  * Check if a Content-Type header value is a safe image type.
126
- * Returns false for SVG, HTML, or any non-image type.
128
+ * Returns false for SVG (unless dangerouslyAllowSVG is true), HTML, or any non-image type.
127
129
  */
128
- export function isSafeImageContentType(contentType) {
130
+ export function isSafeImageContentType(contentType, dangerouslyAllowSVG = false) {
129
131
  if (!contentType)
130
132
  return false;
131
133
  // Extract the media type, ignoring parameters (e.g., charset)
132
134
  const mediaType = contentType.split(";")[0].trim().toLowerCase();
133
- return SAFE_IMAGE_CONTENT_TYPES.has(mediaType);
135
+ if (SAFE_IMAGE_CONTENT_TYPES.has(mediaType))
136
+ return true;
137
+ if (dangerouslyAllowSVG && mediaType === "image/svg+xml")
138
+ return true;
139
+ return false;
134
140
  }
135
141
  /**
136
142
  * Apply security headers to an image optimization response.
137
143
  * These headers are set on every response from the image endpoint,
138
144
  * regardless of whether the image was transformed or served as-is.
145
+ * When an ImageConfig is provided, uses its values for CSP and Content-Disposition.
139
146
  */
140
- function setImageSecurityHeaders(headers) {
141
- headers.set("Content-Security-Policy", IMAGE_CONTENT_SECURITY_POLICY);
147
+ function setImageSecurityHeaders(headers, config) {
148
+ headers.set("Content-Security-Policy", config?.contentSecurityPolicy ?? IMAGE_CONTENT_SECURITY_POLICY);
142
149
  headers.set("X-Content-Type-Options", "nosniff");
143
- headers.set("Content-Disposition", "inline");
150
+ headers.set("Content-Disposition", config?.contentDispositionType ?? "inline");
144
151
  }
145
152
  /**
146
153
  * Handle image optimization requests.
@@ -149,7 +156,7 @@ function setImageSecurityHeaders(headers) {
149
156
  * handlers, optionally transforms it, and returns the response with appropriate
150
157
  * cache headers.
151
158
  */
152
- export async function handleImageOptimization(request, handlers, allowedWidths) {
159
+ export async function handleImageOptimization(request, handlers, allowedWidths, imageConfig) {
153
160
  const url = new URL(request.url);
154
161
  const params = parseImageParams(url, allowedWidths);
155
162
  if (!params) {
@@ -164,12 +171,23 @@ export async function handleImageOptimization(request, handlers, allowedWidths)
164
171
  // Negotiate output format from Accept header
165
172
  const format = negotiateImageFormat(request.headers.get("Accept"));
166
173
  // Block unsafe Content-Types (e.g., SVG which can contain embedded scripts).
167
- // Check the source Content-Type before any processing if the source is
168
- // an SVG or other non-image type, reject it regardless of transformation.
174
+ // Check the source Content-Type before any processing. SVG is only allowed
175
+ // when dangerouslyAllowSVG is explicitly enabled in next.config.js.
169
176
  const sourceContentType = source.headers.get("Content-Type");
170
- if (!isSafeImageContentType(sourceContentType)) {
177
+ if (!isSafeImageContentType(sourceContentType, imageConfig?.dangerouslyAllowSVG)) {
171
178
  return new Response("The requested resource is not an allowed image type", { status: 400 });
172
179
  }
180
+ // SVG passthrough: SVG is a vector format, so transformation (resize, format
181
+ // conversion) provides no benefit. Serve as-is with security headers.
182
+ // This matches Next.js behavior where SVG is a "bypass type".
183
+ const sourceMediaType = sourceContentType?.split(";")[0].trim().toLowerCase();
184
+ if (sourceMediaType === "image/svg+xml") {
185
+ const headers = new Headers(source.headers);
186
+ headers.set("Cache-Control", IMAGE_CACHE_CONTROL);
187
+ headers.set("Vary", "Accept");
188
+ setImageSecurityHeaders(headers, imageConfig);
189
+ return new Response(source.body, { status: 200, headers });
190
+ }
173
191
  // Transform if handler provided, otherwise serve original
174
192
  if (handlers.transformImage) {
175
193
  try {
@@ -181,10 +199,10 @@ export async function handleImageOptimization(request, handlers, allowedWidths)
181
199
  const headers = new Headers(transformed.headers);
182
200
  headers.set("Cache-Control", IMAGE_CACHE_CONTROL);
183
201
  headers.set("Vary", "Accept");
184
- setImageSecurityHeaders(headers);
202
+ setImageSecurityHeaders(headers, imageConfig);
185
203
  // Verify the transformed response also has a safe Content-Type.
186
204
  // A malicious or buggy transform handler could return HTML.
187
- if (!isSafeImageContentType(headers.get("Content-Type"))) {
205
+ if (!isSafeImageContentType(headers.get("Content-Type"), imageConfig?.dangerouslyAllowSVG)) {
188
206
  headers.set("Content-Type", format);
189
207
  }
190
208
  return new Response(transformed.body, { status: 200, headers });
@@ -198,7 +216,7 @@ export async function handleImageOptimization(request, handlers, allowedWidths)
198
216
  const headers = new Headers(source.headers);
199
217
  headers.set("Cache-Control", IMAGE_CACHE_CONTROL);
200
218
  headers.set("Vary", "Accept");
201
- setImageSecurityHeaders(headers);
219
+ setImageSecurityHeaders(headers, imageConfig);
202
220
  return new Response(source.body, { status: 200, headers });
203
221
  }
204
222
  //# sourceMappingURL=image-optimization.js.map