vinext 1.0.0-beta.1 → 1.0.0-beta.3

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 (234) hide show
  1. package/README.md +10 -10
  2. package/dist/build/client-build-config.js +8 -1
  3. package/dist/build/report.d.ts +8 -1
  4. package/dist/build/report.js +12 -2
  5. package/dist/check.js +19 -2
  6. package/dist/cli.js +3 -2
  7. package/dist/config/config-matchers.d.ts +13 -37
  8. package/dist/config/config-matchers.js +35 -122
  9. package/dist/config/next-config.d.ts +15 -5
  10. package/dist/config/next-config.js +7 -1
  11. package/dist/config/request-context.d.ts +14 -0
  12. package/dist/config/request-context.js +26 -0
  13. package/dist/entries/app-browser-entry.d.ts +4 -10
  14. package/dist/entries/app-browser-entry.js +20 -4
  15. package/dist/entries/app-rsc-entry.js +30 -9
  16. package/dist/entries/app-rsc-manifest.js +36 -0
  17. package/dist/entries/pages-client-entry.js +0 -1
  18. package/dist/entries/pages-server-entry.js +13 -5
  19. package/dist/index.js +194 -101
  20. package/dist/init-cloudflare.d.ts +3 -1
  21. package/dist/init-cloudflare.js +59 -5
  22. package/dist/init.d.ts +6 -4
  23. package/dist/init.js +20 -22
  24. package/dist/plugins/extensionless-dynamic-import.js +23 -18
  25. package/dist/plugins/ignore-dynamic-requests.js +3 -1
  26. package/dist/plugins/import-meta-url.js +17 -6
  27. package/dist/plugins/og-assets.js +1 -1
  28. package/dist/plugins/require-context.js +20 -15
  29. package/dist/plugins/transform-cache.d.ts +19 -0
  30. package/dist/plugins/transform-cache.js +36 -0
  31. package/dist/routing/app-route-graph.d.ts +27 -11
  32. package/dist/routing/app-route-graph.js +158 -22
  33. package/dist/routing/app-router.js +12 -6
  34. package/dist/routing/file-matcher.d.ts +11 -22
  35. package/dist/routing/file-matcher.js +21 -33
  36. package/dist/routing/pages-router.js +23 -29
  37. package/dist/routing/route-matching.d.ts +14 -1
  38. package/dist/routing/route-matching.js +13 -1
  39. package/dist/routing/route-pattern.d.ts +2 -1
  40. package/dist/routing/route-pattern.js +7 -4
  41. package/dist/routing/route-trie.d.ts +5 -1
  42. package/dist/routing/route-trie.js +5 -2
  43. package/dist/server/api-handler.d.ts +2 -0
  44. package/dist/server/api-handler.js +3 -3
  45. package/dist/server/app-browser-entry.js +110 -37
  46. package/dist/server/app-browser-history-controller.d.ts +1 -1
  47. package/dist/server/app-browser-history-controller.js +3 -3
  48. package/dist/server/app-browser-navigation-controller.d.ts +23 -21
  49. package/dist/server/app-browser-navigation-controller.js +2 -2
  50. package/dist/server/app-browser-state.js +1 -1
  51. package/dist/server/app-browser-visible-commit.js +1 -1
  52. package/dist/server/app-fallback-renderer.d.ts +3 -0
  53. package/dist/server/app-fallback-renderer.js +4 -2
  54. package/dist/server/app-middleware.js +2 -1
  55. package/dist/server/app-page-boundary-render.d.ts +12 -1
  56. package/dist/server/app-page-boundary-render.js +84 -2
  57. package/dist/server/app-page-cache-finalizer.d.ts +1 -1
  58. package/dist/server/app-page-cache-finalizer.js +1 -1
  59. package/dist/server/app-page-cache.d.ts +2 -2
  60. package/dist/server/app-page-cache.js +16 -2
  61. package/dist/server/app-page-dispatch.d.ts +19 -2
  62. package/dist/server/app-page-dispatch.js +45 -23
  63. package/dist/server/app-page-element-builder.d.ts +9 -2
  64. package/dist/server/app-page-element-builder.js +144 -33
  65. package/dist/server/app-page-head.d.ts +56 -4
  66. package/dist/server/app-page-head.js +216 -85
  67. package/dist/server/app-page-http-access-fallback-metadata.d.ts +29 -0
  68. package/dist/server/app-page-http-access-fallback-metadata.js +114 -0
  69. package/dist/server/app-page-probe.d.ts +4 -0
  70. package/dist/server/app-page-probe.js +6 -2
  71. package/dist/server/app-page-render.d.ts +2 -2
  72. package/dist/server/app-page-render.js +1 -1
  73. package/dist/server/app-page-request.d.ts +15 -0
  74. package/dist/server/app-page-request.js +134 -14
  75. package/dist/server/app-page-response.js +1 -1
  76. package/dist/server/app-page-route-wiring.d.ts +16 -0
  77. package/dist/server/app-page-route-wiring.js +254 -52
  78. package/dist/server/app-pages-bridge.d.ts +1 -1
  79. package/dist/server/app-pages-bridge.js +2 -1
  80. package/dist/server/app-post-middleware-context.d.ts +1 -1
  81. package/dist/server/app-post-middleware-context.js +1 -1
  82. package/dist/server/app-route-handler-cache.js +4 -0
  83. package/dist/server/app-route-handler-dispatch.js +40 -20
  84. package/dist/server/app-route-handler-execution.d.ts +6 -1
  85. package/dist/server/app-route-handler-execution.js +42 -16
  86. package/dist/server/app-route-handler-policy.d.ts +2 -0
  87. package/dist/server/app-route-handler-policy.js +3 -3
  88. package/dist/server/app-route-handler-response.js +1 -1
  89. package/dist/server/app-route-module-loader.d.ts +9 -1
  90. package/dist/server/app-route-module-loader.js +4 -0
  91. package/dist/server/app-router-entry.js +6 -3
  92. package/dist/server/app-rsc-cache-busting.d.ts +1 -1
  93. package/dist/server/app-rsc-errors.d.ts +1 -1
  94. package/dist/server/app-rsc-errors.js +22 -2
  95. package/dist/server/app-rsc-handler.d.ts +10 -5
  96. package/dist/server/app-rsc-handler.js +73 -33
  97. package/dist/server/app-rsc-request-normalization.d.ts +3 -2
  98. package/dist/server/app-rsc-request-normalization.js +8 -2
  99. package/dist/server/app-rsc-response-finalizer.d.ts +2 -2
  100. package/dist/server/app-rsc-response-finalizer.js +5 -11
  101. package/dist/server/app-rsc-route-matching.d.ts +29 -0
  102. package/dist/server/app-rsc-route-matching.js +93 -11
  103. package/dist/server/app-segment-config.js +13 -3
  104. package/dist/server/app-server-action-execution.d.ts +3 -1
  105. package/dist/server/app-server-action-execution.js +9 -7
  106. package/dist/server/app-ssr-entry.js +6 -6
  107. package/dist/server/app-ssr-stream.d.ts +1 -7
  108. package/dist/server/app-ssr-stream.js +2 -10
  109. package/dist/server/cache-control.d.ts +2 -2
  110. package/dist/server/cache-control.js +2 -1
  111. package/dist/server/config-headers.d.ts +24 -0
  112. package/dist/server/config-headers.js +52 -0
  113. package/dist/server/dev-initial-server-error.d.ts +1 -1
  114. package/dist/server/dev-server.d.ts +3 -1
  115. package/dist/server/dev-server.js +170 -321
  116. package/dist/server/headers.d.ts +2 -2
  117. package/dist/server/headers.js +4 -3
  118. package/dist/server/isr-cache.d.ts +11 -34
  119. package/dist/server/isr-cache.js +33 -43
  120. package/dist/server/isr-decision.d.ts +2 -2
  121. package/dist/server/middleware-matcher-pattern.d.ts +22 -0
  122. package/dist/server/middleware-matcher-pattern.js +219 -0
  123. package/dist/server/middleware-matcher.d.ts +2 -7
  124. package/dist/server/middleware-matcher.js +13 -60
  125. package/dist/server/middleware-path-to-regexp.d.ts +14 -0
  126. package/dist/server/middleware-path-to-regexp.js +228 -0
  127. package/dist/server/middleware-runtime.js +4 -3
  128. package/dist/server/middleware.d.ts +1 -1
  129. package/dist/server/middleware.js +2 -1
  130. package/dist/server/pages-api-route.d.ts +2 -0
  131. package/dist/server/pages-api-route.js +4 -1
  132. package/dist/server/pages-data-route.d.ts +11 -1
  133. package/dist/server/pages-data-route.js +16 -1
  134. package/dist/server/pages-dev-hydration.js +0 -1
  135. package/dist/server/pages-get-initial-props.d.ts +16 -3
  136. package/dist/server/pages-get-initial-props.js +17 -10
  137. package/dist/server/pages-i18n.js +64 -16
  138. package/dist/server/pages-node-compat.d.ts +2 -0
  139. package/dist/server/pages-node-compat.js +7 -3
  140. package/dist/server/pages-page-data.d.ts +64 -10
  141. package/dist/server/pages-page-data.js +349 -80
  142. package/dist/server/pages-page-handler.d.ts +9 -3
  143. package/dist/server/pages-page-handler.js +131 -36
  144. package/dist/server/pages-page-response.d.ts +5 -3
  145. package/dist/server/pages-page-response.js +24 -27
  146. package/dist/server/pages-readiness.d.ts +3 -3
  147. package/dist/server/pages-request-pipeline.d.ts +8 -0
  148. package/dist/server/pages-request-pipeline.js +30 -12
  149. package/dist/server/pages-revalidate.d.ts +1 -1
  150. package/dist/server/pages-revalidate.js +54 -8
  151. package/dist/server/pages-router-entry.d.ts +1 -0
  152. package/dist/server/pages-router-entry.js +16 -4
  153. package/dist/server/prerender-route-params.js +2 -2
  154. package/dist/server/prod-server.d.ts +3 -5
  155. package/dist/server/prod-server.js +72 -35
  156. package/dist/server/request-pipeline.d.ts +15 -29
  157. package/dist/server/request-pipeline.js +24 -59
  158. package/dist/server/revalidation-host.d.ts +11 -0
  159. package/dist/server/revalidation-host.js +19 -0
  160. package/dist/server/rsc-stream-hints.js +122 -18
  161. package/dist/server/worker-revalidation-context.d.ts +13 -0
  162. package/dist/server/worker-revalidation-context.js +29 -0
  163. package/dist/shims/app.d.ts +1 -1
  164. package/dist/shims/cache-handler.d.ts +1 -1
  165. package/dist/shims/cache-handler.js +10 -7
  166. package/dist/shims/cache-request-state.d.ts +27 -1
  167. package/dist/shims/cache-request-state.js +60 -1
  168. package/dist/shims/cache-runtime.d.ts +18 -1
  169. package/dist/shims/cache-runtime.js +26 -8
  170. package/dist/shims/cache.d.ts +5 -5
  171. package/dist/shims/cache.js +27 -11
  172. package/dist/shims/document.d.ts +42 -83
  173. package/dist/shims/document.js +62 -53
  174. package/dist/shims/dynamic.d.ts +5 -25
  175. package/dist/shims/dynamic.js +29 -8
  176. package/dist/shims/error.d.ts +1 -1
  177. package/dist/shims/error.js +2 -2
  178. package/dist/shims/fetch-cache.js +13 -4
  179. package/dist/shims/font-google-base.d.ts +11 -4
  180. package/dist/shims/font-google-base.js +17 -8
  181. package/dist/shims/font-local.d.ts +10 -3
  182. package/dist/shims/font-local.js +41 -10
  183. package/dist/shims/head.d.ts +13 -2
  184. package/dist/shims/head.js +3 -3
  185. package/dist/shims/headers.d.ts +37 -43
  186. package/dist/shims/headers.js +183 -74
  187. package/dist/shims/image.d.ts +27 -37
  188. package/dist/shims/image.js +21 -14
  189. package/dist/shims/internal/cookie-serialize.d.ts +12 -9
  190. package/dist/shims/internal/cookie-serialize.js +10 -7
  191. package/dist/shims/internal/hybrid-client-route-owner.js +3 -1
  192. package/dist/shims/internal/interpolate-as.d.ts +15 -1
  193. package/dist/shims/internal/interpolate-as.js +27 -2
  194. package/dist/shims/internal/utils.d.ts +3 -3
  195. package/dist/shims/legacy-image.d.ts +3 -37
  196. package/dist/shims/legacy-image.js +6 -16
  197. package/dist/shims/link.d.ts +15 -22
  198. package/dist/shims/link.js +34 -13
  199. package/dist/shims/metadata.d.ts +7 -17
  200. package/dist/shims/metadata.js +74 -24
  201. package/dist/shims/navigation-context-state.d.ts +1 -1
  202. package/dist/shims/navigation.d.ts +7 -3
  203. package/dist/shims/navigation.js +25 -14
  204. package/dist/shims/navigation.react-server.js +1 -1
  205. package/dist/shims/next-shims-augmentations.d.ts +1 -0
  206. package/dist/shims/next-shims-public.d.ts +1 -0
  207. package/dist/shims/public-shim-map.json.js +103 -0
  208. package/dist/shims/readonly-url-search-params.d.ts +3 -3
  209. package/dist/shims/readonly-url-search-params.js +3 -3
  210. package/dist/shims/request-context.d.ts +4 -1
  211. package/dist/shims/request-state-types.d.ts +1 -1
  212. package/dist/shims/router.d.ts +55 -21
  213. package/dist/shims/router.js +180 -44
  214. package/dist/shims/script.d.ts +6 -10
  215. package/dist/shims/script.js +7 -4
  216. package/dist/shims/server.d.ts +50 -26
  217. package/dist/shims/server.js +193 -55
  218. package/dist/shims/unified-request-context.d.ts +22 -3
  219. package/dist/shims/unified-request-context.js +84 -1
  220. package/dist/shims/url-safety.d.ts +1 -1
  221. package/dist/shims/url-safety.js +2 -2
  222. package/dist/typegen.d.ts +8 -2
  223. package/dist/typegen.js +76 -15
  224. package/dist/utils/cache-control-metadata.d.ts +2 -1
  225. package/dist/utils/cache-control-metadata.js +5 -1
  226. package/dist/utils/domain-locale.d.ts +2 -2
  227. package/dist/utils/external-url.d.ts +5 -0
  228. package/dist/utils/external-url.js +7 -0
  229. package/dist/utils/html-limited-bots.js +1 -1
  230. package/dist/utils/protocol-headers.d.ts +7 -1
  231. package/dist/utils/protocol-headers.js +7 -1
  232. package/dist/utils/regex-safety.d.ts +8 -0
  233. package/dist/utils/regex-safety.js +737 -0
  234. package/package.json +13 -2
