vinext 0.0.45 → 0.0.46

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 (222) hide show
  1. package/dist/build/prerender.js +10 -3
  2. package/dist/build/prerender.js.map +1 -1
  3. package/dist/build/standalone.js +4 -3
  4. package/dist/build/standalone.js.map +1 -1
  5. package/dist/check.js +30 -18
  6. package/dist/check.js.map +1 -1
  7. package/dist/cli.js +4 -0
  8. package/dist/cli.js.map +1 -1
  9. package/dist/cloudflare/kv-cache-handler.js.map +1 -1
  10. package/dist/config/config-matchers.js +1 -0
  11. package/dist/config/config-matchers.js.map +1 -1
  12. package/dist/config/next-config.d.ts +38 -2
  13. package/dist/config/next-config.js +24 -0
  14. package/dist/config/next-config.js.map +1 -1
  15. package/dist/deploy.js +18 -23
  16. package/dist/deploy.js.map +1 -1
  17. package/dist/entries/app-rsc-entry.js +331 -1732
  18. package/dist/entries/app-rsc-entry.js.map +1 -1
  19. package/dist/entries/app-rsc-manifest.d.ts +24 -0
  20. package/dist/entries/app-rsc-manifest.js +153 -0
  21. package/dist/entries/app-rsc-manifest.js.map +1 -0
  22. package/dist/entries/pages-server-entry.js +13 -103
  23. package/dist/entries/pages-server-entry.js.map +1 -1
  24. package/dist/index.js +54 -34
  25. package/dist/index.js.map +1 -1
  26. package/dist/plugins/rsc-client-shim-excludes.d.ts +6 -0
  27. package/dist/plugins/rsc-client-shim-excludes.js +27 -0
  28. package/dist/plugins/rsc-client-shim-excludes.js.map +1 -0
  29. package/dist/routing/app-router.d.ts +14 -5
  30. package/dist/routing/app-router.js +75 -1
  31. package/dist/routing/app-router.js.map +1 -1
  32. package/dist/routing/route-pattern.d.ts +9 -0
  33. package/dist/routing/route-pattern.js +90 -0
  34. package/dist/routing/route-pattern.js.map +1 -0
  35. package/dist/routing/route-trie.js +10 -11
  36. package/dist/routing/route-trie.js.map +1 -1
  37. package/dist/server/app-browser-entry.js +30 -2
  38. package/dist/server/app-browser-entry.js.map +1 -1
  39. package/dist/server/app-browser-state.js.map +1 -1
  40. package/dist/server/app-middleware.d.ts +32 -0
  41. package/dist/server/app-middleware.js +147 -0
  42. package/dist/server/app-middleware.js.map +1 -0
  43. package/dist/server/app-page-boundary-render.d.ts +2 -0
  44. package/dist/server/app-page-boundary-render.js +50 -30
  45. package/dist/server/app-page-boundary-render.js.map +1 -1
  46. package/dist/server/app-page-boundary.d.ts +12 -1
  47. package/dist/server/app-page-boundary.js +27 -12
  48. package/dist/server/app-page-boundary.js.map +1 -1
  49. package/dist/server/app-page-cache.d.ts +4 -1
  50. package/dist/server/app-page-cache.js +38 -2
  51. package/dist/server/app-page-cache.js.map +1 -1
  52. package/dist/server/app-page-dispatch.d.ts +120 -0
  53. package/dist/server/app-page-dispatch.js +332 -0
  54. package/dist/server/app-page-dispatch.js.map +1 -0
  55. package/dist/server/app-page-execution.d.ts +4 -3
  56. package/dist/server/app-page-execution.js +5 -8
  57. package/dist/server/app-page-execution.js.map +1 -1
  58. package/dist/server/app-page-head.d.ts +55 -0
  59. package/dist/server/app-page-head.js +196 -0
  60. package/dist/server/app-page-head.js.map +1 -0
  61. package/dist/server/app-page-method.d.ts +16 -0
  62. package/dist/server/app-page-method.js +30 -0
  63. package/dist/server/app-page-method.js.map +1 -0
  64. package/dist/server/app-page-params.d.ts +7 -0
  65. package/dist/server/app-page-params.js +28 -0
  66. package/dist/server/app-page-params.js.map +1 -0
  67. package/dist/server/app-page-render.d.ts +2 -1
  68. package/dist/server/app-page-render.js +54 -8
  69. package/dist/server/app-page-render.js.map +1 -1
  70. package/dist/server/app-page-request.d.ts +4 -4
  71. package/dist/server/app-page-request.js.map +1 -1
  72. package/dist/server/app-page-route-wiring.d.ts +14 -3
  73. package/dist/server/app-page-route-wiring.js +30 -8
  74. package/dist/server/app-page-route-wiring.js.map +1 -1
  75. package/dist/server/app-page-stream.d.ts +10 -0
  76. package/dist/server/app-page-stream.js +5 -1
  77. package/dist/server/app-page-stream.js.map +1 -1
  78. package/dist/server/app-prerender-endpoints.d.ts +19 -0
  79. package/dist/server/app-prerender-endpoints.js +96 -0
  80. package/dist/server/app-prerender-endpoints.js.map +1 -0
  81. package/dist/server/app-prerender-static-params.d.ts +16 -0
  82. package/dist/server/app-prerender-static-params.js +14 -0
  83. package/dist/server/app-prerender-static-params.js.map +1 -0
  84. package/dist/server/app-route-handler-cache.d.ts +3 -0
  85. package/dist/server/app-route-handler-cache.js +6 -2
  86. package/dist/server/app-route-handler-cache.js.map +1 -1
  87. package/dist/server/app-route-handler-dispatch.d.ts +42 -0
  88. package/dist/server/app-route-handler-dispatch.js +147 -0
  89. package/dist/server/app-route-handler-dispatch.js.map +1 -0
  90. package/dist/server/app-route-handler-execution.d.ts +6 -2
  91. package/dist/server/app-route-handler-execution.js +23 -2
  92. package/dist/server/app-route-handler-execution.js.map +1 -1
  93. package/dist/server/app-route-handler-response.d.ts +2 -1
  94. package/dist/server/app-route-handler-response.js +44 -4
  95. package/dist/server/app-route-handler-response.js.map +1 -1
  96. package/dist/server/app-route-handler-runtime.d.ts +4 -1
  97. package/dist/server/app-route-handler-runtime.js +107 -1
  98. package/dist/server/app-route-handler-runtime.js.map +1 -1
  99. package/dist/server/app-router-entry.js.map +1 -1
  100. package/dist/server/app-rsc-errors.d.ts +27 -0
  101. package/dist/server/app-rsc-errors.js +42 -0
  102. package/dist/server/app-rsc-errors.js.map +1 -0
  103. package/dist/server/app-rsc-route-matching.d.ts +40 -0
  104. package/dist/server/app-rsc-route-matching.js +66 -0
  105. package/dist/server/app-rsc-route-matching.js.map +1 -0
  106. package/dist/server/app-server-action-execution.d.ts +86 -1
  107. package/dist/server/app-server-action-execution.js +255 -5
  108. package/dist/server/app-server-action-execution.js.map +1 -1
  109. package/dist/server/app-ssr-entry.d.ts +7 -0
  110. package/dist/server/app-ssr-entry.js +30 -9
  111. package/dist/server/app-ssr-entry.js.map +1 -1
  112. package/dist/server/app-ssr-stream.d.ts +4 -2
  113. package/dist/server/app-ssr-stream.js +29 -2
  114. package/dist/server/app-ssr-stream.js.map +1 -1
  115. package/dist/server/app-static-generation.d.ts +15 -0
  116. package/dist/server/app-static-generation.js +20 -0
  117. package/dist/server/app-static-generation.js.map +1 -0
  118. package/dist/server/dev-route-files.d.ts +7 -0
  119. package/dist/server/dev-route-files.js +73 -0
  120. package/dist/server/dev-route-files.js.map +1 -0
  121. package/dist/server/dev-server.js +4 -0
  122. package/dist/server/dev-server.js.map +1 -1
  123. package/dist/server/file-based-metadata.d.ts +17 -0
  124. package/dist/server/file-based-metadata.js +356 -0
  125. package/dist/server/file-based-metadata.js.map +1 -0
  126. package/dist/server/implicit-tags.d.ts +6 -0
  127. package/dist/server/implicit-tags.js +42 -0
  128. package/dist/server/implicit-tags.js.map +1 -0
  129. package/dist/server/instrumentation.js.map +1 -1
  130. package/dist/server/isr-cache.d.ts +20 -2
  131. package/dist/server/isr-cache.js +58 -7
  132. package/dist/server/isr-cache.js.map +1 -1
  133. package/dist/server/metadata-route-build-data.d.ts +25 -0
  134. package/dist/server/metadata-route-build-data.js +150 -0
  135. package/dist/server/metadata-route-build-data.js.map +1 -0
  136. package/dist/server/metadata-route-response.d.ts +17 -0
  137. package/dist/server/metadata-route-response.js +187 -0
  138. package/dist/server/metadata-route-response.js.map +1 -0
  139. package/dist/server/metadata-routes.d.ts +42 -4
  140. package/dist/server/metadata-routes.js +127 -11
  141. package/dist/server/metadata-routes.js.map +1 -1
  142. package/dist/server/middleware-matcher.d.ts +15 -0
  143. package/dist/server/middleware-matcher.js +102 -0
  144. package/dist/server/middleware-matcher.js.map +1 -0
  145. package/dist/server/middleware-request-headers.js +2 -1
  146. package/dist/server/middleware-request-headers.js.map +1 -1
  147. package/dist/server/middleware-runtime.d.ts +39 -0
  148. package/dist/server/middleware-runtime.js +159 -0
  149. package/dist/server/middleware-runtime.js.map +1 -0
  150. package/dist/server/middleware.d.ts +4 -36
  151. package/dist/server/middleware.js +18 -228
  152. package/dist/server/middleware.js.map +1 -1
  153. package/dist/server/pages-page-data.d.ts +5 -1
  154. package/dist/server/pages-page-data.js +4 -0
  155. package/dist/server/pages-page-data.js.map +1 -1
  156. package/dist/server/pages-page-response.js +2 -1
  157. package/dist/server/pages-page-response.js.map +1 -1
  158. package/dist/server/prerender-work-unit-setup.d.ts +7 -0
  159. package/dist/server/prerender-work-unit-setup.js +30 -0
  160. package/dist/server/prerender-work-unit-setup.js.map +1 -0
  161. package/dist/server/prod-server.js +10 -14
  162. package/dist/server/prod-server.js.map +1 -1
  163. package/dist/server/request-pipeline.d.ts +46 -5
  164. package/dist/server/request-pipeline.js +84 -5
  165. package/dist/server/request-pipeline.js.map +1 -1
  166. package/dist/server/rsc-stream-hints.d.ts +5 -0
  167. package/dist/server/rsc-stream-hints.js +35 -0
  168. package/dist/server/rsc-stream-hints.js.map +1 -0
  169. package/dist/server/seed-cache.js.map +1 -1
  170. package/dist/server/server-action-not-found.d.ts +9 -0
  171. package/dist/server/server-action-not-found.js +40 -0
  172. package/dist/server/server-action-not-found.js.map +1 -0
  173. package/dist/shims/cache.d.ts +25 -2
  174. package/dist/shims/cache.js +52 -2
  175. package/dist/shims/cache.js.map +1 -1
  176. package/dist/shims/error-boundary.d.ts +50 -5
  177. package/dist/shims/error-boundary.js +76 -4
  178. package/dist/shims/error-boundary.js.map +1 -1
  179. package/dist/shims/font-google-base.d.ts +5 -4
  180. package/dist/shims/font-google-base.js +61 -13
  181. package/dist/shims/font-google-base.js.map +1 -1
  182. package/dist/shims/headers.d.ts +14 -2
  183. package/dist/shims/headers.js +127 -17
  184. package/dist/shims/headers.js.map +1 -1
  185. package/dist/shims/image.js +26 -8
  186. package/dist/shims/image.js.map +1 -1
  187. package/dist/shims/internal/make-hanging-promise.d.ts +16 -0
  188. package/dist/shims/internal/make-hanging-promise.js +46 -0
  189. package/dist/shims/internal/make-hanging-promise.js.map +1 -0
  190. package/dist/shims/internal/work-unit-async-storage.d.ts +26 -3
  191. package/dist/shims/internal/work-unit-async-storage.js +6 -3
  192. package/dist/shims/internal/work-unit-async-storage.js.map +1 -1
  193. package/dist/shims/metadata.d.ts +38 -26
  194. package/dist/shims/metadata.js +75 -45
  195. package/dist/shims/metadata.js.map +1 -1
  196. package/dist/shims/navigation.d.ts +10 -1
  197. package/dist/shims/navigation.js +18 -1
  198. package/dist/shims/navigation.js.map +1 -1
  199. package/dist/shims/navigation.react-server.d.ts +2 -2
  200. package/dist/shims/navigation.react-server.js +2 -2
  201. package/dist/shims/navigation.react-server.js.map +1 -1
  202. package/dist/shims/offline.d.ts +5 -0
  203. package/dist/shims/offline.js +17 -0
  204. package/dist/shims/offline.js.map +1 -0
  205. package/dist/shims/request-state-types.d.ts +2 -1
  206. package/dist/shims/root-params.d.ts +11 -0
  207. package/dist/shims/root-params.js +24 -0
  208. package/dist/shims/root-params.js.map +1 -0
  209. package/dist/shims/router.js +1 -1
  210. package/dist/shims/server.d.ts +3 -1
  211. package/dist/shims/server.js +83 -5
  212. package/dist/shims/server.js.map +1 -1
  213. package/dist/shims/thenable-params.d.ts +5 -0
  214. package/dist/shims/thenable-params.js +37 -0
  215. package/dist/shims/thenable-params.js.map +1 -0
  216. package/dist/shims/unified-request-context.d.ts +2 -1
  217. package/dist/shims/unified-request-context.js +2 -0
  218. package/dist/shims/unified-request-context.js.map +1 -1
  219. package/package.json +6 -1
  220. package/dist/server/middleware-codegen.d.ts +0 -54
  221. package/dist/server/middleware-codegen.js +0 -414
  222. package/dist/server/middleware-codegen.js.map +0 -1
@@ -1,6 +1,6 @@
1
+ import { getRequestExecutionContext } from "./request-context.js";
1
2
  import { encodeMiddlewareRequestHeaders } from "../server/middleware-request-headers.js";
2
3
  import { parseCookieHeader } from "./internal/parse-cookie-header.js";
3
- import { getRequestExecutionContext } from "./request-context.js";
4
4
  import { assertSafeNavigationUrl } from "./url-safety.js";
5
5
  //#region src/shims/server.ts
