@opennextjs/aws 3.2.1 → 3.3.0

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 (155) hide show
  1. package/README.md +21 -2
  2. package/dist/adapters/cache.d.ts +0 -23
  3. package/dist/adapters/cache.js +10 -12
  4. package/dist/adapters/config/index.js +1 -1
  5. package/dist/adapters/config/util.js +2 -2
  6. package/dist/adapters/dynamo-provider.js +3 -5
  7. package/dist/adapters/edge-adapter.d.ts +0 -3
  8. package/dist/adapters/edge-adapter.js +43 -38
  9. package/dist/adapters/image-optimization-adapter.d.ts +1 -2
  10. package/dist/adapters/image-optimization-adapter.js +4 -4
  11. package/dist/adapters/logger.d.ts +0 -3
  12. package/dist/adapters/logger.js +32 -13
  13. package/dist/adapters/middleware.js +42 -18
  14. package/dist/adapters/plugins/image-optimization/image-optimization.d.ts +1 -3
  15. package/dist/adapters/plugins/image-optimization/image-optimization.js +0 -1
  16. package/dist/adapters/plugins/image-optimization/image-optimization.replacement.d.ts +1 -3
  17. package/dist/adapters/revalidate.js +2 -2
  18. package/dist/adapters/server-adapter.d.ts +0 -3
  19. package/dist/adapters/server-adapter.js +3 -1
  20. package/dist/adapters/util.js +2 -2
  21. package/dist/build/bundleNextServer.d.ts +3 -1
  22. package/dist/build/bundleNextServer.js +3 -3
  23. package/dist/build/compileConfig.js +1 -1
  24. package/dist/build/copyTracedFiles.js +15 -26
  25. package/dist/build/createAssets.js +36 -27
  26. package/dist/build/createImageOptimizationBundle.js +1 -1
  27. package/dist/build/createMiddleware.js +8 -3
  28. package/dist/build/createRevalidationBundle.js +1 -1
  29. package/dist/build/createServerBundle.js +25 -31
  30. package/dist/build/createWarmerBundle.js +1 -1
  31. package/dist/build/edge/createEdgeBundle.d.ts +8 -4
  32. package/dist/build/edge/createEdgeBundle.js +34 -16
  33. package/dist/build/generateOutput.js +7 -13
  34. package/dist/build/helper.d.ts +28 -5
  35. package/dist/build/helper.js +44 -15
  36. package/dist/build/installDeps.js +1 -1
  37. package/dist/build/patch/patchedAsyncStorage.js +1 -1
  38. package/dist/build/utils.js +3 -2
  39. package/dist/build/validateConfig.js +4 -1
  40. package/dist/core/createGenericHandler.d.ts +2 -4
  41. package/dist/core/createGenericHandler.js +1 -2
  42. package/dist/core/createMainHandler.d.ts +0 -17
  43. package/dist/core/createMainHandler.js +5 -4
  44. package/dist/core/edgeFunctionHandler.d.ts +1 -51
  45. package/dist/core/patchAsyncStorage.js +5 -6
  46. package/dist/core/requestHandler.d.ts +1 -2
  47. package/dist/core/requestHandler.js +99 -90
  48. package/dist/core/require-hooks.js +8 -7
  49. package/dist/core/resolve.d.ts +13 -7
  50. package/dist/core/resolve.js +29 -35
  51. package/dist/core/routing/cacheInterceptor.js +12 -13
  52. package/dist/core/routing/i18n/accept-header.js +3 -2
  53. package/dist/core/routing/matcher.d.ts +2 -4
  54. package/dist/core/routing/matcher.js +18 -27
  55. package/dist/core/routing/middleware.d.ts +3 -3
  56. package/dist/core/routing/middleware.js +20 -20
  57. package/dist/core/routing/util.d.ts +2 -15
  58. package/dist/core/routing/util.js +26 -88
  59. package/dist/core/routingHandler.d.ts +4 -8
  60. package/dist/core/routingHandler.js +36 -18
  61. package/dist/core/util.js +5 -3
  62. package/dist/helpers/withCloudflare.d.ts +1 -1
  63. package/dist/helpers/withCloudflare.js +2 -2
  64. package/dist/helpers/withSST.d.ts +1 -1
  65. package/dist/http/openNextResponse.d.ts +6 -18
  66. package/dist/http/openNextResponse.js +32 -32
  67. package/dist/http/request.d.ts +0 -3
  68. package/dist/http/request.js +4 -2
  69. package/dist/http/util.d.ts +1 -1
  70. package/dist/http/util.js +8 -12
  71. package/dist/minimize-js.js +19 -19
  72. package/dist/overrides/converters/aws-apigw-v1.d.ts +2 -2
  73. package/dist/overrides/converters/aws-apigw-v1.js +2 -1
  74. package/dist/overrides/converters/aws-apigw-v2.d.ts +2 -2
  75. package/dist/overrides/converters/aws-apigw-v2.js +8 -8
  76. package/dist/overrides/converters/aws-cloudfront.d.ts +2 -2
  77. package/dist/overrides/converters/aws-cloudfront.js +11 -30
  78. package/dist/overrides/converters/dummy.d.ts +1 -1
  79. package/dist/overrides/converters/edge.d.ts +3 -5
  80. package/dist/overrides/converters/edge.js +15 -18
  81. package/dist/overrides/converters/node.d.ts +1 -1
  82. package/dist/overrides/converters/node.js +1 -1
  83. package/dist/overrides/converters/sqs-revalidate.d.ts +1 -1
  84. package/dist/overrides/imageLoader/dummy.d.ts +1 -1
  85. package/dist/overrides/imageLoader/host.d.ts +1 -1
  86. package/dist/overrides/imageLoader/s3.d.ts +1 -1
  87. package/dist/overrides/imageLoader/s3.js +1 -1
  88. package/dist/overrides/incrementalCache/dummy.d.ts +1 -1
  89. package/dist/overrides/incrementalCache/dummy.js +4 -3
  90. package/dist/overrides/incrementalCache/s3-lite.d.ts +1 -1
  91. package/dist/overrides/incrementalCache/s3-lite.js +15 -19
  92. package/dist/overrides/incrementalCache/s3.d.ts +1 -1
  93. package/dist/overrides/incrementalCache/s3.js +1 -1
  94. package/dist/overrides/originResolver/dummy.d.ts +1 -1
  95. package/dist/overrides/originResolver/pattern-env.d.ts +1 -1
  96. package/dist/overrides/originResolver/pattern-env.js +10 -11
  97. package/dist/overrides/proxyExternalRequest/dummy.d.ts +3 -0
  98. package/dist/overrides/proxyExternalRequest/dummy.js +8 -0
  99. package/dist/overrides/proxyExternalRequest/fetch.d.ts +3 -0
  100. package/dist/overrides/proxyExternalRequest/fetch.js +25 -0
  101. package/dist/overrides/proxyExternalRequest/node.d.ts +3 -0
  102. package/dist/overrides/proxyExternalRequest/node.js +67 -0
  103. package/dist/overrides/queue/dummy.d.ts +1 -1
  104. package/dist/overrides/queue/dummy.js +2 -1
  105. package/dist/overrides/queue/sqs-lite.d.ts +1 -1
  106. package/dist/overrides/queue/sqs-lite.js +7 -9
  107. package/dist/overrides/queue/sqs.d.ts +1 -1
  108. package/dist/overrides/queue/sqs.js +1 -1
  109. package/dist/overrides/tagCache/constants.js +2 -2
  110. package/dist/overrides/tagCache/dummy.d.ts +1 -1
  111. package/dist/overrides/tagCache/dynamodb-lite.d.ts +1 -1
  112. package/dist/overrides/tagCache/dynamodb-lite.js +10 -12
  113. package/dist/overrides/tagCache/dynamodb.d.ts +1 -1
  114. package/dist/overrides/tagCache/dynamodb.js +2 -2
  115. package/dist/overrides/warmer/aws-lambda.d.ts +1 -1
  116. package/dist/overrides/warmer/dummy.d.ts +1 -1
  117. package/dist/overrides/warmer/dummy.js +2 -1
  118. package/dist/overrides/wrappers/aws-lambda-streaming.d.ts +3 -3
  119. package/dist/overrides/wrappers/aws-lambda-streaming.js +0 -4
  120. package/dist/overrides/wrappers/aws-lambda.d.ts +2 -2
  121. package/dist/overrides/wrappers/aws-lambda.js +0 -3
  122. package/dist/overrides/wrappers/cloudflare-edge.d.ts +9 -0
  123. package/dist/overrides/wrappers/cloudflare-edge.js +38 -0
  124. package/dist/overrides/wrappers/cloudflare-node.d.ts +8 -0
  125. package/dist/overrides/wrappers/cloudflare-node.js +47 -0
  126. package/dist/overrides/wrappers/dummy.d.ts +3 -3
  127. package/dist/overrides/wrappers/dummy.js +1 -1
  128. package/dist/overrides/wrappers/node.d.ts +3 -3
  129. package/dist/overrides/wrappers/node.js +3 -6
  130. package/dist/plugins/edge.js +6 -5
  131. package/dist/plugins/replacement.js +2 -2
  132. package/dist/plugins/resolve.d.ts +3 -1
  133. package/dist/plugins/resolve.js +9 -2
  134. package/dist/types/aws-lambda.d.ts +2 -5
  135. package/dist/types/cache.d.ts +0 -2
  136. package/dist/types/global.d.ts +188 -0
  137. package/dist/types/next-types.d.ts +1 -3
  138. package/dist/types/open-next.d.ts +33 -41
  139. package/dist/types/overrides.d.ts +86 -0
  140. package/dist/{adapters → utils}/binary.js +1 -0
  141. package/dist/utils/error.d.ts +1 -0
  142. package/dist/utils/error.js +8 -0
  143. package/dist/utils/promise.d.ts +3 -0
  144. package/dist/utils/promise.js +44 -0
  145. package/dist/utils/stream.d.ts +0 -1
  146. package/package.json +3 -3
  147. package/dist/overrides/incrementalCache/types.d.ts +0 -34
  148. package/dist/overrides/queue/types.d.ts +0 -12
  149. package/dist/overrides/tagCache/types.d.ts +0 -11
  150. package/dist/overrides/tagCache/types.js +0 -1
  151. package/dist/overrides/wrappers/cloudflare.d.ts +0 -11
  152. package/dist/overrides/wrappers/cloudflare.js +0 -20
  153. /package/dist/{overrides/incrementalCache/types.js → types/global.js} +0 -0
  154. /package/dist/{overrides/queue/types.js → types/overrides.js} +0 -0
  155. /package/dist/{adapters → utils}/binary.d.ts +0 -0