@@ -0,0 +1,228 @@
1
+ //#region src/server/middleware-path-to-regexp.ts
2
+ function lexer(value) {
3
+ const tokens = [];
4
+ let index = 0;
5
+ while (index < value.length) {
6
+ const character = value[index];
7
+ if (character === "*" || character === "+" || character === "?") {
8
+ tokens.push({
9
+ type: "MODIFIER",
10
+ index,
11
+ value: value[index++]
12
+ });
13
+ continue;
14
+ }
15
+ if (character === "\\") {
16
+ tokens.push({
17
+ type: "ESCAPED_CHAR",
18
+ index: index++,
19
+ value: value[index++]
20
+ });
21
+ continue;
22
+ }
23
+ if (character === "{") {
24
+ tokens.push({
25
+ type: "OPEN",
26
+ index,
27
+ value: value[index++]
28
+ });
29
+ continue;
30
+ }
31
+ if (character === "}") {
32
+ tokens.push({
33
+ type: "CLOSE",
34
+ index,
35
+ value: value[index++]
36
+ });
37
+ continue;
38
+ }
39
+ if (character === ":") {
40
+ let name = "";
41
+ let nameEnd = index + 1;
42
+ while (nameEnd < value.length) {
43
+ const code = value.charCodeAt(nameEnd);
44
+ if (code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122 || code === 95) {
45
+ name += value[nameEnd++];
46
+ continue;
47
+ }
48
+ break;
49
+ }
50
+ if (!name) throw new TypeError(`Missing parameter name at ${index}`);
51
+ tokens.push({
52
+ type: "NAME",
53
+ index,
54
+ value: name
55
+ });
56
+ index = nameEnd;
57
+ continue;
58
+ }
59
+ if (character === "(") {
60
+ let depth = 1;
61
+ let pattern = "";
62
+ let patternEnd = index + 1;
63
+ if (value[patternEnd] === "?") throw new TypeError(`Pattern cannot start with "?" at ${patternEnd}`);
64
+ while (patternEnd < value.length) {
65
+ if (value[patternEnd] === "\\") {
66
+ pattern += value[patternEnd++] + value[patternEnd++];
67
+ continue;
68
+ }
69
+ if (value[patternEnd] === ")") {
70
+ depth--;
71
+ if (depth === 0) {
72
+ patternEnd++;
73
+ break;
74
+ }
75
+ } else if (value[patternEnd] === "(") {
76
+ depth++;
77
+ if (value[patternEnd + 1] !== "?") throw new TypeError(`Capturing groups are not allowed at ${patternEnd}`);
78
+ }
79
+ pattern += value[patternEnd++];
80
+ }
81
+ if (depth) throw new TypeError(`Unbalanced pattern at ${index}`);
82
+ if (!pattern) throw new TypeError(`Missing pattern at ${index}`);
83
+ tokens.push({
84
+ type: "PATTERN",
85
+ index,
86
+ value: pattern
87
+ });
88
+ index = patternEnd;
89
+ continue;
90
+ }
91
+ tokens.push({
92
+ type: "CHAR",
93
+ index,
94
+ value: value[index++]
95
+ });
96
+ }
97
+ tokens.push({
98
+ type: "END",
99
+ index,
100
+ value: ""
101
+ });
102
+ return tokens;
103
+ }
104
+ function parseMiddlewarePath(value) {
105
+ const tokens = lexer(value);
106
+ const result = [];
107
+ const prefixes = "./";
108
+ const delimiter = "/#?";
109
+ let key = 0;
110
+ let index = 0;
111
+ let path = "";
112
+ const tryConsume = (type) => {
113
+ if (index < tokens.length && tokens[index].type === type) return tokens[index++].value;
114
+ };
115
+ const mustConsume = (type) => {
116
+ const consumed = tryConsume(type);
117
+ if (consumed !== void 0) return consumed;
118
+ const next = tokens[index];
119
+ throw new TypeError(`Unexpected ${next.type} at ${next.index}, expected ${type}`);
120
+ };
121
+ const consumeText = () => {
122
+ let text = "";
123
+ let consumed;
124
+ while ((consumed = tryConsume("CHAR") ?? tryConsume("ESCAPED_CHAR")) !== void 0) text += consumed;
125
+ return text;
126
+ };
127
+ const containsDelimiter = (text) => {
128
+ for (const character of delimiter) if (text.includes(character)) return true;
129
+ return false;
130
+ };
131
+ const defaultPattern = (prefix) => {
132
+ const previous = result[result.length - 1];
133
+ const previousText = prefix || (typeof previous === "string" ? previous : "");
134
+ if (previous && !previousText) {
135
+ const name = typeof previous === "string" ? previous : previous.name;
136
+ throw new TypeError(`Must have text between two parameters, missing text after "${name}"`);
137
+ }
138
+ if (!previousText || containsDelimiter(previousText)) return "[^\\/#\\?]+?";
139
+ return `(?:(?!${escapeRegex(previousText)})[^\\/#\\?])+?`;
140
+ };
141
+ while (index < tokens.length) {
142
+ const character = tryConsume("CHAR");
143
+ const name = tryConsume("NAME");
144
+ const pattern = tryConsume("PATTERN");
145
+ if (name !== void 0 || pattern !== void 0) {
146
+ let prefix = character ?? "";
147
+ if (!prefixes.includes(prefix)) {
148
+ path += prefix;
149
+ prefix = "";
150
+ }
151
+ if (path) {
152
+ result.push(path);
153
+ path = "";
154
+ }
155
+ result.push({
156
+ name: name ?? key++,
157
+ prefix,
158
+ suffix: "",
159
+ pattern: pattern ?? defaultPattern(prefix),
160
+ modifier: tryConsume("MODIFIER") ?? ""
161
+ });
162
+ continue;
163
+ }
164
+ const text = character ?? tryConsume("ESCAPED_CHAR");
165
+ if (text !== void 0) {
166
+ path += text;
167
+ continue;
168
+ }
169
+ if (path) {
170
+ result.push(path);
171
+ path = "";
172
+ }
173
+ if (tryConsume("OPEN") !== void 0) {
174
+ const prefix = consumeText();
175
+ const groupName = tryConsume("NAME") ?? "";
176
+ const groupPattern = tryConsume("PATTERN") ?? "";
177
+ const suffix = consumeText();
178
+ mustConsume("CLOSE");
179
+ result.push({
180
+ name: groupName || (groupPattern ? key++ : ""),
181
+ pattern: groupName && !groupPattern ? defaultPattern(prefix) : groupPattern,
182
+ prefix,
183
+ suffix,
184
+ modifier: tryConsume("MODIFIER") ?? ""
185
+ });
186
+ continue;
187
+ }
188
+ mustConsume("END");
189
+ }
190
+ return result;
191
+ }
192
+ function escapeRegex(value) {
193
+ return value.replace(/([.+*?=^!:${}()[\]|/\\])/g, "\\$1");
194
+ }
195
+ function normalizeMiddlewarePathTokens(tokens) {
196
+ return tokens.map((token) => {
197
+ if (typeof token === "object" && (token.modifier === "*" || token.modifier === "+") && token.prefix === "" && token.suffix === "") return {
198
+ ...token,
199
+ prefix: "/"
200
+ };
201
+ return token;
202
+ });
203
+ }
204
+ function middlewarePathTokensToRegExp(tokens) {
205
+ const delimiterRegex = `[${escapeRegex("/#?")}]`;
206
+ let route = "^";
207
+ for (const token of tokens) {
208
+ if (typeof token === "string") {
209
+ route += escapeRegex(token);
210
+ continue;
211
+ }
212
+ const prefix = escapeRegex(token.prefix);
213
+ const suffix = escapeRegex(token.suffix);
214
+ if (token.pattern) if (prefix || suffix) if (token.modifier === "+" || token.modifier === "*") {
215
+ const optional = token.modifier === "*" ? "?" : "";
216
+ route += `(?:${prefix}((?:${token.pattern})(?:${suffix}${prefix}(?:${token.pattern}))*)${suffix})${optional}`;
217
+ } else route += `(?:${prefix}(${token.pattern})${suffix})${token.modifier}`;
218
+ else {
219
+ if (token.modifier === "+" || token.modifier === "*") throw new TypeError(`Can not repeat "${token.name}" without a prefix and suffix`);
220
+ route += `(${token.pattern})${token.modifier}`;
221
+ }
222
+ else route += `(?:${prefix}${suffix})${token.modifier}`;
223
+ }
224
+ route += `${delimiterRegex}?$`;
225
+ return new RegExp(route, "i");
226
+ }
227
+ //#endregion
228
+ export { middlewarePathTokensToRegExp, normalizeMiddlewarePathTokens, parseMiddlewarePath };
@@ -112,10 +112,11 @@ function resolveMiddlewarePathname(request) {
112
112
  return badRequestResponse();
113
113
  }