6
6
  /**
@@ -16,9 +16,27 @@ import { assertSafeNavigationUrl } from "./url-safety.js";
16
16
  const _USE_CACHE_ALS_KEY = Symbol.for("vinext.cacheRuntime.contextAls");
17
17
  const _UNSTABLE_CACHE_ALS_KEY = Symbol.for("vinext.unstableCache.als");
18
18
  const _g = globalThis;
19
+ /**
20
+ * Record an invalid dynamic usage error on the request context so it survives
21
+ * user try/catch and can be forwarded to the dev overlay on client-side navigations.
22
+ */
23
+ function _recordInvalidDynamicUsageError(error) {
24
+ try {
25
+ const ctx = _g[Symbol.for("vinext.unifiedRequestContext.als")]?.getStore();
26
+ if (ctx) ctx.invalidDynamicUsageError = error;
27
+ } catch {}
28
+ }
19
29
  function _throwIfInsideCacheScope(apiName) {
20
- if (_g[_USE_CACHE_ALS_KEY]?.getStore() != null) throw new Error(`\`${apiName}\` cannot be called inside "use cache". If you need this data inside a cached function, call \`${apiName}\` outside and pass the required data as an argument.`);
21
- if (_g[_UNSTABLE_CACHE_ALS_KEY]?.getStore() === true) throw new Error(`\`${apiName}\` cannot be called inside a function cached with \`unstable_cache()\`. If you need this data inside a cached function, call \`${apiName}\` outside and pass the required data as an argument.`);
30
+ if (_g[_USE_CACHE_ALS_KEY]?.getStore() != null) {
31
+ const error = /* @__PURE__ */ new Error(`\`${apiName}\` cannot be called inside "use cache". If you need this data inside a cached function, call \`${apiName}\` outside and pass the required data as an argument.`);
32
+ _recordInvalidDynamicUsageError(error);
33
+ throw error;
34
+ }
35
+ if (_g[_UNSTABLE_CACHE_ALS_KEY]?.getStore() === true) {
36
+ const error = /* @__PURE__ */ new Error(`\`${apiName}\` cannot be called inside a function cached with \`unstable_cache()\`. If you need this data inside a cached function, call \`${apiName}\` outside and pass the required data as an argument.`);
37
+ _recordInvalidDynamicUsageError(error);
38
+ throw error;
39
+ }
22
40
  }