@@ -3,8 +3,8 @@ import { Readable } from "node:stream";
3
3
  import { BuildId, HtmlPages, NextConfig } from "../../adapters/config/index.js";
4
4
  import { OpenNextNodeResponse } from "../../http/openNextResponse.js";
5
5
  import { parseHeaders } from "../../http/util.js";
6
- import { isBinaryContentType } from "../../adapters/binary.js";
7
6
  import { debug, error } from "../../adapters/logger.js";
7
+ import { isBinaryContentType } from "../../utils/binary.js";
8
8
  /**
9
9
  *
10
10
  * @__PURE__
@@ -24,7 +24,8 @@ export function convertFromQueryString(query) {
24
24
  const queryParts = query.split("&");
25
25
  return queryParts.reduce((acc, part) => {
26
26
  const [key, value] = part.split("=");
27
- return { ...acc, [key]: value };
27
+ acc[key] = value;
28
+ return acc;
28
29
  }, {});
29
30
  }
30
31
  /**
@@ -128,45 +129,20 @@ export function getMiddlewareMatch(middlewareManifest) {
128
129
  * @__PURE__
129
130
  */
130
131
  export function escapeRegex(str) {
131
- let path = str.replace(/\(\.\)/g, "_µ1_");
132
- path = path.replace(/\(\.{2}\)/g, "_µ2_");
133
- path = path.replace(/\(\.{3}\)/g, "_µ3_");
134
- return path;
132
+ return str
133
+ .replaceAll("(.)", "_µ1_")
134
+ .replaceAll("(..)", "_µ2_")
135
+ .replaceAll("(...)", "_µ3_");
135
136
  }