114
114
  }
115
- function createNextRequest(request, normalizedPathname, i18nConfig, basePath, trailingSlash, hadBasePath) {
115
+ function createNextRequest(request, i18nConfig, basePath, trailingSlash, hadBasePath) {
116
116
  const url = new URL(request.url);
117
117
  let mwRequest = request.body && !request.bodyUsed ? request.clone() : request;
118
- const mwPathname = basePath && hadBasePath ? addBasePathToPathname(normalizedPathname, basePath) : normalizedPathname;
118
+ const requestPathname = url.pathname;
119
+ const mwPathname = basePath && hadBasePath && !hasBasePath(requestPathname, basePath) ? addBasePathToPathname(requestPathname, basePath) : requestPathname;
119
120
  if (mwPathname !== url.pathname) {
120
121
  const mwUrl = new URL(url);
121
122
  mwUrl.pathname = mwPathname;
@@ -141,7 +142,7 @@ async function executeMiddleware(options) {
141
142
  const hadBasePath = options.hadBasePath ?? (!options.basePath || hasBasePath(new URL(options.request.url).pathname, options.basePath));
142
143
  const matchPathname = options.basePath ? stripBasePath(normalizedPathname, options.basePath) : normalizedPathname;
143
144
  if (!matchesMiddleware(matchPathname, middlewareMatcher(options.module), options.request, options.i18nConfig)) return { continue: true };
144
- const nextRequest = createNextRequest(options.request, normalizedPathname, options.i18nConfig, options.basePath, options.trailingSlash, hadBasePath);
145
+ const nextRequest = createNextRequest(options.request, options.i18nConfig, options.basePath, options.trailingSlash, hadBasePath);
145
146
  if (options.isDataRequest) Object.defineProperty(nextRequest, "__isData", {
146
147
  enumerable: false,
147
148
  value: true
@@ -58,6 +58,6 @@ declare function findMiddlewareFile(root: string, fileMatcher: ValidFileMatcher,
58
58
  * @param request - The incoming Request object
59
59
  * @returns Middleware result describing what action to take
60
60
  */
61
- declare function runMiddleware(runner: ModuleRunner, middlewarePath: string, request: Request, i18nConfig?: NextI18nConfig | null, basePath?: string, trailingSlash?: boolean, isDataRequest?: boolean): Promise<MiddlewareResult>;
61
+ declare function runMiddleware(runner: ModuleRunner, middlewarePath: string, request: Request, i18nConfig?: NextI18nConfig | null, basePath?: string, trailingSlash?: boolean, isDataRequest?: boolean, normalizedPathname?: string): Promise<MiddlewareResult>;
62
62
  //#endregion
63
63
  export { findMiddlewareFile, isProxyFile, matchPattern, matchesMiddleware, resolveMiddlewareHandler, runMiddleware };
@@ -94,7 +94,7 @@ function isMiddlewareModule(value) {
94
94
  * @param request - The incoming Request object
95
95
  * @returns Middleware result describing what action to take
96
96
  */
97
- async function runMiddleware(runner, middlewarePath, request, i18nConfig, basePath, trailingSlash, isDataRequest) {
97
+ async function runMiddleware(runner, middlewarePath, request, i18nConfig, basePath, trailingSlash, isDataRequest, normalizedPathname) {
98
98
  const mod = await runner.import(middlewarePath);
99
99
  if (!isMiddlewareModule(mod)) throw new Error(`Middleware module "${middlewarePath}" did not evaluate to an object.`);
100
100
  return runGeneratedMiddleware({
@@ -106,6 +106,7 @@ async function runMiddleware(runner, middlewarePath, request, i18nConfig, basePa
106
106
  isDataRequest,
107
107
  isProxy: isProxyFile(middlewarePath),
108
108
  module: mod,
109
+ normalizedPathname,
109
110
  request,
110
111
  trailingSlash
111
112
  });
@@ -74,9 +74,11 @@ type HandlePagesApiRouteOptions = {
74
74
  url: string;
75
75
  nextConfig?: {
76
76
  basePath?: string;
77
+ allowedRevalidateHeaderKeys?: readonly string[];
77
78
  i18n?: NextI18nConfig | null;
78
79
  trailingSlash?: boolean;
79
80
  };
81
+ trustedRevalidateOrigin?: string;
80
82
  };
81
83
  declare function handlePagesApiRoute(options: HandlePagesApiRouteOptions): Promise<Response>;
82
84
  //#endregion
@@ -48,10 +48,13 @@ async function _handlePagesApiRoute(options) {
48
48
  if (!isNodeApiRouteModule(route.module)) return new Response("API route does not export a default function", { status: 500 });
49
49
  const query = buildPagesApiQuery(options.url, params);
50
50
  const bodyParserConfig = resolveBodyParserConfig(route.module.config);
51
+ const body = bodyParserConfig.enabled ? await parsePagesApiBody(options.request, bodyParserConfig.sizeLimit) : void 0;
51
52
  const { req, res, responsePromise } = createPagesReqRes({
52
- body: bodyParserConfig.enabled ? await parsePagesApiBody(options.request, bodyParserConfig.sizeLimit) : void 0,
53
+ allowedRevalidateHeaderKeys: options.nextConfig?.allowedRevalidateHeaderKeys,
54
+ body,
53
55
  query,
54
56
  request: options.request,
57
+ trustedRevalidateOrigin: options.trustedRevalidateOrigin,
55
58
  url: options.url
56
59
  });
57
60
  let resWasPiped = false;
@@ -34,6 +34,16 @@ type NextDataMatch = {
34
34
  * even when the buildId is wrong (so we can still return a 404 JSON response).
35
35
  */
36
36
  declare function isNextDataPathname(pathname: string): boolean;
37
+ /**
38
+ * WHATWG URL parsing removes TAB, LF, and CR characters. Reject paths where
39
+ * that normalization would manufacture the internal Pages data namespace.
40
+ */
41
+ declare function urlParserCreatesPagesDataPath(pathname: string): boolean;
42
+ /**
43
+ * Keep URL-parser-ignored characters encoded until route matching decodes the
44
+ * captured parameter. Passing them literally to `new URL()` would remove them.
45
+ */
46
+ declare function encodeUrlParserIgnoredCharacters(pathname: string): string;
37
47
  /**
38
48
  * Parse `/_next/data/<buildId>/<...page>.json` and return the normalized page
39
49
  * pathname. Returns `null` if the pathname does not match the pattern or if
@@ -120,4 +130,4 @@ type NormalizePagesDataRequestResult = {
120
130
  */
121
131
  declare function normalizePagesDataRequest(request: Request, buildId: string | null, basePath?: string, trailingSlash?: boolean): NormalizePagesDataRequestResult;
122
132
  //#endregion
123
- export { buildMiddlewarePrefetchSkipResponse, buildNextDataJsonResponse, buildNextDataNotFoundResponse, buildNextDataPropsJsonResponse, isNextDataPathname, normalizeNextDataPagePathname, normalizePagesDataRequest, parseNextDataPathname };
133
+ export { buildMiddlewarePrefetchSkipResponse, buildNextDataJsonResponse, buildNextDataNotFoundResponse, buildNextDataPropsJsonResponse, encodeUrlParserIgnoredCharacters, isNextDataPathname, normalizeNextDataPagePathname, normalizePagesDataRequest, parseNextDataPathname, urlParserCreatesPagesDataPath };
@@ -32,6 +32,21 @@ function isNextDataPathname(pathname) {
32
32
  return pathname.startsWith(NEXT_DATA_PREFIX) && pathname.endsWith(NEXT_DATA_SUFFIX);
33
33
  }
34
34
  /**
35
+ * WHATWG URL parsing removes TAB, LF, and CR characters. Reject paths where
36
+ * that normalization would manufacture the internal Pages data namespace.
37
+ */
38
+ function urlParserCreatesPagesDataPath(pathname) {
39
+ const parsedPathname = pathname.replaceAll(" ", "").replaceAll("\n", "").replaceAll("\r", "");
40
+ return pathname !== parsedPathname && !isNextDataPathname(pathname) && isNextDataPathname(parsedPathname);
41
+ }
42
+ /**
43
+ * Keep URL-parser-ignored characters encoded until route matching decodes the
44
+ * captured parameter. Passing them literally to `new URL()` would remove them.
45
+ */
46
+ function encodeUrlParserIgnoredCharacters(pathname) {
47
+ return pathname.replaceAll(" ", "%09").replaceAll("\n", "%0A").replaceAll("\r", "%0D");
48
+ }
49
+ /**
35
50
  * Parse `/_next/data/<buildId>/<...page>.json` and return the normalized page
36
51
  * pathname. Returns `null` if the pathname does not match the pattern or if
37
52
  * the buildId segment does not match the server's buildId.
@@ -168,4 +183,4 @@ function normalizePagesDataRequest(request, buildId, basePath = "", trailingSlas
168
183
  };
169
184
  }
170
185
  //#endregion
171
- export { buildMiddlewarePrefetchSkipResponse, buildNextDataJsonResponse, buildNextDataNotFoundResponse, buildNextDataPropsJsonResponse, isNextDataPathname, normalizeNextDataPagePathname, normalizePagesDataRequest, parseNextDataPathname };
186
+ export { buildMiddlewarePrefetchSkipResponse, buildNextDataJsonResponse, buildNextDataNotFoundResponse, buildNextDataPropsJsonResponse, encodeUrlParserIgnoredCharacters, isNextDataPathname, normalizeNextDataPagePathname, normalizePagesDataRequest, parseNextDataPathname, urlParserCreatesPagesDataPath };
@@ -17,7 +17,6 @@ function createPagesDevHydrationScript(options) {
17
17
  element = React.createElement(AppComponent, {
18
18
  ...props,
19
19
  Component: PageComponent,
20
- pageProps: rawPageProps,
21
20
  router: appRouter,
22
21
  });
23
22
  ` : `
@@ -1,3 +1,5 @@
1
+ import { NextRouter } from "../shims/router.js";
2
+
1
3
  //#region src/server/pages-get-initial-props.d.ts
2
4
  type PagesGetInitialPropsContext = {
3
5
  req?: unknown;
@@ -10,6 +12,16 @@ type PagesGetInitialPropsContext = {
10
12
  locales?: string[];
11
13
  defaultLocale?: string;
12
14
  } & Record<string, unknown>;
15
+ type PagesGetInitialPropsRouter = Omit<Pick<NextRouter, "route" | "pathname" | "query" | "asPath">, "query"> & {
16
+ query: Record<string, unknown>;
17
+ };
18
+ /**
19
+ * Build the URL-state subset of Next.js's ServerRouter used by isolated
20
+ * initial-props helpers. Real request handlers pass their full `next/router`
21
+ * instance; this fallback keeps direct helper callers and tests aligned with
22
+ * the same required fields.
23
+ */
24
+ declare function createPagesGetInitialPropsRouter(pathname: string, query: Record<string, unknown>, asPath: string): PagesGetInitialPropsRouter;
13
25
  declare function hasPagesGetInitialProps(component: unknown): boolean;
14
26
  declare function isResponseSent(res: unknown): boolean;
15
27
  declare function loadPagesGetInitialProps(component: unknown, context: PagesGetInitialPropsContext): Promise<Record<string, unknown> | null>;
@@ -31,7 +43,7 @@ type DevAppInitialPropsResult = {
31
43
  kind: "render";
32
44
  pageProps: Record<string, unknown>;
33
45
  renderProps: Record<string, unknown> & {
34
- pageProps: unknown;
46
+ pageProps?: unknown;
35
47
  };
36
48
  };
37
49
  type DevAppInitialPropsContext = {
@@ -47,7 +59,8 @@ type DevAppInitialPropsContext = {
47
59
  res: unknown;
48
60
  pathname: string;
49
61
  query: Record<string, unknown>;
50
- asPath: string;
62
+ asPath: string; /** The request-scoped `next/router` server instance when available. */
63
+ router?: PagesGetInitialPropsRouter;
51
64
  locale?: string;
52
65
  locales?: string[];
53
66
  defaultLocale?: string;
@@ -64,4 +77,4 @@ type DevAppInitialPropsContext = {
64
77
  */
65
78
  declare function loadDevAppInitialProps(ctx: DevAppInitialPropsContext): Promise<DevAppInitialPropsResult>;
66
79
  //#endregion
67
- export { DevAppInitialPropsContext, DevAppInitialPropsResult, hasPagesGetInitialProps, isResponseSent, loadDevAppInitialProps, loadPagesGetInitialProps };
80
+ export { DevAppInitialPropsContext, DevAppInitialPropsResult, PagesGetInitialPropsRouter, createPagesGetInitialPropsRouter, hasPagesGetInitialProps, isResponseSent, loadDevAppInitialProps, loadPagesGetInitialProps };
@@ -1,4 +1,18 @@
1
1
  //#region src/server/pages-get-initial-props.ts
2
+ /**
3
+ * Build the URL-state subset of Next.js's ServerRouter used by isolated
4
+ * initial-props helpers. Real request handlers pass their full `next/router`
5
+ * instance; this fallback keeps direct helper callers and tests aligned with
6
+ * the same required fields.
7
+ */
8
+ function createPagesGetInitialPropsRouter(pathname, query, asPath) {
9
+ return {
10
+ route: pathname.replace(/\/$/, "") || "/",
11
+ pathname,
12
+ query,
13
+ asPath
14
+ };
15
+ }
2
16
  function isObjectLike(value) {
3
17
  return typeof value === "object" && value !== null || typeof value === "function";
4
18
  }
@@ -61,11 +75,7 @@ async function loadDevAppInitialProps(ctx) {
61
75
  const initialProps = await loadPagesGetInitialProps(ctx.appComponent, {
62
76
  AppTree: ctx.appTree,
63
77
  Component: ctx.component,
64
- router: {
65
- pathname: ctx.pathname,
66
- query: ctx.query,
67
- asPath: ctx.asPath
68
- },
78
+ router: ctx.router ?? createPagesGetInitialPropsRouter(ctx.pathname, ctx.query, ctx.asPath),
69
79
  ctx: {
70
80
  req: ctx.req,
71
81
  res: ctx.res,
@@ -82,11 +92,8 @@ async function loadDevAppInitialProps(ctx) {
82
92
  return {
83
93
  kind: "render",
84
94
  pageProps: isPropsObject(initialPageProps) ? initialPageProps : {},
85
- renderProps: isPropsObject(initialProps) ? {
86
- ...initialProps,
87
- pageProps: initialPageProps
88
- } : { pageProps: initialPageProps }
95
+ renderProps: isPropsObject(initialProps) ? initialProps : {}
89
96
  };
90
97
  }
91
98
  //#endregion
92
- export { hasPagesGetInitialProps, isResponseSent, loadDevAppInitialProps, loadPagesGetInitialProps };
99
+ export { createPagesGetInitialPropsRouter, hasPagesGetInitialProps, isResponseSent, loadDevAppInitialProps, loadPagesGetInitialProps };
@@ -93,23 +93,71 @@ function stripI18nLocaleForApiRoute(url, i18nConfig) {
93
93
  */
94
94
  function detectLocaleFromAcceptLanguage(acceptLang, i18nConfig) {
95
95
  if (!acceptLang) return null;
96
- const langs = acceptLang.split(",").map((part) => {
97
- const [lang, qPart] = part.trim().split(";");
98
- const q = qPart ? parseFloat(qPart.replace("q=", "")) : 1;
99
- return {
100
- lang: lang.trim().toLowerCase(),
101
- q
102
- };
103
- }).sort((a, b) => b.q - a.q);
104
- for (const { lang } of langs) {
105
- const exactMatch = i18nConfig.locales.find((locale) => locale.toLowerCase() === lang);
106
- if (exactMatch) return exactMatch;
107
- const prefix = lang.split("-")[0];
108
- const prefixMatch = i18nConfig.locales.find((locale) => {
109
- const lowered = locale.toLowerCase();
110
- return lowered === prefix || lowered.startsWith(prefix + "-");
96
+ const configured = /* @__PURE__ */ new Map();
97
+ let position = 0;
98
+ for (const locale of i18nConfig.locales) {
99
+ const lower = locale.toLowerCase();
100
+ configured.set(lower, {
101
+ locale,
102
+ position: position++
111
103
  });
112
- if (prefixMatch) return prefixMatch;
104
+ const parts = lower.split("-");
105
+ while (parts.length > 1) {
106
+ parts.pop();
107
+ const prefix = parts.join("-");
108
+ if (!configured.has(prefix)) configured.set(prefix, {
109
+ locale,
110
+ position: position++
111
+ });
112
+ }
113
+ }
114
+ const selections = [];
115
+ const listedTokens = /* @__PURE__ */ new Set();
116
+ try {
117
+ const parts = acceptLang.replace(/[ \t]/g, "").split(",");
118
+ for (let headerPosition = 0; headerPosition < parts.length; headerPosition++) {
119
+ const part = parts[headerPosition];
120
+ if (!part) continue;
121
+ const params = part.split(";");
122
+ if (params.length > 2) throw new Error("Invalid Accept-Language header");
123
+ const token = params[0].toLowerCase();
124
+ if (!token) throw new Error("Invalid Accept-Language header");
125
+ const selection = {
126
+ token,
127
+ headerPosition,
128
+ quality: 1
129
+ };
130
+ const configuredMatch = configured.get(token);
131
+ if (configuredMatch) selection.preference = configuredMatch.position;
132
+ listedTokens.add(token);
133
+ if (params.length === 2) {
134
+ const [key, value] = params[1].split("=");
135
+ if (!value || key !== "q" && key !== "Q") throw new Error("Invalid Accept-Language header");
136
+ const quality = parseFloat(value);
137
+ if (quality === 0) continue;
138
+ if (Number.isFinite(quality) && quality >= .001 && quality <= 1) selection.quality = quality;
139
+ }
140
+ selections.push(selection);
141
+ }
142
+ } catch {
143
+ return null;
144
+ }
145
+ selections.sort((a, b) => {
146
+ if (b.quality !== a.quality) return b.quality - a.quality;
147
+ if (a.preference !== b.preference) {
148
+ if (a.preference === void 0) return 1;
149
+ if (b.preference === void 0) return -1;
150
+ return a.preference - b.preference;
151
+ }
152
+ return a.headerPosition - b.headerPosition;
153
+ });
154
+ for (const { token } of selections) {
155
+ if (token === "*") {
156
+ for (const [preference, { locale }] of configured) if (!listedTokens.has(preference)) return locale;
157
+ continue;
158
+ }
159
+ const match = configured.get(token);
160
+ if (match) return match.locale;
113
161
  }
114
162
  return null;
115
163
  }
@@ -49,9 +49,11 @@ type PagesRequestCookiesCarrier = {
49
49
  cookies?: unknown;
50
50
  };
51
51
  type CreatePagesReqResOptions = {
52
+ allowedRevalidateHeaderKeys?: readonly string[];
52
53
  body: unknown;
53
54
  query: PagesRequestQuery;
54
55
  request: Request;
56
+ trustedRevalidateOrigin?: string;
55
57
  url: string;
56
58
  };
57
59
  type CreatePagesReqResResult = {
@@ -121,6 +121,8 @@ var PagesResponseStream = class extends Writable {
121
121
  resolveResponse;
122
122
  rejectResponse;
123
123
  requestHeaders;
124
+ trustedRevalidateOrigin;
125
+ allowedRevalidateHeaderKeys;
124
126
  resStatusCode = 200;
125
127
  resHeaders = {};
126
128
  setCookieHeaders = [];
@@ -128,11 +130,13 @@ var PagesResponseStream = class extends Writable {
128
130
  controller = null;
129
131
  bufferedChunks = [];
130
132
  streamEnded = false;
131
- constructor(resolveResponse, rejectResponse, requestHeaders) {
133
+ constructor(resolveResponse, rejectResponse, requestHeaders, trustedRevalidateOrigin, allowedRevalidateHeaderKeys = []) {
132
134
  super();
133
135
  this.resolveResponse = resolveResponse;
134
136
  this.rejectResponse = rejectResponse;
135
137
  this.requestHeaders = requestHeaders;
138
+ this.trustedRevalidateOrigin = trustedRevalidateOrigin;
139
+ this.allowedRevalidateHeaderKeys = allowedRevalidateHeaderKeys;
136
140
  this.once("error", (err) => {
137
141
  if (!this.resolved) {
138
142
  this.resolved = true;
@@ -202,7 +206,7 @@ var PagesResponseStream = class extends Writable {
202
206
  return headers;
203
207
  }
204
208
  async revalidate(urlPath, opts) {
205
- await performOnDemandRevalidate(this.requestHeaders, urlPath, opts);
209
+ await performOnDemandRevalidate(this.requestHeaders, urlPath, opts, this.trustedRevalidateOrigin, this.allowedRevalidateHeaderKeys);
206
210
  }
207
211
  setPreviewData(data, options = {}) {
208
212
  setPagesPreviewData(this, data, options);
@@ -299,7 +303,7 @@ function createPagesReqRes(options) {
299
303
  resolveResponse = resolve;
300
304
  rejectResponse = reject;
301
305
  });
302
- const res = new PagesResponseStream(resolveResponse, rejectResponse, options.request.headers);
306
+ const res = new PagesResponseStream(resolveResponse, rejectResponse, options.request.headers, options.trustedRevalidateOrigin ?? new URL(options.request.url).origin, options.allowedRevalidateHeaderKeys);
303
307
  attachPagesPreviewApi(req, res);
304
308
  return {
305
309
  req,