23
41
  var NextRequest = class extends Request {
24
42
  _nextUrl;
@@ -104,7 +122,7 @@ var NextResponse = class NextResponse extends Response {
104
122
  _cookies;
105
123
  constructor(body, init) {
106
124
  super(body, init);
107
- this._cookies = new ResponseCookies(this.headers);
125
+ this._cookies = new MiddlewareResponseCookies(this.headers);
108
126
  }
109
127
  get cookies() {
110
128
  return this._cookies;
@@ -401,6 +419,41 @@ var RequestCookies = class {
401
419
  return this.getAll().map((c) => [c.name, c])[Symbol.iterator]();
402
420
  }
403
421
  };
422
+ var ReadonlyRequestCookiesError = class ReadonlyRequestCookiesError extends Error {
423
+ constructor() {
424
+ super("Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options");
425
+ }
426
+ static callable() {
427
+ throw new ReadonlyRequestCookiesError();
428
+ }
429
+ };
430
+ const REQUEST_HEADERS_MUTATING_METHODS = new Set([
431
+ "set",
432
+ "delete",
433
+ "append"
434
+ ]);
435
+ var ReadonlyRequestHeadersError = class ReadonlyRequestHeadersError extends Error {
436
+ constructor() {
437
+ super("Headers cannot be modified. Read more: https://nextjs.org/docs/app/api-reference/functions/headers");
438
+ }
439
+ static callable() {
440
+ throw new ReadonlyRequestHeadersError();
441
+ }
442
+ };
443
+ function sealRequestHeaders(headers) {
444
+ return new Proxy(headers, { get(target, prop) {
445
+ if (typeof prop === "string" && REQUEST_HEADERS_MUTATING_METHODS.has(prop)) return ReadonlyRequestHeadersError.callable;
446
+ const value = Reflect.get(target, prop, target);
447
+ return typeof value === "function" ? value.bind(target) : value;
448
+ } });
449
+ }
450
+ function sealRequestCookies(cookies) {
451
+ return new Proxy(cookies, { get(target, prop) {
452
+ if (prop === "set" || prop === "delete" || prop === "clear") return ReadonlyRequestCookiesError.callable;
453
+ const value = Reflect.get(target, prop, target);
454
+ return typeof value === "function" ? value.bind(target) : value;
455
+ } });
456
+ }
404
457
  /**
405
458
  * RFC 6265 §4.1.1: cookie-name is a token (RFC 2616 §2.2).
406
459
  * Allowed: any visible ASCII (0x21-0x7E) except separators: ()<>@,;:\"/[]?={}
@@ -503,6 +556,31 @@ var ResponseCookies = class {
503
556
  for (const { serialized } of this._parsed.values()) this._headers.append("Set-Cookie", serialized);
504
557
  }
505
558
  };
559
+ var MiddlewareResponseCookies = class extends ResponseCookies {
560
+ _responseHeaders;
561
+ constructor(headers) {
562
+ super(headers);
563
+ this._responseHeaders = headers;
564
+ }
565
+ set(...args) {
566
+ super.set(...args);
567
+ this._syncMiddlewareCookieHeader();
568
+ return this;
569
+ }
570
+ delete(...args) {
571
+ super.delete(...args);
572
+ this._syncMiddlewareCookieHeader();
573
+ return this;
574
+ }
575
+ _syncMiddlewareCookieHeader() {
576
+ const cookies = this._responseHeaders.getSetCookie();
577
+ if (cookies.length === 0) {
578
+ this._responseHeaders.delete("x-middleware-set-cookie");
579
+ return;
580
+ }
581
+ this._responseHeaders.set("x-middleware-set-cookie", cookies.join(","));
582
+ }
583
+ };
506
584
  /**
507
585
  * Parse the overloaded arguments for ResponseCookies.set():
508
586
  * - (name, value, options?) — positional form
@@ -598,6 +676,6 @@ const URLPattern = globalThis.URLPattern ?? (() => {
598
676
  throw new Error("URLPattern is not available in this runtime. Install the `urlpattern-polyfill` package or upgrade to Node 20+.");
599
677
  });
600
678
  //#endregion
601
- export { NextFetchEvent, NextRequest, NextResponse, NextURL, RequestCookies, ResponseCookies, URLPattern, after, connection, userAgent, userAgentFromString };
679
+ export { NextFetchEvent, NextRequest, NextResponse, NextURL, RequestCookies, ResponseCookies, URLPattern, after, connection, sealRequestCookies, sealRequestHeaders, userAgent, userAgentFromString };
602
680
 
603
681
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":[],"sources":["../../src/shims/server.ts"],"sourcesContent":["/**\n * next/server shim\n *\n * Provides NextRequest, NextResponse, and related types that work with\n * standard Web APIs (Request/Response). This means they work on Node,\n * Cloudflare Workers, Deno, and any WinterCG-compatible runtime.\n *\n * This is a pragmatic subset — we implement the most commonly used APIs\n * rather than bug-for-bug parity with Next.js internals.\n */\n\nimport { encodeMiddlewareRequestHeaders } from \"../server/middleware-request-headers.js\";\nimport { parseCookieHeader } from \"./internal/parse-cookie-header.js\";\nimport { getRequestExecutionContext } from \"./request-context.js\";\nimport { assertSafeNavigationUrl } from \"./url-safety.js\";\n\n// ---------------------------------------------------------------------------\n// Inlined cache-scope guard for after()\n//\n// We cannot statically import throwIfInsideCacheScope from headers.ts here\n// because headers.ts contains the \"use cache\" directive string in its error\n// message, which causes Vite's use-cache transform to include it in the module\n// graph. If headers.ts is pulled in via static import from server.ts, the\n// transform fires on it in Pages Router fixtures that lack @vitejs/plugin-rsc.\n//\n// The connection() function in this file avoids the same problem by using\n// `await import(\"./headers.js\")` (dynamic import, async function). after()\n// must remain synchronous, so we inline the check using the same Symbol.for\n// keys that cache-runtime.ts and cache.ts register their ALS instances with.\n// ---------------------------------------------------------------------------\n\nconst _USE_CACHE_ALS_KEY = Symbol.for(\"vinext.cacheRuntime.contextAls\");\nconst _UNSTABLE_CACHE_ALS_KEY = Symbol.for(\"vinext.unstableCache.als\");\nconst _g = globalThis as unknown as Record<PropertyKey, unknown>;\n\nfunction _throwIfInsideCacheScope(apiName: string): void {\n const cacheAls = _g[_USE_CACHE_ALS_KEY] as { getStore(): unknown } | undefined;\n if (cacheAls?.getStore() != null) {\n throw new Error(\n `\\`${apiName}\\` cannot be called inside \"use cache\". ` +\n `If you need this data inside a cached function, call \\`${apiName}\\` ` +\n \"outside and pass the required data as an argument.\",\n );\n }\n const unstableAls = _g[_UNSTABLE_CACHE_ALS_KEY] as { getStore(): unknown } | undefined;\n if (unstableAls?.getStore() === true) {\n throw new Error(\n `\\`${apiName}\\` cannot be called inside a function cached with \\`unstable_cache()\\`. ` +\n `If you need this data inside a cached function, call \\`${apiName}\\` ` +\n \"outside and pass the required data as an argument.\",\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// NextRequest\n// ---------------------------------------------------------------------------\n\nexport class NextRequest extends Request {\n private _nextUrl: NextURL;\n private _url: string;\n private _cookies: RequestCookies;\n\n constructor(\n input: URL | RequestInfo,\n init?: RequestInit & {\n nextConfig?: {\n basePath?: string;\n i18n?: { locales: string[]; defaultLocale: string };\n };\n },\n ) {\n // Strip nextConfig before passing to super() — it's vinext-internal,\n // not a valid RequestInit property.\n const { nextConfig: _nextConfig, ...requestInit } = init ?? {};\n // Handle the case where input is a Request object - we need to extract URL and init\n // to avoid Node.js undici issues with passing Request objects directly to super()\n if (input instanceof Request) {\n const req = input;\n super(req.url, {\n method: req.method,\n headers: req.headers,\n body: req.body,\n // @ts-expect-error - duplex is not in RequestInit type but needed for streams\n duplex: req.body ? \"half\" : undefined,\n ...requestInit,\n });\n } else {\n super(input, requestInit);\n }\n const url =\n typeof input === \"string\"\n ? new URL(input, \"http://localhost\")\n : input instanceof URL\n ? input\n : new URL(input.url, \"http://localhost\");\n const urlConfig: NextURLConfig | undefined = _nextConfig\n ? { basePath: _nextConfig.basePath, nextConfig: { i18n: _nextConfig.i18n } }\n : undefined;\n this._nextUrl = new NextURL(url, undefined, urlConfig);\n this._url = process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE\n ? url.toString()\n : this._nextUrl.toString();\n this._cookies = new RequestCookies(this.headers);\n }\n\n get nextUrl(): NextURL {\n return this._nextUrl;\n }\n\n get url(): string {\n return this._url;\n }\n\n get cookies(): RequestCookies {\n return this._cookies;\n }\n\n /**\n * Client IP address. Prefers Cloudflare's trusted CF-Connecting-IP header\n * over the spoofable X-Forwarded-For. Returns undefined if unavailable.\n */\n get ip(): string | undefined {\n return (\n this.headers.get(\"cf-connecting-ip\") ??\n this.headers.get(\"x-real-ip\") ??\n this.headers.get(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ??\n undefined\n );\n }\n\n /**\n * Geolocation data. Platform-dependent (e.g., Cloudflare, Vercel).\n * Returns undefined if not available.\n */\n get geo():\n | { city?: string; country?: string; region?: string; latitude?: string; longitude?: string }\n | undefined {\n // Check Cloudflare-style headers, Vercel-style headers\n const country =\n this.headers.get(\"cf-ipcountry\") ?? this.headers.get(\"x-vercel-ip-country\") ?? undefined;\n if (!country) return undefined;\n return {\n country,\n city: this.headers.get(\"cf-ipcity\") ?? this.headers.get(\"x-vercel-ip-city\") ?? undefined,\n region:\n this.headers.get(\"cf-region\") ??\n this.headers.get(\"x-vercel-ip-country-region\") ??\n undefined,\n latitude:\n this.headers.get(\"cf-iplatitude\") ?? this.headers.get(\"x-vercel-ip-latitude\") ?? undefined,\n longitude:\n this.headers.get(\"cf-iplongitude\") ??\n this.headers.get(\"x-vercel-ip-longitude\") ??\n undefined,\n };\n }\n\n /**\n * The build ID of the Next.js application.\n * Delegates to `nextUrl.buildId` to match Next.js API surface.\n * Can be used in middleware to detect deployment skew between client and server.\n */\n get buildId(): string | undefined {\n return this._nextUrl.buildId;\n }\n}\n\n// ---------------------------------------------------------------------------\n// NextResponse\n// ---------------------------------------------------------------------------\n\n/** Valid HTTP redirect status codes, matching Next.js's REDIRECTS set. */\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\n\nfunction validateURL(url: string | URL): string {\n assertSafeNavigationUrl(String(url));\n try {\n return String(new URL(String(url)));\n } catch (error) {\n throw new Error(\n `URL is malformed \"${String(\n url,\n )}\". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls`,\n { cause: error },\n );\n }\n}\n\nexport class NextResponse<_Body = unknown> extends Response {\n private _cookies: ResponseCookies;\n\n constructor(body?: BodyInit | null, init?: ResponseInit) {\n super(body, init);\n this._cookies = new ResponseCookies(this.headers);\n }\n\n get cookies(): ResponseCookies {\n return this._cookies;\n }\n\n /**\n * Create a JSON response.\n */\n static json<JsonBody>(body: JsonBody, init?: ResponseInit): NextResponse<JsonBody> {\n const headers = new Headers(init?.headers);\n if (!headers.has(\"content-type\")) {\n headers.set(\"content-type\", \"application/json\");\n }\n return new NextResponse(JSON.stringify(body), {\n ...init,\n headers,\n }) as NextResponse<JsonBody>;\n }\n\n /**\n * Create a redirect response.\n */\n static redirect(url: string | URL, init?: number | ResponseInit): NextResponse {\n const status = typeof init === \"number\" ? init : (init?.status ?? 307);\n if (!REDIRECT_STATUSES.has(status)) {\n throw new RangeError(`Failed to execute \"redirect\" on \"response\": Invalid status code`);\n }\n const headers = new Headers(typeof init === \"object\" ? init?.headers : undefined);\n headers.set(\"Location\", validateURL(url));\n return new NextResponse(null, { status, headers });\n }\n\n /**\n * Create a rewrite response (middleware pattern).\n * Sets the x-middleware-rewrite header.\n */\n static rewrite(destination: string | URL, init?: MiddlewareResponseInit): NextResponse {\n const headers = new Headers(init?.headers);\n headers.set(\"x-middleware-rewrite\", validateURL(destination));\n if (init?.request?.headers) {\n encodeMiddlewareRequestHeaders(headers, init.request.headers);\n }\n return new NextResponse(null, { ...init, headers });\n }\n\n /**\n * Continue to the next handler (middleware pattern).\n * Sets the x-middleware-next header.\n */\n static next(init?: MiddlewareResponseInit): NextResponse {\n const headers = new Headers(init?.headers);\n headers.set(\"x-middleware-next\", \"1\");\n if (init?.request?.headers) {\n encodeMiddlewareRequestHeaders(headers, init.request.headers);\n }\n return new NextResponse(null, { ...init, headers });\n }\n}\n\n// ---------------------------------------------------------------------------\n// NextURL — lightweight URL wrapper with pathname helpers\n// ---------------------------------------------------------------------------\n\nexport type NextURLConfig = {\n basePath?: string;\n nextConfig?: {\n i18n?: {\n locales: string[];\n defaultLocale: string;\n };\n };\n};\n\nexport class NextURL {\n /** Internal URL stores the pathname WITHOUT basePath or locale prefix. */\n private _url: URL;\n private _basePath: string;\n private _locale: string | undefined;\n private _defaultLocale: string | undefined;\n private _locales: string[] | undefined;\n\n constructor(input: string | URL, base?: string | URL, config?: NextURLConfig) {\n this._url = new URL(input.toString(), base);\n this._basePath = config?.basePath ?? \"\";\n this._stripBasePath();\n const i18n = config?.nextConfig?.i18n;\n if (i18n) {\n this._locales = [...i18n.locales];\n this._defaultLocale = i18n.defaultLocale;\n this._analyzeLocale(this._locales);\n }\n }\n\n /** Strip basePath prefix from the internal pathname. */\n private _stripBasePath(): void {\n if (!this._basePath) return;\n const { pathname } = this._url;\n if (pathname === this._basePath || pathname.startsWith(this._basePath + \"/\")) {\n this._url.pathname = pathname.slice(this._basePath.length) || \"/\";\n }\n }\n\n /** Extract locale from pathname, stripping it from the internal URL. */\n private _analyzeLocale(locales: string[]): void {\n const segments = this._url.pathname.split(\"/\");\n const candidate = segments[1]?.toLowerCase();\n const match = locales.find((l) => l.toLowerCase() === candidate);\n if (match) {\n this._locale = match;\n this._url.pathname = \"/\" + segments.slice(2).join(\"/\");\n } else {\n this._locale = this._defaultLocale;\n }\n }\n\n /**\n * Reconstruct the full pathname with basePath + locale prefix.\n * Mirrors Next.js's internal formatPathname().\n */\n private _formatPathname(): string {\n // Build prefix: basePath + locale (skip defaultLocale — Next.js omits it)\n let prefix = this._basePath;\n if (this._locale && this._locale !== this._defaultLocale) {\n prefix += \"/\" + this._locale;\n }\n if (!prefix) return this._url.pathname;\n const inner = this._url.pathname;\n return inner === \"/\" ? prefix : prefix + inner;\n }\n\n get href(): string {\n const formatted = this._formatPathname();\n if (formatted === this._url.pathname) return this._url.href;\n // Replace pathname in href via string slicing — avoids URL allocation.\n // URL.href is always <origin+auth><pathname><search><hash>.\n const { href, pathname, search, hash } = this._url;\n const baseEnd = href.length - pathname.length - search.length - hash.length;\n return href.slice(0, baseEnd) + formatted + search + hash;\n }\n set href(value: string) {\n this._url.href = value;\n this._stripBasePath();\n if (this._locales) this._analyzeLocale(this._locales);\n }\n\n get origin(): string {\n return this._url.origin;\n }\n\n get protocol(): string {\n return this._url.protocol;\n }\n set protocol(value: string) {\n this._url.protocol = value;\n }\n\n get username(): string {\n return this._url.username;\n }\n set username(value: string) {\n this._url.username = value;\n }\n\n get password(): string {\n return this._url.password;\n }\n set password(value: string) {\n this._url.password = value;\n }\n\n get host(): string {\n return this._url.host;\n }\n set host(value: string) {\n this._url.host = value;\n }\n\n get hostname(): string {\n return this._url.hostname;\n }\n set hostname(value: string) {\n this._url.hostname = value;\n }\n\n get port(): string {\n return this._url.port;\n }\n set port(value: string) {\n this._url.port = value;\n }\n\n /** Returns the pathname WITHOUT basePath or locale prefix. */\n get pathname(): string {\n return this._url.pathname;\n }\n set pathname(value: string) {\n this._url.pathname = value;\n }\n\n get search(): string {\n return this._url.search;\n }\n set search(value: string) {\n this._url.search = value;\n }\n\n get searchParams(): URLSearchParams {\n return this._url.searchParams;\n }\n\n get hash(): string {\n return this._url.hash;\n }\n set hash(value: string) {\n this._url.hash = value;\n }\n\n get basePath(): string {\n return this._basePath;\n }\n set basePath(value: string) {\n this._basePath = value === \"\" ? \"\" : value.startsWith(\"/\") ? value : \"/\" + value;\n }\n\n get locale(): string {\n return this._locale ?? \"\";\n }\n set locale(value: string | undefined) {\n if (this._locales) {\n if (!value) {\n this._locale = this._defaultLocale;\n return;\n }\n if (!this._locales.includes(value)) {\n throw new TypeError(\n `The locale \"${value}\" is not in the configured locales: ${this._locales.join(\", \")}`,\n );\n }\n }\n this._locale = this._locales ? value : this._locale;\n }\n\n get defaultLocale(): string | undefined {\n return this._defaultLocale;\n }\n\n get locales(): string[] | undefined {\n return this._locales ? [...this._locales] : undefined;\n }\n\n clone(): NextURL {\n const config: NextURLConfig = {\n basePath: this._basePath,\n nextConfig: this._locales\n ? { i18n: { locales: [...this._locales], defaultLocale: this._defaultLocale! } }\n : undefined,\n };\n // Pass the full href (with locale/basePath re-added) so the constructor\n // can re-analyze and extract locale correctly.\n return new NextURL(this.href, undefined, config);\n }\n\n toString(): string {\n return this.href;\n }\n\n /**\n * The build ID of the Next.js application.\n * Set from `generateBuildId` in next.config.js, or a random UUID if not configured.\n * Can be used in middleware to detect deployment skew between client and server.\n * Matches the Next.js API: `request.nextUrl.buildId`.\n */\n get buildId(): string | undefined {\n return process.env.__VINEXT_BUILD_ID ?? undefined;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Cookie helpers (minimal implementations)\n// ---------------------------------------------------------------------------\n\ntype CookieEntry = {\n name: string;\n value: string;\n};\n\nexport class RequestCookies {\n private _headers: Headers;\n private _parsed: Map<string, string>;\n\n constructor(headers: Headers) {\n this._headers = headers;\n this._parsed = parseCookieHeader(headers.get(\"cookie\") ?? \"\");\n }\n\n get(name: string): CookieEntry | undefined {\n const value = this._parsed.get(name);\n return value !== undefined ? { name, value } : undefined;\n }\n\n getAll(nameOrOptions?: string | CookieEntry): CookieEntry[] {\n const name = typeof nameOrOptions === \"string\" ? nameOrOptions : nameOrOptions?.name;\n return [...this._parsed.entries()]\n .filter(([cookieName]) => name === undefined || cookieName === name)\n .map(([cookieName, value]) => ({ name: cookieName, value }));\n }\n\n has(name: string): boolean {\n return this._parsed.has(name);\n }\n\n set(nameOrOptions: string | CookieEntry, value?: string): this {\n let cookieName: string;\n let cookieValue: string;\n if (typeof nameOrOptions === \"string\") {\n cookieName = nameOrOptions;\n cookieValue = value ?? \"\";\n } else {\n cookieName = nameOrOptions.name;\n cookieValue = nameOrOptions.value;\n }\n validateCookieName(cookieName);\n this._parsed.set(cookieName, cookieValue);\n this._syncHeader();\n return this;\n }\n\n delete(names: string | string[]): boolean | boolean[] {\n if (Array.isArray(names)) {\n const results = names.map((name) => {\n validateCookieName(name);\n return this._parsed.delete(name);\n });\n this._syncHeader();\n return results;\n }\n validateCookieName(names);\n const result = this._parsed.delete(names);\n this._syncHeader();\n return result;\n }\n\n clear(): this {\n this._parsed.clear();\n this._syncHeader();\n return this;\n }\n\n get size(): number {\n return this._parsed.size;\n }\n\n toString(): string {\n return this._serialize();\n }\n\n private _serialize(): string {\n return [...this._parsed.entries()].map(([n, v]) => `${n}=${encodeURIComponent(v)}`).join(\"; \");\n }\n\n private _syncHeader(): void {\n if (this._parsed.size === 0) {\n this._headers.delete(\"cookie\");\n } else {\n this._headers.set(\"cookie\", this._serialize());\n }\n }\n\n [Symbol.iterator](): IterableIterator<[string, CookieEntry]> {\n const entries = this.getAll().map((c) => [c.name, c] as [string, CookieEntry]);\n return entries[Symbol.iterator]();\n }\n}\n\n/**\n * RFC 6265 §4.1.1: cookie-name is a token (RFC 2616 §2.2).\n * Allowed: any visible ASCII (0x21-0x7E) except separators: ()<>@,;:\\\"/[]?={}\n */\nconst VALID_COOKIE_NAME_RE =\n /^[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2E\\x30-\\x39\\x41-\\x5A\\x5E-\\x7A\\x7C\\x7E]+$/;\n\nfunction validateCookieName(name: string): void {\n if (!name || !VALID_COOKIE_NAME_RE.test(name)) {\n throw new Error(`Invalid cookie name: ${JSON.stringify(name)}`);\n }\n}\n\nfunction validateCookieAttributeValue(value: string, attributeName: string): void {\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code <= 0x1f || code === 0x7f || value[i] === \";\") {\n throw new Error(`Invalid cookie ${attributeName} value: ${JSON.stringify(value)}`);\n }\n }\n}\n\nexport class ResponseCookies {\n private _headers: Headers;\n /** Internal map keyed by cookie name — single source of truth. */\n private _parsed: Map<string, { serialized: string; entry: CookieEntry }> = new Map();\n\n constructor(headers: Headers) {\n this._headers = headers;\n\n // Hydrate internal map from any existing Set-Cookie headers\n for (const header of headers.getSetCookie()) {\n const eq = header.indexOf(\"=\");\n if (eq === -1) continue;\n const cookieName = header.slice(0, eq);\n const semi = header.indexOf(\";\", eq);\n const raw = header.slice(eq + 1, semi === -1 ? undefined : semi);\n let value: string;\n try {\n value = decodeURIComponent(raw);\n } catch {\n value = raw;\n }\n this._parsed.set(cookieName, { serialized: header, entry: { name: cookieName, value } });\n }\n }\n\n set(\n ...args:\n | [name: string, value: string, options?: CookieOptions]\n | [options: CookieOptions & { name: string; value: string }]\n ): this {\n const [name, value, opts] = parseCookieSetArgs(args);\n validateCookieName(name);\n\n const parts = [`${name}=${encodeURIComponent(value)}`];\n const path = opts?.path ?? \"/\";\n validateCookieAttributeValue(path, \"Path\");\n parts.push(`Path=${path}`);\n if (opts?.domain) {\n validateCookieAttributeValue(opts.domain, \"Domain\");\n parts.push(`Domain=${opts.domain}`);\n }\n if (opts?.maxAge !== undefined) parts.push(`Max-Age=${opts.maxAge}`);\n if (opts?.expires) parts.push(`Expires=${opts.expires.toUTCString()}`);\n if (opts?.httpOnly) parts.push(\"HttpOnly\");\n if (opts?.secure) parts.push(\"Secure\");\n if (opts?.sameSite) parts.push(`SameSite=${opts.sameSite}`);\n\n this._parsed.set(name, { serialized: parts.join(\"; \"), entry: { name, value } });\n this._syncHeaders();\n return this;\n }\n\n get(...args: [name: string] | [options: { name: string }]): CookieEntry | undefined {\n const key = typeof args[0] === \"string\" ? args[0] : args[0].name;\n return this._parsed.get(key)?.entry;\n }\n\n has(name: string): boolean {\n return this._parsed.has(name);\n }\n\n getAll(...args: [name: string] | [options: { name: string }] | []): CookieEntry[] {\n const all = [...this._parsed.values()].map((v) => v.entry);\n if (args.length === 0) return all;\n const key = typeof args[0] === \"string\" ? args[0] : args[0].name;\n return all.filter((c) => c.name === key);\n }\n\n delete(\n ...args:\n | [name: string]\n | [options: Omit<CookieOptions & { name: string }, \"maxAge\" | \"expires\">]\n ): this {\n const [name, opts] =\n typeof args[0] === \"string\" ? [args[0], undefined] : [args[0].name, args[0]];\n return this.set({\n name,\n value: \"\",\n expires: new Date(0),\n path: opts?.path,\n domain: opts?.domain,\n httpOnly: opts?.httpOnly,\n secure: opts?.secure,\n sameSite: opts?.sameSite,\n });\n }\n\n [Symbol.iterator](): IterableIterator<[string, CookieEntry]> {\n const entries: [string, CookieEntry][] = [...this._parsed.values()].map((v) => [\n v.entry.name,\n v.entry,\n ]);\n return entries[Symbol.iterator]();\n }\n\n /** Delete all Set-Cookie headers and re-append from the internal map. */\n private _syncHeaders(): void {\n this._headers.delete(\"Set-Cookie\");\n for (const { serialized } of this._parsed.values()) {\n this._headers.append(\"Set-Cookie\", serialized);\n }\n }\n}\n\ntype CookieOptions = {\n path?: string;\n domain?: string;\n maxAge?: number;\n expires?: Date;\n httpOnly?: boolean;\n secure?: boolean;\n sameSite?: \"Strict\" | \"Lax\" | \"None\";\n};\n\n/**\n * Parse the overloaded arguments for ResponseCookies.set():\n * - (name, value, options?) — positional form\n * - ({ name, value, ...options }) — object form\n */\nfunction parseCookieSetArgs(\n args:\n | [name: string, value: string, options?: CookieOptions]\n | [options: CookieOptions & { name: string; value: string }],\n): [string, string, CookieOptions | undefined] {\n if (typeof args[0] === \"string\") {\n return [args[0], args[1] as string, args[2] as CookieOptions | undefined];\n }\n const { name, value, ...opts } = args[0];\n return [name, value, opts as CookieOptions];\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type MiddlewareResponseInit = {\n request?: {\n headers?: Headers;\n };\n} & ResponseInit;\n\nexport type NextMiddlewareResult = NextResponse | Response | null | undefined | void;\n\nexport type NextMiddleware = (\n request: NextRequest,\n event: NextFetchEvent,\n) => NextMiddlewareResult | Promise<NextMiddlewareResult>;\n\n/**\n * Minimal NextFetchEvent — extends FetchEvent where available,\n * otherwise provides the waitUntil pattern standalone.\n */\nexport class NextFetchEvent {\n sourcePage: string;\n private _waitUntilPromises: Promise<unknown>[] = [];\n\n constructor(params: { page: string }) {\n this.sourcePage = params.page;\n }\n\n waitUntil(promise: Promise<unknown>): void {\n this._waitUntilPromises.push(promise);\n }\n\n get waitUntilPromises(): Promise<unknown>[] {\n return this._waitUntilPromises;\n }\n\n /** Drain all waitUntil promises. Returns a single promise that settles when all are done. */\n drainWaitUntil(): Promise<PromiseSettledResult<unknown>[]> {\n return Promise.allSettled(this._waitUntilPromises);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Utility exports\n// ---------------------------------------------------------------------------\n\n/**\n * Parse user agent string. Minimal implementation — for full UA parsing,\n * apps should use a dedicated library like `ua-parser-js`.\n */\nexport function userAgentFromString(ua: string | undefined): UserAgent {\n const input = ua ?? \"\";\n return {\n isBot: /bot|crawler|spider|crawling/i.test(input),\n ua: input,\n browser: {},\n device: {},\n engine: {},\n os: {},\n cpu: {},\n };\n}\n\nexport function userAgent({ headers }: { headers: Headers }): UserAgent {\n return userAgentFromString(headers.get(\"user-agent\") ?? undefined);\n}\n\nexport type UserAgent = {\n isBot: boolean;\n ua: string;\n browser: { name?: string; version?: string; major?: string };\n device: { model?: string; type?: string; vendor?: string };\n engine: { name?: string; version?: string };\n os: { name?: string; version?: string };\n cpu: { architecture?: string };\n};\n\n/**\n * after() — schedule work after the response is sent.\n *\n * Uses the platform's `waitUntil` (via the per-request ExecutionContext) when\n * available so the task survives past the response on Cloudflare Workers.\n * Falls back to a fire-and-forget microtask on runtimes without an execution\n * context (e.g. Node.js dev server).\n *\n * Throws when called inside a cached scope — request-specific\n * side-effects must not leak into cached results.\n */\nexport function after<T>(task: Promise<T> | (() => T | Promise<T>)): void {\n _throwIfInsideCacheScope(\"after()\");\n\n const promise = typeof task === \"function\" ? Promise.resolve().then(task) : task;\n // NOTE: vinext runs function tasks concurrently with response streaming (next microtask),\n // whereas Next.js queues them to run strictly after the response is sent via onClose.\n // This is a known simplification — function tasks here are not guaranteed to run\n // after the response completes, only after the current synchronous execution.\n //\n // `.catch()` is attached synchronously in the same tick as `promise` is created, so\n // there is no window where a pre-rejected `task` promise could trigger an\n // `unhandledrejection` event before the handler is in place.\n const guarded = promise.catch((err) => {\n console.error(\"[vinext] after() task failed:\", err);\n });\n\n // TODO: Next.js throws when after() is called outside a request context or when\n // waitUntil is unavailable, preventing silent task loss. vinext falls back to\n // fire-and-forget here, which is correct for the Node.js dev server (where\n // getRequestExecutionContext() always returns null). On Workers, a misconfigured\n // entry that omits runWithExecutionContext would silently drop tasks — consider\n // a one-time console.warn on the fallback path, gated to production only (e.g.\n // `process.env.NODE_ENV === 'production'` or `typeof caches !== 'undefined'` for\n // a Workers runtime check) with a module-level `let _warned = false` guard so it\n // fires at most once and doesn't spam the dev-server console.\n getRequestExecutionContext()?.waitUntil(guarded);\n}\n\n/**\n * connection() — signals that the response requires a live connection\n * (not a static/cached response). Opts the page out of ISR caching\n * and sets Cache-Control: no-store on the response.\n */\nexport async function connection(): Promise<void> {\n const { markDynamicUsage, throwIfInsideCacheScope } = await import(\"./headers.js\");\n throwIfInsideCacheScope(\"connection()\");\n markDynamicUsage();\n}\n\n/**\n * URLPattern re-export — used in middleware for route matching.\n * Available natively in Node 20+, Cloudflare Workers, Deno.\n * Falls back to urlpattern-polyfill if the global is not available.\n */\nexport const URLPattern: typeof globalThis.URLPattern =\n globalThis.URLPattern ??\n (() => {\n throw new Error(\n \"URLPattern is not available in this runtime. \" +\n \"Install the `urlpattern-polyfill` package or upgrade to Node 20+.\",\n );\n });\n"],"mappings":";;;;;;;;;;;;;;;AA+BA,MAAM,qBAAqB,OAAO,IAAI,iCAAiC;AACvE,MAAM,0BAA0B,OAAO,IAAI,2BAA2B;AACtE,MAAM,KAAK;AAEX,SAAS,yBAAyB,SAAuB;AAEvD,KADiB,GAAG,qBACN,UAAU,IAAI,KAC1B,OAAM,IAAI,MACR,KAAK,QAAQ,iGAC+C,QAAQ,uDAErE;AAGH,KADoB,GAAG,0BACN,UAAU,KAAK,KAC9B,OAAM,IAAI,MACR,KAAK,QAAQ,iIAC+C,QAAQ,uDAErE;;AAQL,IAAa,cAAb,cAAiC,QAAQ;CACvC;CACA;CACA;CAEA,YACE,OACA,MAMA;EAGA,MAAM,EAAE,YAAY,aAAa,GAAG,gBAAgB,QAAQ,EAAE;AAG9D,MAAI,iBAAiB,SAAS;GAC5B,MAAM,MAAM;AACZ,SAAM,IAAI,KAAK;IACb,QAAQ,IAAI;IACZ,SAAS,IAAI;IACb,MAAM,IAAI;IAEV,QAAQ,IAAI,OAAO,SAAS,KAAA;IAC5B,GAAG;IACJ,CAAC;QAEF,OAAM,OAAO,YAAY;EAE3B,MAAM,MACJ,OAAO,UAAU,WACb,IAAI,IAAI,OAAO,mBAAmB,GAClC,iBAAiB,MACf,QACA,IAAI,IAAI,MAAM,KAAK,mBAAmB;AAI9C,OAAK,WAAW,IAAI,QAAQ,KAAK,KAAA,GAHY,cACzC;GAAE,UAAU,YAAY;GAAU,YAAY,EAAE,MAAM,YAAY,MAAM;GAAE,GAC1E,KAAA,EACkD;AACtD,OAAK,OAAO,QAAQ,IAAI,qCACpB,IAAI,UAAU,GACd,KAAK,SAAS,UAAU;AAC5B,OAAK,WAAW,IAAI,eAAe,KAAK,QAAQ;;CAGlD,IAAI,UAAmB;AACrB,SAAO,KAAK;;CAGd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CAAiC,IAAI;GACnD;AAWF,6BAA4B,EAAE,UAAU,QAAQ;;;;;;;AAQlD,eAAsB,aAA4B;CAChD,MAAM,EAAE,kBAAkB,4BAA4B,MAAM,OAAO;AACnE,yBAAwB,eAAe;AACvC,mBAAkB;;;;;;;AAQpB,MAAa,aACX,WAAW,qBACJ;AACL,OAAM,IAAI,MACR,iHAED"}
1
+ {"version":3,"file":"server.js","names":[],"sources":["../../src/shims/server.ts"],"sourcesContent":["/**\n * next/server shim\n *\n * Provides NextRequest, NextResponse, and related types that work with\n * standard Web APIs (Request/Response). This means they work on Node,\n * Cloudflare Workers, Deno, and any WinterCG-compatible runtime.\n *\n * This is a pragmatic subset — we implement the most commonly used APIs\n * rather than bug-for-bug parity with Next.js internals.\n */\n\nimport { encodeMiddlewareRequestHeaders } from \"../server/middleware-request-headers.js\";\nimport { parseCookieHeader } from \"./internal/parse-cookie-header.js\";\nimport { getRequestExecutionContext } from \"./request-context.js\";\nimport { assertSafeNavigationUrl } from \"./url-safety.js\";\n\n// ---------------------------------------------------------------------------\n// Inlined cache-scope guard for after()\n//\n// We cannot statically import throwIfInsideCacheScope from headers.ts here\n// because headers.ts contains the \"use cache\" directive string in its error\n// message, which causes Vite's use-cache transform to include it in the module\n// graph. If headers.ts is pulled in via static import from server.ts, the\n// transform fires on it in Pages Router fixtures that lack @vitejs/plugin-rsc.\n//\n// The connection() function in this file avoids the same problem by using\n// `await import(\"./headers.js\")` (dynamic import, async function). after()\n// must remain synchronous, so we inline the check using the same Symbol.for\n// keys that cache-runtime.ts and cache.ts register their ALS instances with.\n// ---------------------------------------------------------------------------\n\nconst _USE_CACHE_ALS_KEY = Symbol.for(\"vinext.cacheRuntime.contextAls\");\nconst _UNSTABLE_CACHE_ALS_KEY = Symbol.for(\"vinext.unstableCache.als\");\nconst _g = globalThis as unknown as Record<PropertyKey, unknown>;\n\n/**\n * Record an invalid dynamic usage error on the request context so it survives\n * user try/catch and can be forwarded to the dev overlay on client-side navigations.\n */\nfunction _recordInvalidDynamicUsageError(error: Error): void {\n try {\n const _unifiedAls = _g[Symbol.for(\"vinext.unifiedRequestContext.als\")] as\n | { getStore(): unknown }\n | undefined;\n const ctx = _unifiedAls?.getStore() as Record<string, unknown> | undefined;\n if (ctx) ctx.invalidDynamicUsageError = error;\n } catch {\n // Ignore — best-effort recording for dev diagnostics\n }\n}\n\nfunction _throwIfInsideCacheScope(apiName: string): void {\n const cacheAls = _g[_USE_CACHE_ALS_KEY] as { getStore(): unknown } | undefined;\n if (cacheAls?.getStore() != null) {\n const error = new Error(\n `\\`${apiName}\\` cannot be called inside \"use cache\". ` +\n `If you need this data inside a cached function, call \\`${apiName}\\` ` +\n \"outside and pass the required data as an argument.\",\n );\n _recordInvalidDynamicUsageError(error);\n throw error;\n }\n const unstableAls = _g[_UNSTABLE_CACHE_ALS_KEY] as { getStore(): unknown } | undefined;\n if (unstableAls?.getStore() === true) {\n const error = new Error(\n `\\`${apiName}\\` cannot be called inside a function cached with \\`unstable_cache()\\`. ` +\n `If you need this data inside a cached function, call \\`${apiName}\\` ` +\n \"outside and pass the required data as an argument.\",\n );\n _recordInvalidDynamicUsageError(error);\n throw error;\n }\n}\n\n// ---------------------------------------------------------------------------\n// NextRequest\n// ---------------------------------------------------------------------------\n\nexport class NextRequest extends Request {\n private _nextUrl: NextURL;\n private _url: string;\n private _cookies: RequestCookies;\n\n constructor(\n input: URL | RequestInfo,\n init?: RequestInit & {\n nextConfig?: {\n basePath?: string;\n i18n?: { locales: string[]; defaultLocale: string };\n };\n },\n ) {\n // Strip nextConfig before passing to super() — it's vinext-internal,\n // not a valid RequestInit property.\n const { nextConfig: _nextConfig, ...requestInit } = init ?? {};\n // Handle the case where input is a Request object - we need to extract URL and init\n // to avoid Node.js undici issues with passing Request objects directly to super()\n if (input instanceof Request) {\n const req = input;\n super(req.url, {\n method: req.method,\n headers: req.headers,\n body: req.body,\n // @ts-expect-error - duplex is not in RequestInit type but needed for streams\n duplex: req.body ? \"half\" : undefined,\n ...requestInit,\n });\n } else {\n super(input, requestInit);\n }\n const url =\n typeof input === \"string\"\n ? new URL(input, \"http://localhost\")\n : input instanceof URL\n ? input\n : new URL(input.url, \"http://localhost\");\n const urlConfig: NextURLConfig | undefined = _nextConfig\n ? { basePath: _nextConfig.basePath, nextConfig: { i18n: _nextConfig.i18n } }\n : undefined;\n this._nextUrl = new NextURL(url, undefined, urlConfig);\n this._url = process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE\n ? url.toString()\n : this._nextUrl.toString();\n this._cookies = new RequestCookies(this.headers);\n }\n\n get nextUrl(): NextURL {\n return this._nextUrl;\n }\n\n get url(): string {\n return this._url;\n }\n\n get cookies(): RequestCookies {\n return this._cookies;\n }\n\n /**\n * Client IP address. Prefers Cloudflare's trusted CF-Connecting-IP header\n * over the spoofable X-Forwarded-For. Returns undefined if unavailable.\n */\n get ip(): string | undefined {\n return (\n this.headers.get(\"cf-connecting-ip\") ??\n this.headers.get(\"x-real-ip\") ??\n this.headers.get(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ??\n undefined\n );\n }\n\n /**\n * Geolocation data. Platform-dependent (e.g., Cloudflare, Vercel).\n * Returns undefined if not available.\n */\n get geo():\n | { city?: string; country?: string; region?: string; latitude?: string; longitude?: string }\n | undefined {\n // Check Cloudflare-style headers, Vercel-style headers\n const country =\n this.headers.get(\"cf-ipcountry\") ?? this.headers.get(\"x-vercel-ip-country\") ?? undefined;\n if (!country) return undefined;\n return {\n country,\n city: this.headers.get(\"cf-ipcity\") ?? this.headers.get(\"x-vercel-ip-city\") ?? undefined,\n region:\n this.headers.get(\"cf-region\") ??\n this.headers.get(\"x-vercel-ip-country-region\") ??\n undefined,\n latitude:\n this.headers.get(\"cf-iplatitude\") ?? this.headers.get(\"x-vercel-ip-latitude\") ?? undefined,\n longitude:\n this.headers.get(\"cf-iplongitude\") ??\n this.headers.get(\"x-vercel-ip-longitude\") ??\n undefined,\n };\n }\n\n /**\n * The build ID of the Next.js application.\n * Delegates to `nextUrl.buildId` to match Next.js API surface.\n * Can be used in middleware to detect deployment skew between client and server.\n */\n get buildId(): string | undefined {\n return this._nextUrl.buildId;\n }\n}\n\n// ---------------------------------------------------------------------------\n// NextResponse\n// ---------------------------------------------------------------------------\n\n/** Valid HTTP redirect status codes, matching Next.js's REDIRECTS set. */\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\n\nfunction validateURL(url: string | URL): string {\n assertSafeNavigationUrl(String(url));\n try {\n return String(new URL(String(url)));\n } catch (error) {\n throw new Error(\n `URL is malformed \"${String(\n url,\n )}\". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls`,\n { cause: error },\n );\n }\n}\n\nexport class NextResponse<_Body = unknown> extends Response {\n private _cookies: ResponseCookies;\n\n constructor(body?: BodyInit | null, init?: ResponseInit) {\n super(body, init);\n this._cookies = new MiddlewareResponseCookies(this.headers);\n }\n\n get cookies(): ResponseCookies {\n return this._cookies;\n }\n\n /**\n * Create a JSON response.\n */\n static json<JsonBody>(body: JsonBody, init?: ResponseInit): NextResponse<JsonBody> {\n const headers = new Headers(init?.headers);\n if (!headers.has(\"content-type\")) {\n headers.set(\"content-type\", \"application/json\");\n }\n return new NextResponse(JSON.stringify(body), {\n ...init,\n headers,\n }) as NextResponse<JsonBody>;\n }\n\n /**\n * Create a redirect response.\n */\n static redirect(url: string | URL, init?: number | ResponseInit): NextResponse {\n const status = typeof init === \"number\" ? init : (init?.status ?? 307);\n if (!REDIRECT_STATUSES.has(status)) {\n throw new RangeError(`Failed to execute \"redirect\" on \"response\": Invalid status code`);\n }\n const headers = new Headers(typeof init === \"object\" ? init?.headers : undefined);\n headers.set(\"Location\", validateURL(url));\n return new NextResponse(null, { status, headers });\n }\n\n /**\n * Create a rewrite response (middleware pattern).\n * Sets the x-middleware-rewrite header.\n */\n static rewrite(destination: string | URL, init?: MiddlewareResponseInit): NextResponse {\n const headers = new Headers(init?.headers);\n headers.set(\"x-middleware-rewrite\", validateURL(destination));\n if (init?.request?.headers) {\n encodeMiddlewareRequestHeaders(headers, init.request.headers);\n }\n return new NextResponse(null, { ...init, headers });\n }\n\n /**\n * Continue to the next handler (middleware pattern).\n * Sets the x-middleware-next header.\n */\n static next(init?: MiddlewareResponseInit): NextResponse {\n const headers = new Headers(init?.headers);\n headers.set(\"x-middleware-next\", \"1\");\n if (init?.request?.headers) {\n encodeMiddlewareRequestHeaders(headers, init.request.headers);\n }\n return new NextResponse(null, { ...init, headers });\n }\n}\n\n// ---------------------------------------------------------------------------\n// NextURL — lightweight URL wrapper with pathname helpers\n// ---------------------------------------------------------------------------\n\nexport type NextURLConfig = {\n basePath?: string;\n nextConfig?: {\n i18n?: {\n locales: string[];\n defaultLocale: string;\n };\n };\n};\n\nexport class NextURL {\n /** Internal URL stores the pathname WITHOUT basePath or locale prefix. */\n private _url: URL;\n private _basePath: string;\n private _locale: string | undefined;\n private _defaultLocale: string | undefined;\n private _locales: string[] | undefined;\n\n constructor(input: string | URL, base?: string | URL, config?: NextURLConfig) {\n this._url = new URL(input.toString(), base);\n this._basePath = config?.basePath ?? \"\";\n this._stripBasePath();\n const i18n = config?.nextConfig?.i18n;\n if (i18n) {\n this._locales = [...i18n.locales];\n this._defaultLocale = i18n.defaultLocale;\n this._analyzeLocale(this._locales);\n }\n }\n\n /** Strip basePath prefix from the internal pathname. */\n private _stripBasePath(): void {\n if (!this._basePath) return;\n const { pathname } = this._url;\n if (pathname === this._basePath || pathname.startsWith(this._basePath + \"/\")) {\n this._url.pathname = pathname.slice(this._basePath.length) || \"/\";\n }\n }\n\n /** Extract locale from pathname, stripping it from the internal URL. */\n private _analyzeLocale(locales: string[]): void {\n const segments = this._url.pathname.split(\"/\");\n const candidate = segments[1]?.toLowerCase();\n const match = locales.find((l) => l.toLowerCase() === candidate);\n if (match) {\n this._locale = match;\n this._url.pathname = \"/\" + segments.slice(2).join(\"/\");\n } else {\n this._locale = this._defaultLocale;\n }\n }\n\n /**\n * Reconstruct the full pathname with basePath + locale prefix.\n * Mirrors Next.js's internal formatPathname().\n */\n private _formatPathname(): string {\n // Build prefix: basePath + locale (skip defaultLocale — Next.js omits it)\n let prefix = this._basePath;\n if (this._locale && this._locale !== this._defaultLocale) {\n prefix += \"/\" + this._locale;\n }\n if (!prefix) return this._url.pathname;\n const inner = this._url.pathname;\n return inner === \"/\" ? prefix : prefix + inner;\n }\n\n get href(): string {\n const formatted = this._formatPathname();\n if (formatted === this._url.pathname) return this._url.href;\n // Replace pathname in href via string slicing — avoids URL allocation.\n // URL.href is always <origin+auth><pathname><search><hash>.\n const { href, pathname, search, hash } = this._url;\n const baseEnd = href.length - pathname.length - search.length - hash.length;\n return href.slice(0, baseEnd) + formatted + search + hash;\n }\n set href(value: string) {\n this._url.href = value;\n this._stripBasePath();\n if (this._locales) this._analyzeLocale(this._locales);\n }\n\n get origin(): string {\n return this._url.origin;\n }\n\n get protocol(): string {\n return this._url.protocol;\n }\n set protocol(value: string) {\n this._url.protocol = value;\n }\n\n get username(): string {\n return this._url.username;\n }\n set username(value: string) {\n this._url.username = value;\n }\n\n get password(): string {\n return this._url.password;\n }\n set password(value: string) {\n this._url.password = value;\n }\n\n get host(): string {\n return this._url.host;\n }\n set host(value: string) {\n this._url.host = value;\n }\n\n get hostname(): string {\n return this._url.hostname;\n }\n set hostname(value: string) {\n this._url.hostname = value;\n }\n\n get port(): string {\n return this._url.port;\n }\n set port(value: string) {\n this._url.port = value;\n }\n\n /** Returns the pathname WITHOUT basePath or locale prefix. */\n get pathname(): string {\n return this._url.pathname;\n }\n set pathname(value: string) {\n this._url.pathname = value;\n }\n\n get search(): string {\n return this._url.search;\n }\n set search(value: string) {\n this._url.search = value;\n }\n\n get searchParams(): URLSearchParams {\n return this._url.searchParams;\n }\n\n get hash(): string {\n return this._url.hash;\n }\n set hash(value: string) {\n this._url.hash = value;\n }\n\n get basePath(): string {\n return this._basePath;\n }\n set basePath(value: string) {\n this._basePath = value === \"\" ? \"\" : value.startsWith(\"/\") ? value : \"/\" + value;\n }\n\n get locale(): string {\n return this._locale ?? \"\";\n }\n set locale(value: string | undefined) {\n if (this._locales) {\n if (!value) {\n this._locale = this._defaultLocale;\n return;\n }\n if (!this._locales.includes(value)) {\n throw new TypeError(\n `The locale \"${value}\" is not in the configured locales: ${this._locales.join(\", \")}`,\n );\n }\n }\n this._locale = this._locales ? value : this._locale;\n }\n\n get defaultLocale(): string | undefined {\n return this._defaultLocale;\n }\n\n get locales(): string[] | undefined {\n return this._locales ? [...this._locales] : undefined;\n }\n\n clone(): NextURL {\n const config: NextURLConfig = {\n basePath: this._basePath,\n nextConfig: this._locales\n ? { i18n: { locales: [...this._locales], defaultLocale: this._defaultLocale! } }\n : undefined,\n };\n // Pass the full href (with locale/basePath re-added) so the constructor\n // can re-analyze and extract locale correctly.\n return new NextURL(this.href, undefined, config);\n }\n\n toString(): string {\n return this.href;\n }\n\n /**\n * The build ID of the Next.js application.\n * Set from `generateBuildId` in next.config.js, or a random UUID if not configured.\n * Can be used in middleware to detect deployment skew between client and server.\n * Matches the Next.js API: `request.nextUrl.buildId`.\n */\n get buildId(): string | undefined {\n return process.env.__VINEXT_BUILD_ID ?? undefined;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Cookie helpers (minimal implementations)\n// ---------------------------------------------------------------------------\n\ntype CookieEntry = {\n name: string;\n value: string;\n};\n\nexport class RequestCookies {\n private _headers: Headers;\n private _parsed: Map<string, string>;\n\n constructor(headers: Headers) {\n this._headers = headers;\n this._parsed = parseCookieHeader(headers.get(\"cookie\") ?? \"\");\n }\n\n get(name: string): CookieEntry | undefined {\n const value = this._parsed.get(name);\n return value !== undefined ? { name, value } : undefined;\n }\n\n getAll(nameOrOptions?: string | CookieEntry): CookieEntry[] {\n const name = typeof nameOrOptions === \"string\" ? nameOrOptions : nameOrOptions?.name;\n return [...this._parsed.entries()]\n .filter(([cookieName]) => name === undefined || cookieName === name)\n .map(([cookieName, value]) => ({ name: cookieName, value }));\n }\n\n has(name: string): boolean {\n return this._parsed.has(name);\n }\n\n set(nameOrOptions: string | CookieEntry, value?: string): this {\n let cookieName: string;\n let cookieValue: string;\n if (typeof nameOrOptions === \"string\") {\n cookieName = nameOrOptions;\n cookieValue = value ?? \"\";\n } else {\n cookieName = nameOrOptions.name;\n cookieValue = nameOrOptions.value;\n }\n validateCookieName(cookieName);\n this._parsed.set(cookieName, cookieValue);\n this._syncHeader();\n return this;\n }\n\n delete(names: string | string[]): boolean | boolean[] {\n if (Array.isArray(names)) {\n const results = names.map((name) => {\n validateCookieName(name);\n return this._parsed.delete(name);\n });\n this._syncHeader();\n return results;\n }\n validateCookieName(names);\n const result = this._parsed.delete(names);\n this._syncHeader();\n return result;\n }\n\n clear(): this {\n this._parsed.clear();\n this._syncHeader();\n return this;\n }\n\n get size(): number {\n return this._parsed.size;\n }\n\n toString(): string {\n return this._serialize();\n }\n\n private _serialize(): string {\n return [...this._parsed.entries()].map(([n, v]) => `${n}=${encodeURIComponent(v)}`).join(\"; \");\n }\n\n private _syncHeader(): void {\n if (this._parsed.size === 0) {\n this._headers.delete(\"cookie\");\n } else {\n this._headers.set(\"cookie\", this._serialize());\n }\n }\n\n [Symbol.iterator](): IterableIterator<[string, CookieEntry]> {\n const entries = this.getAll().map((c) => [c.name, c] as [string, CookieEntry]);\n return entries[Symbol.iterator]();\n }\n}\n\n// Keep this error message in sync with headers.ts. This adapter backs\n// NextRequest cookies, while headers.ts owns the next/headers cookies object.\nclass ReadonlyRequestCookiesError extends Error {\n constructor() {\n super(\n \"Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options\",\n );\n }\n\n static callable(this: void): never {\n throw new ReadonlyRequestCookiesError();\n }\n}\n\nconst REQUEST_HEADERS_MUTATING_METHODS = new Set([\"set\", \"delete\", \"append\"]);\n\n// Keep this error message in sync with headers.ts. This adapter backs\n// NextRequest headers in force-static route handlers, while headers.ts owns the\n// next/headers object.\nclass ReadonlyRequestHeadersError extends Error {\n constructor() {\n super(\n \"Headers cannot be modified. Read more: https://nextjs.org/docs/app/api-reference/functions/headers\",\n );\n }\n\n static callable(this: void): never {\n throw new ReadonlyRequestHeadersError();\n }\n}\n\nexport function sealRequestHeaders(headers: Headers): Headers {\n return new Proxy<Headers>(headers, {\n get(target, prop) {\n if (typeof prop === \"string\" && REQUEST_HEADERS_MUTATING_METHODS.has(prop)) {\n return ReadonlyRequestHeadersError.callable;\n }\n\n const value = Reflect.get(target, prop, target);\n return typeof value === \"function\" ? value.bind(target) : value;\n },\n });\n}\n\nexport function sealRequestCookies(cookies: RequestCookies): RequestCookies {\n return new Proxy<RequestCookies>(cookies, {\n get(target, prop) {\n if (prop === \"set\" || prop === \"delete\" || prop === \"clear\") {\n return ReadonlyRequestCookiesError.callable;\n }\n\n const value = Reflect.get(target, prop, target);\n return typeof value === \"function\" ? value.bind(target) : value;\n },\n });\n}\n\n/**\n * RFC 6265 §4.1.1: cookie-name is a token (RFC 2616 §2.2).\n * Allowed: any visible ASCII (0x21-0x7E) except separators: ()<>@,;:\\\"/[]?={}\n */\nconst VALID_COOKIE_NAME_RE =\n /^[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2E\\x30-\\x39\\x41-\\x5A\\x5E-\\x7A\\x7C\\x7E]+$/;\n\nfunction validateCookieName(name: string): void {\n if (!name || !VALID_COOKIE_NAME_RE.test(name)) {\n throw new Error(`Invalid cookie name: ${JSON.stringify(name)}`);\n }\n}\n\nfunction validateCookieAttributeValue(value: string, attributeName: string): void {\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code <= 0x1f || code === 0x7f || value[i] === \";\") {\n throw new Error(`Invalid cookie ${attributeName} value: ${JSON.stringify(value)}`);\n }\n }\n}\n\nexport class ResponseCookies {\n private _headers: Headers;\n /** Internal map keyed by cookie name — single source of truth. */\n private _parsed: Map<string, { serialized: string; entry: CookieEntry }> = new Map();\n\n constructor(headers: Headers) {\n this._headers = headers;\n\n // Hydrate internal map from any existing Set-Cookie headers\n for (const header of headers.getSetCookie()) {\n const eq = header.indexOf(\"=\");\n if (eq === -1) continue;\n const cookieName = header.slice(0, eq);\n const semi = header.indexOf(\";\", eq);\n const raw = header.slice(eq + 1, semi === -1 ? undefined : semi);\n let value: string;\n try {\n value = decodeURIComponent(raw);\n } catch {\n value = raw;\n }\n this._parsed.set(cookieName, { serialized: header, entry: { name: cookieName, value } });\n }\n }\n\n set(\n ...args:\n | [name: string, value: string, options?: CookieOptions]\n | [options: CookieOptions & { name: string; value: string }]\n ): this {\n const [name, value, opts] = parseCookieSetArgs(args);\n validateCookieName(name);\n\n const parts = [`${name}=${encodeURIComponent(value)}`];\n const path = opts?.path ?? \"/\";\n validateCookieAttributeValue(path, \"Path\");\n parts.push(`Path=${path}`);\n if (opts?.domain) {\n validateCookieAttributeValue(opts.domain, \"Domain\");\n parts.push(`Domain=${opts.domain}`);\n }\n if (opts?.maxAge !== undefined) parts.push(`Max-Age=${opts.maxAge}`);\n if (opts?.expires) parts.push(`Expires=${opts.expires.toUTCString()}`);\n if (opts?.httpOnly) parts.push(\"HttpOnly\");\n if (opts?.secure) parts.push(\"Secure\");\n if (opts?.sameSite) parts.push(`SameSite=${opts.sameSite}`);\n\n this._parsed.set(name, { serialized: parts.join(\"; \"), entry: { name, value } });\n this._syncHeaders();\n return this;\n }\n\n get(...args: [name: string] | [options: { name: string }]): CookieEntry | undefined {\n const key = typeof args[0] === \"string\" ? args[0] : args[0].name;\n return this._parsed.get(key)?.entry;\n }\n\n has(name: string): boolean {\n return this._parsed.has(name);\n }\n\n getAll(...args: [name: string] | [options: { name: string }] | []): CookieEntry[] {\n const all = [...this._parsed.values()].map((v) => v.entry);\n if (args.length === 0) return all;\n const key = typeof args[0] === \"string\" ? args[0] : args[0].name;\n return all.filter((c) => c.name === key);\n }\n\n delete(\n ...args:\n | [name: string]\n | [options: Omit<CookieOptions & { name: string }, \"maxAge\" | \"expires\">]\n ): this {\n const [name, opts] =\n typeof args[0] === \"string\" ? [args[0], undefined] : [args[0].name, args[0]];\n return this.set({\n name,\n value: \"\",\n expires: new Date(0),\n path: opts?.path,\n domain: opts?.domain,\n httpOnly: opts?.httpOnly,\n secure: opts?.secure,\n sameSite: opts?.sameSite,\n });\n }\n\n [Symbol.iterator](): IterableIterator<[string, CookieEntry]> {\n const entries: [string, CookieEntry][] = [...this._parsed.values()].map((v) => [\n v.entry.name,\n v.entry,\n ]);\n return entries[Symbol.iterator]();\n }\n\n /** Delete all Set-Cookie headers and re-append from the internal map. */\n private _syncHeaders(): void {\n this._headers.delete(\"Set-Cookie\");\n for (const { serialized } of this._parsed.values()) {\n this._headers.append(\"Set-Cookie\", serialized);\n }\n }\n}\n\nclass MiddlewareResponseCookies extends ResponseCookies {\n private _responseHeaders: Headers;\n\n constructor(headers: Headers) {\n super(headers);\n this._responseHeaders = headers;\n }\n\n override set(\n ...args:\n | [name: string, value: string, options?: CookieOptions]\n | [options: CookieOptions & { name: string; value: string }]\n ): this {\n super.set(...args);\n this._syncMiddlewareCookieHeader();\n return this;\n }\n\n override delete(\n ...args:\n | [name: string]\n | [options: Omit<CookieOptions & { name: string }, \"maxAge\" | \"expires\">]\n ): this {\n super.delete(...args);\n this._syncMiddlewareCookieHeader();\n return this;\n }\n\n private _syncMiddlewareCookieHeader(): void {\n const cookies = this._responseHeaders.getSetCookie();\n if (cookies.length === 0) {\n this._responseHeaders.delete(\"x-middleware-set-cookie\");\n return;\n }\n\n this._responseHeaders.set(\"x-middleware-set-cookie\", cookies.join(\",\"));\n }\n}\n\ntype CookieOptions = {\n path?: string;\n domain?: string;\n maxAge?: number;\n expires?: Date;\n httpOnly?: boolean;\n secure?: boolean;\n sameSite?: \"Strict\" | \"Lax\" | \"None\";\n};\n\n/**\n * Parse the overloaded arguments for ResponseCookies.set():\n * - (name, value, options?) — positional form\n * - ({ name, value, ...options }) — object form\n */\nfunction parseCookieSetArgs(\n args:\n | [name: string, value: string, options?: CookieOptions]\n | [options: CookieOptions & { name: string; value: string }],\n): [string, string, CookieOptions | undefined] {\n if (typeof args[0] === \"string\") {\n return [args[0], args[1] as string, args[2] as CookieOptions | undefined];\n }\n const { name, value, ...opts } = args[0];\n return [name, value, opts as CookieOptions];\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type MiddlewareResponseInit = {\n request?: {\n headers?: Headers;\n };\n} & ResponseInit;\n\nexport type NextMiddlewareResult = NextResponse | Response | null | undefined | void;\n\nexport type NextMiddleware = (\n request: NextRequest,\n event: NextFetchEvent,\n) => NextMiddlewareResult | Promise<NextMiddlewareResult>;\n\n/**\n * Minimal NextFetchEvent — extends FetchEvent where available,\n * otherwise provides the waitUntil pattern standalone.\n */\nexport class NextFetchEvent {\n sourcePage: string;\n private _waitUntilPromises: Promise<unknown>[] = [];\n\n constructor(params: { page: string }) {\n this.sourcePage = params.page;\n }\n\n waitUntil(promise: Promise<unknown>): void {\n this._waitUntilPromises.push(promise);\n }\n\n get waitUntilPromises(): Promise<unknown>[] {\n return this._waitUntilPromises;\n }\n\n /** Drain all waitUntil promises. Returns a single promise that settles when all are done. */\n drainWaitUntil(): Promise<PromiseSettledResult<unknown>[]> {\n return Promise.allSettled(this._waitUntilPromises);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Utility exports\n// ---------------------------------------------------------------------------\n\n/**\n * Parse user agent string. Minimal implementation — for full UA parsing,\n * apps should use a dedicated library like `ua-parser-js`.\n */\nexport function userAgentFromString(ua: string | undefined): UserAgent {\n const input = ua ?? \"\";\n return {\n isBot: /bot|crawler|spider|crawling/i.test(input),\n ua: input,\n browser: {},\n device: {},\n engine: {},\n os: {},\n cpu: {},\n };\n}\n\nexport function userAgent({ headers }: { headers: Headers }): UserAgent {\n return userAgentFromString(headers.get(\"user-agent\") ?? undefined);\n}\n\nexport type UserAgent = {\n isBot: boolean;\n ua: string;\n browser: { name?: string; version?: string; major?: string };\n device: { model?: string; type?: string; vendor?: string };\n engine: { name?: string; version?: string };\n os: { name?: string; version?: string };\n cpu: { architecture?: string };\n};\n\n/**\n * after() — schedule work after the response is sent.\n *\n * Uses the platform's `waitUntil` (via the per-request ExecutionContext) when\n * available so the task survives past the response on Cloudflare Workers.\n * Falls back to a fire-and-forget microtask on runtimes without an execution\n * context (e.g. Node.js dev server).\n *\n * Throws when called inside a cached scope — request-specific\n * side-effects must not leak into cached results.\n */\nexport function after<T>(task: Promise<T> | (() => T | Promise<T>)): void {\n _throwIfInsideCacheScope(\"after()\");\n\n const promise = typeof task === \"function\" ? Promise.resolve().then(task) : task;\n // NOTE: vinext runs function tasks concurrently with response streaming (next microtask),\n // whereas Next.js queues them to run strictly after the response is sent via onClose.\n // This is a known simplification — function tasks here are not guaranteed to run\n // after the response completes, only after the current synchronous execution.\n //\n // `.catch()` is attached synchronously in the same tick as `promise` is created, so\n // there is no window where a pre-rejected `task` promise could trigger an\n // `unhandledrejection` event before the handler is in place.\n const guarded = promise.catch((err) => {\n console.error(\"[vinext] after() task failed:\", err);\n });\n\n // TODO: Next.js throws when after() is called outside a request context or when\n // waitUntil is unavailable, preventing silent task loss. vinext falls back to\n // fire-and-forget here, which is correct for the Node.js dev server (where\n // getRequestExecutionContext() always returns null). On Workers, a misconfigured\n // entry that omits runWithExecutionContext would silently drop tasks — consider\n // a one-time console.warn on the fallback path, gated to production only (e.g.\n // `process.env.NODE_ENV === 'production'` or `typeof caches !== 'undefined'` for\n // a Workers runtime check) with a module-level `let _warned = false` guard so it\n // fires at most once and doesn't spam the dev-server console.\n getRequestExecutionContext()?.waitUntil(guarded);\n}\n\n/**\n * connection() — signals that the response requires a live connection\n * (not a static/cached response). Opts the page out of ISR caching\n * and sets Cache-Control: no-store on the response.\n */\nexport async function connection(): Promise<void> {\n const { markDynamicUsage, throwIfInsideCacheScope } = await import(\"./headers.js\");\n throwIfInsideCacheScope(\"connection()\");\n markDynamicUsage();\n}\n\n/**\n * URLPattern re-export — used in middleware for route matching.\n * Available natively in Node 20+, Cloudflare Workers, Deno.\n * Falls back to urlpattern-polyfill if the global is not available.\n */\nexport const URLPattern: typeof globalThis.URLPattern =\n globalThis.URLPattern ??\n (() => {\n throw new Error(\n \"URLPattern is not available in this runtime. \" +\n \"Install the `urlpattern-polyfill` package or upgrade to Node 20+.\",\n );\n });\n"],"mappings":";;;;;;;;;;;;;;;AA+BA,MAAM,qBAAqB,OAAO,IAAI,iCAAiC;AACvE,MAAM,0BAA0B,OAAO,IAAI,2BAA2B;AACtE,MAAM,KAAK;;;;;AAMX,SAAS,gCAAgC,OAAoB;AAC3D,KAAI;EAIF,MAAM,MAHc,GAAG,OAAO,IAAI,mCAAmC,GAG5C,UAAU;AACnC,MAAI,IAAK,KAAI,2BAA2B;SAClC;;AAKV,SAAS,yBAAyB,SAAuB;AAEvD,KADiB,GAAG,qBACN,UAAU,IAAI,MAAM;EAChC,MAAM,wBAAQ,IAAI,MAChB,KAAK,QAAQ,iGAC+C,QAAQ,uDAErE;AACD,kCAAgC,MAAM;AACtC,QAAM;;AAGR,KADoB,GAAG,0BACN,UAAU,KAAK,MAAM;EACpC,MAAM,wBAAQ,IAAI,MAChB,KAAK,QAAQ,iIAC+C,QAAQ,uDAErE;AACD,kCAAgC,MAAM;AACtC,QAAM;;;AAQV,IAAa,cAAb,cAAiC,QAAQ;CACvC;CACA;CACA;CAEA,YACE,OACA,MAMA;EAGA,MAAM,EAAE,YAAY,aAAa,GAAG,gBAAgB,QAAQ,EAAE;AAG9D,MAAI,iBAAiB,SAAS;GAC5B,MAAM,MAAM;AACZ,SAAM,IAAI,KAAK;IACb,QAAQ,IAAI;IACZ,SAAS,IAAI;IACb,MAAM,IAAI;IAEV,QAAQ,IAAI,OAAO,SAAS,KAAA;IAC5B,GAAG;IACJ,CAAC;QAEF,OAAM,OAAO,YAAY;EAE3B,MAAM,MACJ,OAAO,UAAU,WACb,IAAI,IAAI,OAAO,mBAAmB,GAClC,iBAAiB,MACf,QACA,IAAI,IAAI,MAAM,KAAK,mBAAmB;AAI9C,OAAK,WAAW,IAAI,QAAQ,KAAK,KAAA,GAHY,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,QAAQ,EAAE;EACV,QAAQ,EAAE;EACV,IAAI,EAAE;EACN,KAAK,EAAE;EACR;;AAGH,SAAgB,UAAU,EAAE,WAA4C;AACtE,QAAO,oBAAoB,QAAQ,IAAI,aAAa,IAAI,KAAA,EAAU;;;;;;;;;;;;;AAwBpE,SAAgB,MAAS,MAAiD;AACxE,0BAAyB,UAAU;CAWnC,MAAM,WATU,OAAO,SAAS,aAAa,QAAQ,SAAS,CAAC,KAAK,KAAK,GAAG,MASpD,OAAO,QAAQ;AACrC,UAAQ,MAAM,iCAAiC,IAAI;GACnD;AAWF,6BAA4B,EAAE,UAAU,QAAQ;;;;;;;AAQlD,eAAsB,aAA4B;CAChD,MAAM,EAAE,kBAAkB,4BAA4B,MAAM,OAAO;AACnE,yBAAwB,eAAe;AACvC,mBAAkB;;;;;;;AAQpB,MAAa,aACX,WAAW,qBACJ;AACL,OAAM,IAAI,MACR,iHAED"}
@@ -0,0 +1,5 @@
1
+ //#region src/shims/thenable-params.d.ts
2
+ declare function makeThenableParams<T extends Record<string, unknown>>(obj: T): Promise<Awaited<T>>;
3
+ //#endregion
4
+ export { makeThenableParams };
5
+ //# sourceMappingURL=thenable-params.d.ts.map
@@ -0,0 +1,37 @@
1
+ //#region src/shims/thenable-params.ts
2
+ function hasParamProperty(obj, prop) {
3
+ return Object.prototype.hasOwnProperty.call(obj, prop);
4
+ }
5
+ function isPromiseMethod(prop) {
6
+ return prop === "then" || prop === "catch" || prop === "finally";
7
+ }
8
+ function makeThenableParams(obj) {
9
+ const plain = { ...obj };
10
+ const promise = Promise.resolve(plain);
11
+ return new Proxy(promise, {
12
+ get(target, prop, receiver) {
13
+ if (!isPromiseMethod(prop) && hasParamProperty(plain, prop)) return Reflect.get(plain, prop);
14
+ const value = Reflect.get(target, prop, receiver);
15
+ return typeof value === "function" ? value.bind(target) : value;
16
+ },
17
+ getOwnPropertyDescriptor(target, prop) {
18
+ if (!isPromiseMethod(prop) && hasParamProperty(plain, prop)) return {
19
+ configurable: true,
20
+ enumerable: true,
21
+ value: Reflect.get(plain, prop),
22
+ writable: true
23
+ };
24
+ return Reflect.getOwnPropertyDescriptor(target, prop);
25
+ },
26
+ has(target, prop) {
27
+ return Reflect.has(target, prop) || hasParamProperty(plain, prop);
28
+ },
29
+ ownKeys() {
30
+ return Reflect.ownKeys(plain).filter((prop) => !isPromiseMethod(prop));
31
+ }
32
+ });
33
+ }
34
+ //#endregion
35
+ export { makeThenableParams };
36
+
37
+ //# sourceMappingURL=thenable-params.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"thenable-params.js","names":[],"sources":["../../src/shims/thenable-params.ts"],"sourcesContent":["function hasParamProperty<T extends Record<string, unknown>>(obj: T, prop: PropertyKey): boolean {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nfunction isPromiseMethod(prop: PropertyKey): boolean {\n return prop === \"then\" || prop === \"catch\" || prop === \"finally\";\n}\n\nexport function makeThenableParams<T extends Record<string, unknown>>(obj: T) {\n const plain = { ...obj };\n const promise = Promise.resolve(plain);\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (!isPromiseMethod(prop) && hasParamProperty(plain, prop)) {\n return Reflect.get(plain, prop);\n }\n\n const value = Reflect.get(target, prop, receiver);\n return typeof value === \"function\" ? value.bind(target) : value;\n },\n getOwnPropertyDescriptor(target, prop) {\n if (!isPromiseMethod(prop) && hasParamProperty(plain, prop)) {\n return {\n configurable: true,\n enumerable: true,\n value: Reflect.get(plain, prop),\n writable: true,\n };\n }\n\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n has(target, prop) {\n return Reflect.has(target, prop) || hasParamProperty(plain, prop);\n },\n ownKeys() {\n return Reflect.ownKeys(plain).filter((prop) => !isPromiseMethod(prop));\n },\n });\n}\n"],"mappings":";AAAA,SAAS,iBAAoD,KAAQ,MAA4B;AAC/F,QAAO,OAAO,UAAU,eAAe,KAAK,KAAK,KAAK;;AAGxD,SAAS,gBAAgB,MAA4B;AACnD,QAAO,SAAS,UAAU,SAAS,WAAW,SAAS;;AAGzD,SAAgB,mBAAsD,KAAQ;CAC5E,MAAM,QAAQ,EAAE,GAAG,KAAK;CACxB,MAAM,UAAU,QAAQ,QAAQ,MAAM;AAEtC,QAAO,IAAI,MAAM,SAAS;EACxB,IAAI,QAAQ,MAAM,UAAU;AAC1B,OAAI,CAAC,gBAAgB,KAAK,IAAI,iBAAiB,OAAO,KAAK,CACzD,QAAO,QAAQ,IAAI,OAAO,KAAK;GAGjC,MAAM,QAAQ,QAAQ,IAAI,QAAQ,MAAM,SAAS;AACjD,UAAO,OAAO,UAAU,aAAa,MAAM,KAAK,OAAO,GAAG;;EAE5D,yBAAyB,QAAQ,MAAM;AACrC,OAAI,CAAC,gBAAgB,KAAK,IAAI,iBAAiB,OAAO,KAAK,CACzD,QAAO;IACL,cAAc;IACd,YAAY;IACZ,OAAO,QAAQ,IAAI,OAAO,KAAK;IAC/B,UAAU;IACX;AAGH,UAAO,QAAQ,yBAAyB,QAAQ,KAAK;;EAEvD,IAAI,QAAQ,MAAM;AAChB,UAAO,QAAQ,IAAI,QAAQ,KAAK,IAAI,iBAAiB,OAAO,KAAK;;EAEnE,UAAU;AACR,UAAO,QAAQ,QAAQ,MAAM,CAAC,QAAQ,SAAS,CAAC,gBAAgB,KAAK,CAAC;;EAEzE,CAAC"}
@@ -1,6 +1,7 @@
1
1
  import { PrivateCacheState } from "./cache-runtime.js";