136
137
  /**
137
138
  *
138
139
  * @__PURE__
139
140
  */
140
141
  export function unescapeRegex(str) {
141
- let path = str.replace(/_µ1_/g, "(.)");
142
- path = path.replace(/_µ2_/g, "(..)");
143
- path = path.replace(/_µ3_/g, "(...)");
144
- return path;
145
- }
146
- /**
147
- *
148
- * @__PURE__
149
- */
150
- function filterHeadersForProxy(headers) {
151
- const filteredHeaders = {};
152
- const disallowedHeaders = [
153
- "host",
154
- "connection",
155
- "via",
156
- "x-cache",
157
- "transfer-encoding",
158
- "content-encoding",
159
- "content-length",
160
- ];
161
- Object.entries(headers).forEach(([key, value]) => {
162
- const lowerKey = key.toLowerCase();
163
- if (disallowedHeaders.includes(lowerKey) || lowerKey.startsWith("x-amz"))
164
- return;
165
- else {
166
- filteredHeaders[key] = value?.toString() ?? "";
167
- }
168
- });
169
- return filteredHeaders;
142
+ return str
143
+ .replaceAll("_µ1_", "(.)")
144
+ .replaceAll("_µ2_", "(..)")
145
+ .replaceAll("_µ3_", "(...)");
170
146
  }
171
147
  /**
172
148
  * @__PURE__
@@ -184,50 +160,6 @@ export function convertBodyToReadableStream(method, body) {
184
160
  });
185
161
  return readable;
186
162
  }
187
- /**
188
- *
189
- * @__PURE__
190
- */
191
- export async function proxyRequest(internalEvent, res) {
192
- const { url, headers, method, body } = internalEvent;
193
- const request = await import("node:https").then((m) => m.request);
194
- debug("proxyRequest", url);
195
- await new Promise((resolve, reject) => {
196
- const filteredHeaders = filterHeadersForProxy(headers);
197
- debug("filteredHeaders", filteredHeaders);
198
- const req = request(url, {
199
- headers: filteredHeaders,
200
- method,
201
- rejectUnauthorized: false,
202
- }, (_res) => {
203
- res.writeHead(_res.statusCode ?? 200, filterHeadersForProxy(_res.headers));
204
- if (_res.headers["content-encoding"] === "br") {
205
- _res.pipe(require("node:zlib").createBrotliDecompress()).pipe(res);
206
- }
207
- else if (_res.headers["content-encoding"] === "gzip") {
208
- _res.pipe(require("node:zlib").createGunzip()).pipe(res);
209
- }
210
- else {
211
- _res.pipe(res);
212
- }
213
- _res.on("error", (e) => {
214
- error("proxyRequest error", e);
215
- res.end();
216
- reject(e);
217
- });
218
- res.on("finish", () => {
219
- resolve();
220
- });
221
- });
222
- if (body && method !== "GET" && method !== "HEAD") {
223
- req.write(body);
224
- }
225
- req.end();
226
- });
227
- // console.log("result", result);
228
- // res.writeHead(result.status, resHeaders);
229
- // res.end(await result.text());
230
- }
231
163
  var CommonHeaders;
232
164
  (function (CommonHeaders) {
233
165
  CommonHeaders["CACHE_CONTROL"] = "cache-control";
@@ -247,7 +179,8 @@ export function fixCacheHeaderForHtmlPages(rawPath, headers) {
247
179
  "private, no-cache, no-store, max-age=0, must-revalidate";
248
180
  return;
249
181
  }
250
- // WORKAROUND: `NextServer` does not set cache headers for HTML pages — https://github.com/serverless-stack/open-next#workaround-nextserver-does-not-set-cache-headers-for-html-pages
182
+ // WORKAROUND: `NextServer` does not set cache headers for HTML pages
183
+ // https://opennext.js.org/aws/v2/advanced/workaround#workaround-nextserver-does-not-set-cache-headers-for-html-pages
251
184
  if (HtmlPages.includes(rawPath)) {
252
185
  headers[CommonHeaders.CACHE_CONTROL] =
253
186
  "public, max-age=0, s-maxage=31536000, must-revalidate";
@@ -279,7 +212,8 @@ export function addOpenNextHeader(headers) {
279
212
  }
280
213
  if (globalThis.openNextDebug) {
281
214
  headers["X-OpenNext-Version"] = globalThis.openNextVersion;
282
- headers["X-OpenNext-RequestId"] = globalThis.__als.getStore()?.requestId;
215
+ headers["X-OpenNext-RequestId"] =
216
+ globalThis.__openNextAls.getStore()?.requestId;
283
217
  }
284
218
  }
285
219
  /**
@@ -310,13 +244,13 @@ export async function revalidateIfRequired(host, rawPath, headers, req) {
310
244
  // If data has the same etag during these 5 min dedup window, it will be deduplicated and not revalidated.
311
245
  try {
312
246
  const hash = (str) => crypto.createHash("md5").update(str).digest("hex");
313
- const requestId = globalThis.__als.getStore()?.requestId ?? "";
247
+ const requestId = globalThis.__openNextAls.getStore()?.requestId ?? "";
314
248
  const lastModified = globalThis.lastModified[requestId] > 0
315
249
  ? globalThis.lastModified[requestId]
316
250
  : "";
317
251
  // For some weird cases, lastModified is not set, haven't been able to figure out yet why
318
252
  // For those cases we add the etag to the deduplication id, it might help
319
- const etag = headers["etag"] ?? headers["ETag"] ?? "";
253
+ const etag = headers.etag ?? headers.ETag ?? "";
320
254
  await globalThis.queue.send({
321
255
  MessageBody: { host, url: revalidateUrl },
322
256
  MessageDeduplicationId: hash(`${rawPath}-${lastModified}-${etag}`),
@@ -338,19 +272,22 @@ export async function revalidateIfRequired(host, rawPath, headers, req) {
338
272
  export function generateMessageGroupId(rawPath) {
339
273
  let a = cyrb128(rawPath);
340
274
  // We use mulberry32 to generate a random int between 0 and MAX_REVALIDATE_CONCURRENCY
341
- var t = (a += 0x6d2b79f5);
275
+ let t = (a += 0x6d2b79f5);
342
276
  t = Math.imul(t ^ (t >>> 15), t | 1);
343
277
  t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
344
278
  const randomFloat = ((t ^ (t >>> 14)) >>> 0) / 4294967296;
345
279
  // This will generate a random int between 0 and MAX_REVALIDATE_CONCURRENCY
346
280
  // This means that we could have 1000 revalidate request at the same time
347
- const maxConcurrency = parseInt(process.env.MAX_REVALIDATE_CONCURRENCY ?? "10");
281
+ const maxConcurrency = Number.parseInt(process.env.MAX_REVALIDATE_CONCURRENCY ?? "10");
348
282
  const randomInt = Math.floor(randomFloat * maxConcurrency);
349
283
  return `revalidate-${randomInt}`;
350
284
  }
351
285
  // Used to generate a hash int from a string
352
286
  function cyrb128(str) {
353
- let h1 = 1779033703, h2 = 3144134277, h3 = 1013904242, h4 = 2773480762;
287
+ let h1 = 1779033703;
288
+ let h2 = 3144134277;
289
+ let h3 = 1013904242;
290
+ let h4 = 2773480762;
354
291
  for (let i = 0, k; i < str.length; i++) {
355
292
  k = str.charCodeAt(i);
356
293
  h1 = h2 ^ Math.imul(h1 ^ k, 597399067);
@@ -362,6 +299,7 @@ function cyrb128(str) {
362
299
  h2 = Math.imul(h4 ^ (h2 >>> 22), 2869860233);
363
300
  h3 = Math.imul(h1 ^ (h3 >>> 17), 951274213);
364
301
  h4 = Math.imul(h2 ^ (h4 >>> 19), 2716044179);
302
+ // biome-ignore lint/style/noCommaOperator:
365
303
  (h1 ^= h2 ^ h3 ^ h4), (h2 ^= h1), (h3 ^= h1), (h4 ^= h1);
366
304
  return h1 >>> 0;
367
305
  }
@@ -375,7 +313,7 @@ export function fixISRHeaders(headers) {
375
313
  "private, no-cache, no-store, max-age=0, must-revalidate";
376
314
  return;
377
315
  }
378
- const requestId = globalThis.__als.getStore()?.requestId ?? "";
316
+ const requestId = globalThis.__openNextAls.getStore()?.requestId ?? "";
379
317
  const _lastModified = globalThis.lastModified[requestId] ?? 0;
380
318
  if (headers[CommonHeaders.NEXT_CACHE] === "HIT" && _lastModified > 0) {
381
319
  // calculate age
@@ -387,7 +325,7 @@ export function fixISRHeaders(headers) {
387
325
  if (typeof cacheControl !== "string")
388
326
  return;
389
327
  const match = cacheControl.match(regex);
390
- const sMaxAge = match ? parseInt(match[1]) : undefined;
328
+ const sMaxAge = match ? Number.parseInt(match[1]) : undefined;
391
329
  // 31536000 is the default s-maxage value for SSG pages
392
330
  if (sMaxAge && sMaxAge !== 31536000) {
393
331
  const remainingTtl = Math.max(sMaxAge - age, 1);
@@ -1,8 +1,4 @@
1
- import type { InternalEvent, InternalResult, Origin } from "../types/open-next";
2
- export interface MiddlewareOutputEvent {
3
- internalEvent: InternalEvent;
4
- isExternalRewrite: boolean;
5
- origin: Origin | false;
6
- isISR: boolean;
7
- }
8
- export default function routingHandler(event: InternalEvent): Promise<InternalResult | MiddlewareOutputEvent>;
1
+ import type { InternalEvent, InternalResult, RoutingResult } from "../types/open-next";
2
+ export declare const MIDDLEWARE_HEADER_PREFIX = "x-middleware-response-";
3
+ export declare const MIDDLEWARE_HEADER_PREFIX_LEN: number;
4
+ export default function routingHandler(event: InternalEvent): Promise<InternalResult | RoutingResult>;
@@ -1,18 +1,20 @@
1
1
  import { BuildId, ConfigHeaders, PrerenderManifest, RoutesManifest, } from "../adapters/config/index";
2
2
  import { debug } from "../adapters/logger";
3
3
  import { cacheInterceptor } from "./routing/cacheInterceptor";
4
- import { addNextConfigHeaders, fixDataPage, handleFallbackFalse, handleRedirects, handleRewrites, } from "./routing/matcher";
4
+ import { fixDataPage, getNextConfigHeaders, handleFallbackFalse, handleRedirects, handleRewrites, } from "./routing/matcher";
5
5
  import { handleMiddleware } from "./routing/middleware";
6
+ export const MIDDLEWARE_HEADER_PREFIX = "x-middleware-response-";
7
+ export const MIDDLEWARE_HEADER_PREFIX_LEN = MIDDLEWARE_HEADER_PREFIX.length;
6
8
  // Add the locale prefix to the regex so we correctly match the rawPath
7
- const optionalLocalePrefixRegex = !!RoutesManifest.locales.length
8
- ? `^/(?:${RoutesManifest.locales.map((locale) => locale + "/?").join("|")})?`
9
+ const optionalLocalePrefixRegex = RoutesManifest.locales.length
10
+ ? `^/(?:${RoutesManifest.locales.map((locale) => `${locale}/?`).join("|")})?`
9
11
  : "^/";
10
12
  // Add the basepath prefix to the regex so we correctly match the rawPath
11
- const optionalBasepathPrefixRegex = !!RoutesManifest.basePath
13
+ const optionalBasepathPrefixRegex = RoutesManifest.basePath
12
14
  ? `^${RoutesManifest.basePath}/?`
13
15
  : "^/";
14
16
  // Add the basePath prefix to the api routes
15
- const apiPrefix = !!RoutesManifest.basePath
17
+ const apiPrefix = RoutesManifest.basePath
16
18
  ? `${RoutesManifest.basePath}/api`
17
19
  : "/api";
18
20
  const staticRegexp = RoutesManifest.routes.static.map((route) => new RegExp(route.regex
@@ -21,16 +23,34 @@ const staticRegexp = RoutesManifest.routes.static.map((route) => new RegExp(rout
21
23
  const dynamicRegexp = RoutesManifest.routes.dynamic.map((route) => new RegExp(route.regex
22
24
  .replace("^/", optionalLocalePrefixRegex)
23
25
  .replace("^/", optionalBasepathPrefixRegex)));
26
+ // Geolocation headers starting from Nextjs 15
27
+ // See https://github.com/vercel/vercel/blob/7714b1c/packages/functions/src/headers.ts
28
+ const geoHeaderToNextHeader = {
29
+ "x-open-next-city": "x-vercel-ip-city",
30
+ "x-open-next-country": "x-vercel-ip-country",
31
+ "x-open-next-region": "x-vercel-ip-country-region",
32
+ "x-open-next-latitude": "x-vercel-ip-latitude",
33
+ "x-open-next-longitude": "x-vercel-ip-longitude",
34
+ };
24
35
  function applyMiddlewareHeaders(eventHeaders, middlewareHeaders, setPrefix = true) {
36
+ const keyPrefix = setPrefix ? MIDDLEWARE_HEADER_PREFIX : "";
25
37
  Object.entries(middlewareHeaders).forEach(([key, value]) => {
26
38
  if (value) {
27
- eventHeaders[`${setPrefix ? "x-middleware-response-" : ""}${key}`] =
28
- Array.isArray(value) ? value.join(",") : value;
39
+ eventHeaders[keyPrefix + key] = Array.isArray(value)
40
+ ? value.join(",")
41
+ : value;
29
42
  }
30
43
  });
31
44
  }
32
45
  export default async function routingHandler(event) {
33
- const nextHeaders = addNextConfigHeaders(event, ConfigHeaders);
46
+ // Add Next geo headers
47
+ for (const [openNextGeoName, nextGeoName] of Object.entries(geoHeaderToNextHeader)) {
48
+ const value = event.headers[openNextGeoName];
49
+ if (value) {
50
+ event.headers[nextGeoName] = value;
51
+ }
52
+ }
53
+ const nextHeaders = getNextConfigHeaders(event, ConfigHeaders);
34
54
  let internalEvent = fixDataPage(event, BuildId);
35
55
  if ("statusCode" in internalEvent) {
36
56
  return internalEvent;
@@ -40,17 +60,15 @@ export default async function routingHandler(event) {
40
60
  debug("redirect", redirect);
41
61
  return redirect;
42
62
  }
43
- const middleware = await handleMiddleware(internalEvent);
44
- let middlewareResponseHeaders = {};
45
- if ("statusCode" in middleware) {
46
- return middleware;
47
- }
48
- else {
49
- middlewareResponseHeaders = middleware.responseHeaders || {};
50
- internalEvent = middleware;
63
+ const eventOrResult = await handleMiddleware(internalEvent);
64
+ const isResult = "statusCode" in eventOrResult;
65
+ if (isResult) {
66
+ return eventOrResult;
51
67
  }
52
- // At this point internalEvent is an InternalEvent or a MiddlewareOutputEvent
53
- let isExternalRewrite = middleware.externalRewrite ?? false;
68
+ const middlewareResponseHeaders = eventOrResult.responseHeaders;
69
+ let isExternalRewrite = eventOrResult.isExternalRewrite ?? false;
70
+ // internalEvent is `InternalEvent | MiddlewareEvent`
71
+ internalEvent = eventOrResult;
54
72
  if (!isExternalRewrite) {
55
73
  // First rewrite to be applied
56
74
  const beforeRewrites = handleRewrites(internalEvent, RoutesManifest.rewrites.beforeFiles);
package/dist/core/util.js CHANGED
@@ -5,7 +5,8 @@ import { AppPathsManifestKeys, NextConfig, RoutesManifest, } from "../adapters/c
5
5
  import NextServer from "next/dist/server/next-server.js";
6
6
  import { debug } from "../adapters/logger.js";
7
7
  import { applyOverride as applyNextjsRequireHooksOverride, overrideHooks as overrideNextjsRequireHooks, } from "./require-hooks.js";
8
- // WORKAROUND: Set `__NEXT_PRIVATE_PREBUNDLED_REACT` to use prebundled React — https://github.com/serverless-stack/open-next#workaround-set-__next_private_prebundled_react-to-use-prebundled-react
8
+ // WORKAROUND: Set `__NEXT_PRIVATE_PREBUNDLED_REACT` to use prebundled Reac
9
+ // See https://opennext.js.org/aws/v2/advanced/workaround#workaround-set-__next_private_prebundled_react-to-use-prebundled-react
9
10
  // Step 1: Need to override the require hooks for React before Next.js server
10
11
  // overrides them with prebundled ones in the case of app dir
11
12
  // Step 2: Import Next.js server
@@ -31,7 +32,7 @@ export const requestHandler = new NextServer.default({
31
32
  // our own cache handler to store the cache on S3.
32
33
  //#override stableIncrementalCache
33
34
  cacheHandler: cacheHandlerPath,
34
- cacheMaxMemorySize: 0,
35
+ cacheMaxMemorySize: 0, // We need to disable memory cache
35
36
  //#endOverride
36
37
  experimental: {
37
38
  ...NextConfig.experimental,
@@ -62,7 +63,8 @@ export function loadMiddlewareManifest(nextDir) {
62
63
  }
63
64
  //#override setNextjsPrebundledReact
64
65
  export function setNextjsPrebundledReact(rawPath) {
65
- // WORKAROUND: Set `__NEXT_PRIVATE_PREBUNDLED_REACT` to use prebundled React — https://github.com/serverless-stack/open-next#workaround-set-__next_private_prebundled_react-to-use-prebundled-react
66
+ // WORKAROUND: Set `__NEXT_PRIVATE_PREBUNDLED_REACT` to use prebundled React
67
+ // See https://opennext.js.org/aws/v2/advanced/workaround#workaround-set-__next_private_prebundled_react-to-use-prebundled-react
66
68
  const routes = [
67
69
  ...RoutesManifest.routes.static,
68
70
  ...RoutesManifest.routes.dynamic,
@@ -57,7 +57,7 @@ export declare function withCloudflare<Fn extends Record<string, CloudflareCompa
57
57
  external: true;
58
58
  originResolver: "pattern-env";
59
59
  override: {
60
- wrapper: "cloudflare";
60
+ wrapper: "cloudflare-edge";
61
61
  converter: "edge";
62
62
  };
63
63
  };
@@ -36,7 +36,7 @@ export function withCloudflare(config) {
36
36
  routes: [fn.routes],
37
37
  patterns: [fn.patterns],
38
38
  override: {
39
- wrapper: "cloudflare",
39
+ wrapper: "cloudflare-edge",
40
40
  converter: "edge",
41
41
  },
42
42
  }
@@ -50,7 +50,7 @@ export function withCloudflare(config) {
50
50
  external: true,
51
51
  originResolver: "pattern-env",
52
52
  override: {
53
- wrapper: "cloudflare",
53
+ wrapper: "cloudflare-edge",
54
54
  converter: "edge",
55
55
  },
56
56
  },
@@ -44,7 +44,7 @@ export declare function withSST<Fn extends Record<string, SSTCompatibleSplittedF
44
44
  functions?: Fn | undefined;
45
45
  middleware?: {
46
46
  external: true;
47
- } | undefined;
47
+ };
48
48
  dangerous?: import("../types/open-next").DangerousOptions | undefined;
49
49
  buildCommand?: string | undefined;
50
50
  buildOutputPath?: string | undefined;
@@ -1,23 +1,11 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
- /// <reference types="node" />
4
- /// <reference types="node" />
5
- /// <reference types="node" />
6
- import type { IncomingMessage, OutgoingHttpHeader, OutgoingHttpHeaders, ServerResponse } from "http";
7
- import type { Socket } from "net";
8
- import type { TransformCallback, Writable } from "stream";
9
- import { Transform } from "stream";
10
- export interface StreamCreator {
11
- writeHeaders(prelude: {
12
- statusCode: number;
13
- cookies: string[];
14
- headers: Record<string, string>;
15
- }): Writable;
16
- onWrite?: () => void;
17
- onFinish: (length: number) => void;
18
- }
1
+ import type { IncomingMessage, OutgoingHttpHeader, OutgoingHttpHeaders, ServerResponse } from "node:http";
2
+ import type { Socket } from "node:net";
3
+ import type { TransformCallback } from "node:stream";
4
+ import { Transform } from "node:stream";
5
+ import type { StreamCreator } from "../types/open-next";
19
6
  export declare class OpenNextNodeResponse extends Transform implements ServerResponse {
20
7
  private fixHeaders;
8
+ private onEnd;
21
9
  private streamCreator?;
22
10
  private initialHeaders?;
23
11
  statusCode: number;
@@ -1,4 +1,4 @@
1
- import { Transform } from "stream";
1
+ import { Transform } from "node:stream";
2
2
  import { debug } from "../adapters/logger";
3
3
  import { parseCookies, parseHeaders } from "./util";
4
4
  const SET_COOKIE_HEADER = "set-cookie";
@@ -6,6 +6,7 @@ const CANNOT_BE_USED = "This cannot be used in OpenNext";
6
6
  // We only need to implement the methods that are used by next.js
7
7
  export class OpenNextNodeResponse extends Transform {
8
8
  fixHeaders;
9
+ onEnd;
9
10
  streamCreator;
10
11
  initialHeaders;
11
12
  statusCode;
@@ -53,20 +54,9 @@ export class OpenNextNodeResponse extends Transform {
53
54
  constructor(fixHeaders, onEnd, streamCreator, initialHeaders) {
54
55
  super();
55
56
  this.fixHeaders = fixHeaders;
57
+ this.onEnd = onEnd;
56
58
  this.streamCreator = streamCreator;
57
59
  this.initialHeaders = initialHeaders;
58
- this.once("finish", () => {
59
- if (!this.headersSent) {
60
- this.flushHeaders();
61
- }
62
- // In some cases we might not have a store i.e. for example in the image optimization function
63
- // We may want to reconsider this in the future, it might be intersting to have access to this store everywhere
64
- globalThis.__als
65
- ?.getStore()
66
- ?.pendingPromiseRunner.add(onEnd(this.headers));
67
- const bodyLength = this.getBody().length;
68
- this.streamCreator?.onFinish(bodyLength);
69
- });
70
60
  }
71
61
  // Necessary for next 12
72
62
  // We might have to implement all the methods here
@@ -74,7 +64,9 @@ export class OpenNextNodeResponse extends Transform {
74
64
  return this;
75
65
  }
76
66
  get finished() {
77
- return Boolean(this.writableFinished && this.responseStream?.writableFinished);
67
+ return this.responseStream
68
+ ? this.responseStream?.writableFinished
69
+ : this.writableFinished;
78
70
  }
79
71
  setHeader(name, value) {
80
72
  const key = name.toLowerCase();
@@ -122,7 +114,8 @@ export class OpenNextNodeResponse extends Transform {
122
114
  this.headersSent = true;
123
115
  // Initial headers should be merged with the new headers
124
116
  // These initial headers are the one created either in the middleware or in next.config.js
125
- const mergeHeadersPriority = globalThis.__als?.getStore()?.mergeHeadersPriority ?? "middleware";
117
+ const mergeHeadersPriority = globalThis.__openNextAls?.getStore()?.mergeHeadersPriority ??
118
+ "middleware";
126
119
  if (this.initialHeaders) {
127
120
  this.headers =
128
121
  mergeHeadersPriority === "middleware"
@@ -134,7 +127,7 @@ export class OpenNextNodeResponse extends Transform {
134
127
  ...this.initialHeaders,
135
128
  ...this.headers,
136
129
  };
137
- const initialCookies = parseCookies(this.initialHeaders[SET_COOKIE_HEADER] ?? []);
130
+ const initialCookies = parseCookies(this.initialHeaders[SET_COOKIE_HEADER]?.toString());
138
131
  this._cookies =
139
132
  mergeHeadersPriority === "middleware"
140
133
  ? [...this._cookies, ...initialCookies]
@@ -162,14 +155,12 @@ export class OpenNextNodeResponse extends Transform {
162
155
  if (!this.hasHeader(key)) {
163
156
  return this.setHeader(key, value);
164
157
  }
165
- else {
166
- const existingHeader = this.getHeader(key);
167
- const toAppend = Array.isArray(value) ? value : [value];
168
- const newValue = Array.isArray(existingHeader)
169
- ? [...existingHeader, ...toAppend]
170
- : [existingHeader, ...toAppend];
171
- return this.setHeader(key, newValue);
172
- }
158
+ const existingHeader = this.getHeader(key);
159
+ const toAppend = Array.isArray(value) ? value : [value];
160
+ const newValue = Array.isArray(existingHeader)
161
+ ? [...existingHeader, ...toAppend]
162
+ : [existingHeader, ...toAppend];
163
+ return this.setHeader(key, newValue);
173
164
  }
174
165
  writeHead(statusCode, statusMessage, headers) {
175
166
  let _headers = headers;
@@ -227,15 +218,24 @@ export class OpenNextNodeResponse extends Transform {
227
218
  this._internalWrite(chunk, encoding);
228
219
  callback();
229
220
  }
230
- //This is only here because of aws broken streaming implementation.
231
- //Hopefully one day they will be able to give us a working streaming implementation in lambda for everyone
232
- //If you're lucky you have a working streaming implementation in your aws account and don't need this
233
- //If not you can set the OPEN_NEXT_FORCE_NON_EMPTY_RESPONSE env variable to true
234
- //BE CAREFUL: Aws keeps rolling out broken streaming implementations even on accounts that had working ones before
235
- //This is not dependent on the node runtime used
236
- //There is another known issue with aws lambda streaming where the request reach the lambda only way after the request has been sent by the client. For this there is absolutely nothing we can do, contact aws support if that's your case
237
221
  _flush(callback) {
238
- if (this.getBody().length < 1 &&
222
+ if (!this.headersSent) {
223
+ this.flushHeaders();
224
+ }
225
+ // In some cases we might not have a store i.e. for example in the image optimization function
226
+ // We may want to reconsider this in the future, it might be intersting to have access to this store everywhere
227
+ globalThis.__openNextAls
228
+ ?.getStore()
229
+ ?.pendingPromiseRunner.add(this.onEnd(this.headers));
230
+ const bodyLength = this.getBody().length;
231
+ this.streamCreator?.onFinish?.(bodyLength);
232
+ //This is only here because of aws broken streaming implementation.
233
+ //Hopefully one day they will be able to give us a working streaming implementation in lambda for everyone
234
+ //If you're lucky you have a working streaming implementation in your aws account and don't need this
235
+ //If not you can set the OPEN_NEXT_FORCE_NON_EMPTY_RESPONSE env variable to true
236
+ //BE CAREFUL: Aws keeps rolling out broken streaming implementations even on accounts that had working ones before
237
+ //This is not dependent on the node runtime used
238
+ if (bodyLength === 0 &&
239
239
  // We use an env variable here because not all aws account have the same behavior
240
240
  // On some aws accounts the response will hang if the body is empty
241
241
  // We are modifying the response body here, this is not a good practice
@@ -1,6 +1,3 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
- /// <reference types="node" />
4
1
  import http from "node:http";
5
2
  export declare class IncomingMessage extends http.IncomingMessage {
6
3
  constructor({ method, url, headers, body, remoteAddress, }: {
@@ -13,8 +13,10 @@ export class IncomingMessage extends http.IncomingMessage {
13
13
  end: Function.prototype,
14
14
  destroy: Function.prototype,
15
15
  });
16
- if (typeof headers["content-length"] === "undefined") {
17
- headers["content-length"] = Buffer.byteLength(body).toString();
16
+ // Set the content length when there is a body.
17
+ // See https://httpwg.org/specs/rfc9110.html#field.content-length
18
+ if (body) {
19
+ headers["content-length"] ??= String(Buffer.byteLength(body));
18
20
  }
19
21
  Object.assign(this, {
20
22
  ip: remoteAddress,
@@ -1,4 +1,4 @@
1
1
  import type http from "node:http";
2
2
  export declare const parseHeaders: (headers?: http.OutgoingHttpHeader[] | http.OutgoingHttpHeaders) => Record<string, string>;
3
3
  export declare const convertHeader: (header: http.OutgoingHttpHeader) => string;
4
- export declare function parseCookies(cookies?: string | string[]): string[] | undefined;
4
+ export declare function parseCookies(cookies: string | string[] | null | undefined): string[];
package/dist/http/util.js CHANGED
@@ -7,9 +7,7 @@ export const parseHeaders = (headers) => {
7
7
  if (value === undefined) {
8
8
  continue;
9
9
  }
10
- else {
11
- result[key.toLowerCase()] = convertHeader(value);
12
- }
10
+ result[key.toLowerCase()] = convertHeader(value);
13
11
  }
14
12
  return result;
15
13
  };
@@ -17,18 +15,16 @@ export const convertHeader = (header) => {
17
15
  if (typeof header === "string") {
18
16
  return header;
19
17
  }
20
- else if (Array.isArray(header)) {
18
+ if (Array.isArray(header)) {
21
19
  return header.join(",");
22
20
  }
23
- else {
24
- return String(header);
25
- }
21
+ return String(header);
26
22
  };
27
23
  export function parseCookies(cookies) {
28
- if (!cookies)
29
- return;
30
- if (typeof cookies === "string") {
31
- return cookies.split(/(?<!Expires=\w+),/i).map((c) => c.trim());
24
+ if (!cookies) {
25
+ return [];
32
26
  }
33
- return cookies;
27
+ return typeof cookies === "string"
28
+ ? cookies.split(/(?<!Expires=\w+),/i).map((c) => c.trim())
29
+ : cookies;
34
30
  }