2
2
  import { ExecutionContextLike } from "./request-context.js";
3
3
  import { CacheState } from "./cache.js";
4
+ import { RootParamsState } from "./root-params.js";
4
5
  import { VinextHeadersShimState } from "./headers.js";
5
6
  import { RouterState } from "./router-state.js";
6
7
  import { FetchCacheState } from "./fetch-cache.js";
@@ -18,7 +19,7 @@ import { NavigationState } from "./navigation-state.js";
18
19
  type UnifiedRequestContext = {
19
20
  /** Cloudflare Workers ExecutionContext, or null on Node.js dev. */executionContext: ExecutionContextLike | null; /** Per-request cache for cacheForRequest(). Keyed by factory function reference. */
20
21
  requestCache: WeakMap<(...args: any[]) => any, unknown>;
21
- } & VinextHeadersShimState & I18nState & NavigationState & CacheState & PrivateCacheState & FetchCacheState & RouterState & HeadState;
22
+ } & VinextHeadersShimState & I18nState & NavigationState & CacheState & PrivateCacheState & FetchCacheState & RouterState & HeadState & RootParamsState;
22
23
  /**
23
24
  * Create a fresh `UnifiedRequestContext` with defaults for all fields.
24
25
  * Pass partial overrides for the fields you need to pre-populate.
@@ -28,6 +28,7 @@ function createRequestContext(opts) {
28
28
  return {
29
29
  headersContext: null,
30
30
  dynamicUsageDetected: false,
31
+ invalidDynamicUsageError: null,
31
32
  pendingSetCookies: [],
32
33
  draftModeCookieHeader: null,
33
34
  phase: "render",
@@ -43,6 +44,7 @@ function createRequestContext(opts) {
43
44
  requestCache: /* @__PURE__ */ new WeakMap(),
44
45
  ssrContext: null,
45
46
  ssrHeadChildren: [],
47
+ rootParams: null,
46
48
  ...opts
47
49
  };
48
50
  }
@@ -1 +1 @@
1
- {"version":3,"file":"unified-request-context.js","names":[],"sources":["../../src/shims/unified-request-context.ts"],"sourcesContent":["/**\n * Unified per-request context backed by a single AsyncLocalStorage.\n *\n * Consolidates the 5–6 nested ALS scopes that previously wrapped every\n * App Router request (headers, navigation, cache-state, private-cache,\n * fetch-cache, execution-context) into one flat store.\n *\n * Each shim module checks `isInsideUnifiedScope()` and reads its sub-fields\n * from the unified store, falling back to its own standalone ALS when\n * outside (SSR environment, Pages Router, tests).\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type {\n CacheState,\n ExecutionContextLike,\n FetchCacheState,\n HeadState,\n I18nState,\n NavigationState,\n PrivateCacheState,\n RouterState,\n VinextHeadersShimState,\n} from \"./request-state-types.js\";\n\n// ---------------------------------------------------------------------------\n// Unified context shape\n// ---------------------------------------------------------------------------\n\n/**\n * Flat union of all per-request state previously spread across\n * VinextHeadersShimState, NavigationState, CacheState, PrivateCacheState,\n * FetchCacheState, and ExecutionContextLike.\n *\n * Each field group is documented with its source shim module.\n */\nexport type UnifiedRequestContext = {\n // ── request-context.ts ─────────────────────────────────────────────\n /** Cloudflare Workers ExecutionContext, or null on Node.js dev. */\n executionContext: ExecutionContextLike | null;\n\n // ── cache-for-request.ts ──────────────────────────────────────────\n /** Per-request cache for cacheForRequest(). Keyed by factory function reference. */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n requestCache: WeakMap<(...args: any[]) => any, unknown>;\n} & VinextHeadersShimState &\n I18nState &\n NavigationState &\n CacheState &\n PrivateCacheState &\n FetchCacheState &\n RouterState &\n HeadState;\n\n// ---------------------------------------------------------------------------\n// ALS setup — stored on globalThis via Symbol.for so all Vite environments\n// (RSC/SSR/client) share the same instance.\n// ---------------------------------------------------------------------------\n\nconst _ALS_KEY = Symbol.for(\"vinext.unifiedRequestContext.als\");\nconst _REQUEST_CONTEXT_ALS_KEY = Symbol.for(\"vinext.requestContext.als\");\nconst _g = globalThis as unknown as Record<PropertyKey, unknown>;\nconst _als = (_g[_ALS_KEY] ??=\n new AsyncLocalStorage<UnifiedRequestContext>()) as AsyncLocalStorage<UnifiedRequestContext>;\n\nfunction _getInheritedExecutionContext(): ExecutionContextLike | null {\n const unifiedStore = _als.getStore();\n if (unifiedStore) return unifiedStore.executionContext;\n\n const executionContextAls = _g[_REQUEST_CONTEXT_ALS_KEY] as\n | AsyncLocalStorage<ExecutionContextLike | null>\n | undefined;\n return executionContextAls?.getStore() ?? null;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Create a fresh `UnifiedRequestContext` with defaults for all fields.\n * Pass partial overrides for the fields you need to pre-populate.\n */\nexport function createRequestContext(opts?: Partial<UnifiedRequestContext>): UnifiedRequestContext {\n return {\n headersContext: null,\n dynamicUsageDetected: false,\n pendingSetCookies: [],\n draftModeCookieHeader: null,\n phase: \"render\",\n i18nContext: null,\n serverContext: null,\n serverInsertedHTMLCallbacks: [],\n requestScopedCacheLife: null,\n unstableCacheRevalidation: \"foreground\",\n _privateCache: null,\n currentRequestTags: [],\n currentFetchSoftTags: [],\n executionContext: _getInheritedExecutionContext(), // inherits from standalone ALS if present\n requestCache: new WeakMap(),\n ssrContext: null,\n ssrHeadChildren: [],\n ...opts,\n };\n}\n\n/**\n * Run `fn` within a unified request context scope.\n * All shim modules will read/write their state from `ctx` for the\n * duration of the call, including async continuations.\n */\nexport function runWithRequestContext<T>(\n ctx: UnifiedRequestContext,\n fn: () => Promise<T>,\n): Promise<T>;\nexport function runWithRequestContext<T>(\n ctx: UnifiedRequestContext,\n fn: () => T | Promise<T>,\n): T | Promise<T>;\nexport function runWithRequestContext<T>(\n ctx: UnifiedRequestContext,\n fn: () => T | Promise<T>,\n): T | Promise<T> {\n return _als.run(ctx, fn);\n}\n\n/**\n * Run `fn` in a nested unified scope derived from the current request context.\n * Used by legacy runWith* wrappers to reset or override one sub-state while\n * preserving proper async isolation for continuations created inside `fn`.\n * The child scope is a shallow clone of the parent store, so untouched fields\n * keep sharing their existing references while overridden slices can be reset.\n *\n * @internal\n */\nexport function runWithUnifiedStateMutation<T>(\n mutate: (ctx: UnifiedRequestContext) => void,\n fn: () => Promise<T>,\n): Promise<T>;\nexport function runWithUnifiedStateMutation<T>(\n mutate: (ctx: UnifiedRequestContext) => void,\n fn: () => T | Promise<T>,\n): T | Promise<T>;\nexport function runWithUnifiedStateMutation<T>(\n mutate: (ctx: UnifiedRequestContext) => void,\n fn: () => T | Promise<T>,\n): T | Promise<T> {\n const parentCtx = _als.getStore();\n if (!parentCtx) return fn();\n\n const childCtx = { ...parentCtx };\n // NOTE: This is a shallow clone. Array fields (pendingSetCookies,\n // serverInsertedHTMLCallbacks, currentRequestTags, ssrHeadChildren), the\n // _privateCache Map, requestCache WeakMap, and object fields (headersContext,\n // i18nContext, serverContext, ssrContext, executionContext,\n // requestScopedCacheLife) still share references with the parent until\n // replaced. requestCache is intentionally shared — nested scopes within\n // the same request should see the same cached values. The mutate\n // callback must replace those reference-typed slices (for example\n // `ctx.currentRequestTags = []`) rather than mutating them in-place (for\n // example `ctx.currentRequestTags.push(...)`) or the parent scope will\n // observe those changes too. Keep this enumeration in sync with\n // UnifiedRequestContext: when adding a new reference-typed field, add it\n // here too and verify callers still follow the replace-not-mutate rule.\n mutate(childCtx);\n return _als.run(childCtx, fn);\n}\n\n/**\n * Get the current unified request context.\n * Returns the ALS store when inside a `runWithRequestContext()` scope,\n * or a fresh detached context otherwise. Unlike the legacy per-shim fallback\n * singletons, this detached value is ephemeral — mutations do not persist\n * across calls. This is intentional to prevent state leakage outside request\n * scopes.\n *\n * Only direct callers observe this detached fallback. Shim `_getState()`\n * helpers should continue to gate on `isInsideUnifiedScope()` and fall back\n * to their standalone ALS/fallback singletons outside the unified scope.\n * If called inside a standalone `runWithExecutionContext()` scope, the\n * detached context still reflects that inherited `executionContext`.\n */\nexport function getRequestContext(): UnifiedRequestContext {\n return _als.getStore() ?? createRequestContext();\n}\n\n/**\n * Check whether the current execution is inside a `runWithRequestContext()` scope.\n * Shim modules use this to decide whether to read from the unified store\n * or fall back to their own standalone ALS.\n */\nexport function isInsideUnifiedScope(): boolean {\n return _als.getStore() != null;\n}\n"],"mappings":";;;;;;;;;;;;;AA2DA,MAAM,WAAW,OAAO,IAAI,mCAAmC;AAC/D,MAAM,2BAA2B,OAAO,IAAI,4BAA4B;AACxE,MAAM,KAAK;AACX,MAAM,OAAQ,GAAG,cACf,IAAI,mBAA0C;AAEhD,SAAS,gCAA6D;CACpE,MAAM,eAAe,KAAK,UAAU;AACpC,KAAI,aAAc,QAAO,aAAa;AAKtC,QAH4B,GAAG,2BAGH,UAAU,IAAI;;;;;;AAW5C,SAAgB,qBAAqB,MAA8D;AACjG,QAAO;EACL,gBAAgB;EAChB,sBAAsB;EACtB,mBAAmB,EAAE;EACrB,uBAAuB;EACvB,OAAO;EACP,aAAa;EACb,eAAe;EACf,6BAA6B,EAAE;EAC/B,wBAAwB;EACxB,2BAA2B;EAC3B,eAAe;EACf,oBAAoB,EAAE;EACtB,sBAAsB,EAAE;EACxB,kBAAkB,+BAA+B;EACjD,8BAAc,IAAI,SAAS;EAC3B,YAAY;EACZ,iBAAiB,EAAE;EACnB,GAAG;EACJ;;AAgBH,SAAgB,sBACd,KACA,IACgB;AAChB,QAAO,KAAK,IAAI,KAAK,GAAG;;AAoB1B,SAAgB,4BACd,QACA,IACgB;CAChB,MAAM,YAAY,KAAK,UAAU;AACjC,KAAI,CAAC,UAAW,QAAO,IAAI;CAE3B,MAAM,WAAW,EAAE,GAAG,WAAW;AAcjC,QAAO,SAAS;AAChB,QAAO,KAAK,IAAI,UAAU,GAAG;;;;;;;;;;;;;;;;AAiB/B,SAAgB,oBAA2C;AACzD,QAAO,KAAK,UAAU,IAAI,sBAAsB;;;;;;;AAQlD,SAAgB,uBAAgC;AAC9C,QAAO,KAAK,UAAU,IAAI"}
1
+ {"version":3,"file":"unified-request-context.js","names":[],"sources":["../../src/shims/unified-request-context.ts"],"sourcesContent":["/**\n * Unified per-request context backed by a single AsyncLocalStorage.\n *\n * Consolidates the 5–6 nested ALS scopes that previously wrapped every\n * App Router request (headers, navigation, cache-state, private-cache,\n * fetch-cache, execution-context) into one flat store.\n *\n * Each shim module checks `isInsideUnifiedScope()` and reads its sub-fields\n * from the unified store, falling back to its own standalone ALS when\n * outside (SSR environment, Pages Router, tests).\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type {\n CacheState,\n ExecutionContextLike,\n FetchCacheState,\n HeadState,\n I18nState,\n NavigationState,\n PrivateCacheState,\n RouterState,\n RootParamsState,\n VinextHeadersShimState,\n} from \"./request-state-types.js\";\n\n// ---------------------------------------------------------------------------\n// Unified context shape\n// ---------------------------------------------------------------------------\n\n/**\n * Flat union of all per-request state previously spread across\n * VinextHeadersShimState, NavigationState, CacheState, PrivateCacheState,\n * FetchCacheState, and ExecutionContextLike.\n *\n * Each field group is documented with its source shim module.\n */\nexport type UnifiedRequestContext = {\n // ── request-context.ts ─────────────────────────────────────────────\n /** Cloudflare Workers ExecutionContext, or null on Node.js dev. */\n executionContext: ExecutionContextLike | null;\n\n // ── cache-for-request.ts ──────────────────────────────────────────\n /** Per-request cache for cacheForRequest(). Keyed by factory function reference. */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n requestCache: WeakMap<(...args: any[]) => any, unknown>;\n} & VinextHeadersShimState &\n I18nState &\n NavigationState &\n CacheState &\n PrivateCacheState &\n FetchCacheState &\n RouterState &\n HeadState &\n RootParamsState;\n\n// ---------------------------------------------------------------------------\n// ALS setup — stored on globalThis via Symbol.for so all Vite environments\n// (RSC/SSR/client) share the same instance.\n// ---------------------------------------------------------------------------\n\nconst _ALS_KEY = Symbol.for(\"vinext.unifiedRequestContext.als\");\nconst _REQUEST_CONTEXT_ALS_KEY = Symbol.for(\"vinext.requestContext.als\");\nconst _g = globalThis as unknown as Record<PropertyKey, unknown>;\nconst _als = (_g[_ALS_KEY] ??=\n new AsyncLocalStorage<UnifiedRequestContext>()) as AsyncLocalStorage<UnifiedRequestContext>;\n\nfunction _getInheritedExecutionContext(): ExecutionContextLike | null {\n const unifiedStore = _als.getStore();\n if (unifiedStore) return unifiedStore.executionContext;\n\n const executionContextAls = _g[_REQUEST_CONTEXT_ALS_KEY] as\n | AsyncLocalStorage<ExecutionContextLike | null>\n | undefined;\n return executionContextAls?.getStore() ?? null;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Create a fresh `UnifiedRequestContext` with defaults for all fields.\n * Pass partial overrides for the fields you need to pre-populate.\n */\nexport function createRequestContext(opts?: Partial<UnifiedRequestContext>): UnifiedRequestContext {\n return {\n headersContext: null,\n dynamicUsageDetected: false,\n invalidDynamicUsageError: null,\n pendingSetCookies: [],\n draftModeCookieHeader: null,\n phase: \"render\",\n i18nContext: null,\n serverContext: null,\n serverInsertedHTMLCallbacks: [],\n requestScopedCacheLife: null,\n unstableCacheRevalidation: \"foreground\",\n _privateCache: null,\n currentRequestTags: [],\n currentFetchSoftTags: [],\n executionContext: _getInheritedExecutionContext(), // inherits from standalone ALS if present\n requestCache: new WeakMap(),\n ssrContext: null,\n ssrHeadChildren: [],\n rootParams: null,\n ...opts,\n };\n}\n\n/**\n * Run `fn` within a unified request context scope.\n * All shim modules will read/write their state from `ctx` for the\n * duration of the call, including async continuations.\n */\nexport function runWithRequestContext<T>(\n ctx: UnifiedRequestContext,\n fn: () => Promise<T>,\n): Promise<T>;\nexport function runWithRequestContext<T>(\n ctx: UnifiedRequestContext,\n fn: () => T | Promise<T>,\n): T | Promise<T>;\nexport function runWithRequestContext<T>(\n ctx: UnifiedRequestContext,\n fn: () => T | Promise<T>,\n): T | Promise<T> {\n return _als.run(ctx, fn);\n}\n\n/**\n * Run `fn` in a nested unified scope derived from the current request context.\n * Used by legacy runWith* wrappers to reset or override one sub-state while\n * preserving proper async isolation for continuations created inside `fn`.\n * The child scope is a shallow clone of the parent store, so untouched fields\n * keep sharing their existing references while overridden slices can be reset.\n *\n * @internal\n */\nexport function runWithUnifiedStateMutation<T>(\n mutate: (ctx: UnifiedRequestContext) => void,\n fn: () => Promise<T>,\n): Promise<T>;\nexport function runWithUnifiedStateMutation<T>(\n mutate: (ctx: UnifiedRequestContext) => void,\n fn: () => T | Promise<T>,\n): T | Promise<T>;\nexport function runWithUnifiedStateMutation<T>(\n mutate: (ctx: UnifiedRequestContext) => void,\n fn: () => T | Promise<T>,\n): T | Promise<T> {\n const parentCtx = _als.getStore();\n if (!parentCtx) return fn();\n\n const childCtx = { ...parentCtx };\n // NOTE: This is a shallow clone. Array fields (pendingSetCookies,\n // serverInsertedHTMLCallbacks, currentRequestTags, ssrHeadChildren), the\n // _privateCache Map, requestCache WeakMap, and object fields (headersContext,\n // i18nContext, serverContext, ssrContext, executionContext,\n // requestScopedCacheLife) still share references with the parent until\n // replaced. requestCache is intentionally shared — nested scopes within\n // the same request should see the same cached values. The mutate\n // callback must replace those reference-typed slices (for example\n // `ctx.currentRequestTags = []`) rather than mutating them in-place (for\n // example `ctx.currentRequestTags.push(...)`) or the parent scope will\n // observe those changes too. Keep this enumeration in sync with\n // UnifiedRequestContext: when adding a new reference-typed field, add it\n // here too and verify callers still follow the replace-not-mutate rule.\n mutate(childCtx);\n return _als.run(childCtx, fn);\n}\n\n/**\n * Get the current unified request context.\n * Returns the ALS store when inside a `runWithRequestContext()` scope,\n * or a fresh detached context otherwise. Unlike the legacy per-shim fallback\n * singletons, this detached value is ephemeral — mutations do not persist\n * across calls. This is intentional to prevent state leakage outside request\n * scopes.\n *\n * Only direct callers observe this detached fallback. Shim `_getState()`\n * helpers should continue to gate on `isInsideUnifiedScope()` and fall back\n * to their standalone ALS/fallback singletons outside the unified scope.\n * If called inside a standalone `runWithExecutionContext()` scope, the\n * detached context still reflects that inherited `executionContext`.\n */\nexport function getRequestContext(): UnifiedRequestContext {\n return _als.getStore() ?? createRequestContext();\n}\n\n/**\n * Check whether the current execution is inside a `runWithRequestContext()` scope.\n * Shim modules use this to decide whether to read from the unified store\n * or fall back to their own standalone ALS.\n */\nexport function isInsideUnifiedScope(): boolean {\n return _als.getStore() != null;\n}\n"],"mappings":";;;;;;;;;;;;;AA6DA,MAAM,WAAW,OAAO,IAAI,mCAAmC;AAC/D,MAAM,2BAA2B,OAAO,IAAI,4BAA4B;AACxE,MAAM,KAAK;AACX,MAAM,OAAQ,GAAG,cACf,IAAI,mBAA0C;AAEhD,SAAS,gCAA6D;CACpE,MAAM,eAAe,KAAK,UAAU;AACpC,KAAI,aAAc,QAAO,aAAa;AAKtC,QAH4B,GAAG,2BAGH,UAAU,IAAI;;;;;;AAW5C,SAAgB,qBAAqB,MAA8D;AACjG,QAAO;EACL,gBAAgB;EAChB,sBAAsB;EACtB,0BAA0B;EAC1B,mBAAmB,EAAE;EACrB,uBAAuB;EACvB,OAAO;EACP,aAAa;EACb,eAAe;EACf,6BAA6B,EAAE;EAC/B,wBAAwB;EACxB,2BAA2B;EAC3B,eAAe;EACf,oBAAoB,EAAE;EACtB,sBAAsB,EAAE;EACxB,kBAAkB,+BAA+B;EACjD,8BAAc,IAAI,SAAS;EAC3B,YAAY;EACZ,iBAAiB,EAAE;EACnB,YAAY;EACZ,GAAG;EACJ;;AAgBH,SAAgB,sBACd,KACA,IACgB;AAChB,QAAO,KAAK,IAAI,KAAK,GAAG;;AAoB1B,SAAgB,4BACd,QACA,IACgB;CAChB,MAAM,YAAY,KAAK,UAAU;AACjC,KAAI,CAAC,UAAW,QAAO,IAAI;CAE3B,MAAM,WAAW,EAAE,GAAG,WAAW;AAcjC,QAAO,SAAS;AAChB,QAAO,KAAK,IAAI,UAAU,GAAG;;;;;;;;;;;;;;;;AAiB/B,SAAgB,oBAA2C;AACzD,QAAO,KAAK,UAAU,IAAI,sBAAsB;;;;;;;AAQlD,SAAgB,uBAAgC;AAC9C,QAAO,KAAK,UAAU,IAAI"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vinext",
3
- "version": "0.0.45",
3
+ "version": "0.0.46",
4
4
  "description": "Run Next.js apps on Vite. Drop-in replacement for the next CLI.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -41,6 +41,10 @@
41
41
  "types": "./dist/server/image-optimization.d.ts",
42
42
  "import": "./dist/server/image-optimization.js"
43
43
  },
44
+ "./server/request-pipeline": {
45
+ "types": "./dist/server/request-pipeline.d.ts",
46
+ "import": "./dist/server/request-pipeline.js"
47
+ },
44
48
  "./server/app-router-entry": {
45
49
  "types": "./dist/server/app-router-entry.d.ts",
46
50
  "import": "./dist/server/app-router-entry.js"
@@ -57,6 +61,7 @@
57
61
  "dependencies": {
58
62
  "@unpic/react": "^1.0.2",
59
63
  "@vercel/og": "^0.8.6",
64
+ "image-size": "2.0.2",
60
65
  "magic-string": "^0.30.21",
61
66
  "vite-plugin-commonjs": "^0.10.4",
62
67
  "vite-tsconfig-paths": "^6.1.1"
@@ -1,54 +0,0 @@
1
- //#region src/server/middleware-codegen.d.ts
2
- /**
3
- * Shared middleware matching code generator.
4
- *
5
- * Both the App Router RSC entry (entries/app-rsc-entry.ts) and the Pages Router
6
- * production entry (index.ts) need middleware matching logic inlined as
7
- * generated JavaScript strings. This module provides a single source of
8
- * truth to prevent the implementations from diverging.
9
- *
10
- * The regex detection guard (checking for "(" or "\\") is critical.
11
- * Without it, dot-escaping corrupts regex patterns like
12
- * /((?!api|_next).*), causing middleware to silently skip paths.
13
- */
14
- /**
15
- * Returns the generated JavaScript source for `__isSafeRegex` and `__safeRegExp`.
16
- *
17
- * @param style - "modern" emits const/let (for RSC entry), "es5" emits var (for prod entry)
18
- */
19
- declare function generateSafeRegExpCode(style?: "modern" | "es5"): string;
20
- /**
21
- * Returns the generated JavaScript source for `__normalizePath`.
22
- *
23
- * This must be kept in sync with `normalizePath()` in `normalize-path.ts`.
24
- * The inline version is used by codegen entries that can't import modules.
25
- *
26
- * @param style - "modern" emits const/let, "es5" emits var
27
- */
28
- declare function generateNormalizePathCode(style?: "modern" | "es5"): string;
29
- /**
30
- * Returns generated JavaScript source for route-path normalization that
31
- * preserves encoded path delimiters within a single segment.
32
- *
33
- * This mirrors decodeRouteSegment()/normalizePathnameForRouteMatch() in
34
- * routing/utils.ts so "%5F" becomes "_" while "%2F" remains "%2F".
35
- *
36
- * @param style - "modern" emits const/let, "es5" emits var
37
- */
38
- declare function generateRouteMatchNormalizationCode(style?: "modern" | "es5"): string;
39
- /**
40
- * Returns the generated JavaScript source for middleware pattern matching.
41
- *
42
- * This includes:
43
- * - `matchMiddlewarePattern(pathname, pattern)` — matches a single pattern
44
- * - `matchesMiddleware(pathname, matcher, request, i18nConfig)` — matches the full matcher config
45
- *
46
- * The generated code depends on `__safeRegExp` being defined in the same scope
47
- * (use `generateSafeRegExpCode` to emit it).
48
- *
49
- * @param style - "modern" emits const/let/arrow functions, "es5" emits var/function
50
- */
51
- declare function generateMiddlewareMatcherCode(style?: "modern" | "es5"): string;
52
- //#endregion
53
- export { generateMiddlewareMatcherCode, generateNormalizePathCode, generateRouteMatchNormalizationCode, generateSafeRegExpCode };
54
- //# sourceMappingURL=middleware-codegen.d.ts.map