@opennextjs/aws 3.8.0 → 3.8.1

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.
@@ -3,6 +3,7 @@ import type { IncomingMessage } from "../../http/index.js";
3
3
  import { OpenNextNodeResponse } from "../../http/openNextResponse.js";
4
4
  import type { FunctionsConfigManifest, MiddlewareManifest } from "../../types/next-types";
5
5
  import type { InternalEvent, InternalResult, RoutingResult, StreamCreator } from "../../types/open-next.js";
6
+ import { ReadableStream } from "node:stream/web";
6
7
  /**
7
8
  *
8
9
  * @__PURE__
@@ -1,9 +1,9 @@
1
1
  import crypto from "node:crypto";
2
2
  import { parse as parseQs, stringify as stringifyQs } from "node:querystring";
3
- import { Readable } from "node:stream";
4
3
  import { BuildId, HtmlPages, NextConfig } from "../../adapters/config/index.js";
5
4
  import { OpenNextNodeResponse } from "../../http/openNextResponse.js";
6
5
  import { getQueryFromIterator, parseHeaders } from "../../http/util.js";
6
+ import { ReadableStream } from "node:stream/web";
7
7
  import { debug, error } from "../../adapters/logger.js";
8
8
  import { isBinaryContentType } from "../../utils/binary.js";
9
9
  import { localizePath } from "./i18n/index.js";
@@ -84,9 +84,15 @@ export function convertRes(res) {
84
84
  const headers = parseHeaders(res.getFixedHeaders());
85
85
  const isBase64Encoded = isBinaryContentType(headers["content-type"]) ||
86
86
  !!headers["content-encoding"];
87
- // We cannot convert the OpenNextNodeResponse to a ReadableStream directly
88
- // You can look in the `aws-lambda.ts` file for some context
89
- const body = Readable.toWeb(Readable.from(res.getBody()));
87
+ const body = new ReadableStream({
88
+ pull(controller) {
89
+ if (!res._chunks || res._chunks.length === 0) {
90
+ controller.close();
91
+ return;
92
+ }
93
+ controller.enqueue(res._chunks.shift());
94
+ },
95
+ });
90
96
  return {
91
97
  type: "core",
92
98
  statusCode,
@@ -11,10 +11,11 @@ export declare class OpenNextNodeResponse extends Transform implements ServerRes
11
11
  statusCode: number;
12
12
  statusMessage: string;
13
13
  headers: OutgoingHttpHeaders;
14
- private _cookies;
15
- private responseStream?;
16
14
  headersSent: boolean;
17
15
  _chunks: Buffer[];
16
+ private _cookies;
17
+ private responseStream?;
18
+ private bodyLength;
18
19
  strictContentLength: boolean;
19
20
  assignSocket(_socket: Socket): void;
20
21
  detachSocket(_socket: Socket): void;
@@ -12,10 +12,11 @@ export class OpenNextNodeResponse extends Transform {
12
12
  statusCode;
13
13
  statusMessage = "";
14
14
  headers = {};
15
- _cookies = [];
16
- responseStream;
17
15
  headersSent = false;
18
16
  _chunks = [];
17
+ _cookies = [];
18
+ responseStream;
19
+ bodyLength = 0;
19
20
  // To comply with the ServerResponse interface :
20
21
  strictContentLength = false;
21
22
  assignSocket(_socket) {
@@ -221,7 +222,12 @@ export class OpenNextNodeResponse extends Transform {
221
222
  return Buffer.concat(this._chunks);
222
223
  }
223
224
  _internalWrite(chunk, encoding) {
224
- this._chunks.push(Buffer.from(chunk, encoding));
225
+ const buffer = Buffer.from(chunk, encoding);
226
+ this.bodyLength += buffer.length;
227
+ if (this.streamCreator?.retainChunks !== false) {
228
+ // Avoid keeping chunks around when the `StreamCreator` supports it to save memory
229
+ this._chunks.push(buffer);
230
+ }
225
231
  this.push(chunk, encoding);
226
232
  this.streamCreator?.onWrite?.();
227
233
  }
@@ -237,19 +243,18 @@ export class OpenNextNodeResponse extends Transform {
237
243
  this.flushHeaders();
238
244
  }
239
245
  // In some cases we might not have a store i.e. for example in the image optimization function
240
- // We may want to reconsider this in the future, it might be intersting to have access to this store everywhere
246
+ // We may want to reconsider this in the future, it might be interesting to have access to this store everywhere
241
247
  globalThis.__openNextAls
242
248
  ?.getStore()
243
249
  ?.pendingPromiseRunner.add(this.onEnd(this.headers));
244
- const bodyLength = this.getBody().length;
245
- this.streamCreator?.onFinish?.(bodyLength);
250
+ this.streamCreator?.onFinish?.(this.bodyLength);
246
251
  //This is only here because of aws broken streaming implementation.
247
252
  //Hopefully one day they will be able to give us a working streaming implementation in lambda for everyone
248
253
  //If you're lucky you have a working streaming implementation in your aws account and don't need this
249
254
  //If not you can set the OPEN_NEXT_FORCE_NON_EMPTY_RESPONSE env variable to true
250
255
  //BE CAREFUL: Aws keeps rolling out broken streaming implementations even on accounts that had working ones before
251
256
  //This is not dependent on the node runtime used
252
- if (bodyLength === 0 &&
257
+ if (this.bodyLength === 0 &&
253
258
  // We use an env variable here because not all aws account have the same behavior
254
259
  // On some aws accounts the response will hang if the body is empty
255
260
  // We are modifying the response body here, this is not a good practice
@@ -283,8 +288,10 @@ export class OpenNextNodeResponse extends Transform {
283
288
  return (Array.isArray(values) ? values : [values]).map((value) => value.toString());
284
289
  }
285
290
  send() {
286
- const body = this.getBody();
287
- this.end(body);
291
+ for (const chunk of this._chunks) {
292
+ this.write(chunk);
293
+ }
294
+ this.end();
288
295
  }
289
296
  body(value) {
290
297
  this.write(value);
package/dist/http/util.js CHANGED
@@ -1,3 +1,4 @@
1
+ import logger from "../logger";
1
2
  export const parseHeaders = (headers) => {
2
3
  const result = {};
3
4
  if (!headers) {
@@ -7,7 +8,26 @@ export const parseHeaders = (headers) => {
7
8
  if (value === undefined) {
8
9
  continue;
9
10
  }
10
- result[key.toLowerCase()] = convertHeader(value);
11
+ const keyLower = key.toLowerCase();
12
+ /**
13
+ * Next can return an Array for the Location header when you return null from a get in the cacheHandler on a page that has a redirect()
14
+ * We dont want to merge that into a comma-separated string
15
+ * If they are the same just return one of them
16
+ * Otherwise return the last one
17
+ * See: https://github.com/opennextjs/opennextjs-cloudflare/issues/875#issuecomment-3258248276
18
+ * and https://github.com/opennextjs/opennextjs-aws/pull/977#issuecomment-3261763114
19
+ */
20
+ if (keyLower === "location" && Array.isArray(value)) {
21
+ if (value[0] === value[1]) {
22
+ result[keyLower] = value[0];
23
+ }
24
+ else {
25
+ logger.warn("Multiple different values for Location header found. Using the last one");
26
+ result[keyLower] = value[value.length - 1];
27
+ }
28
+ continue;
29
+ }
30
+ result[keyLower] = convertHeader(value);
11
31
  }
12
32
  return result;
13
33
  };
@@ -42,6 +42,8 @@ const handler = async (handler, converter) => async (request, env, ctx, abortSig
42
42
  // Ensures that the response we pass to NextServer is aborted if the request is aborted
43
43
  // By doing this `request.signal.onabort` will work in route handlers
44
44
  abortSignal: abortSignal,
45
+ // There is no need to retain the chunks that were pushed to the response stream.
46
+ retainChunks: false,
45
47
  };
46
48
  ctx.waitUntil(handler(internalEvent, {
47
49
  streamCreator,
@@ -36,6 +36,18 @@ export interface StreamCreator {
36
36
  onWrite?: () => void;
37
37
  onFinish?: (length: number) => void;
38
38
  abortSignal?: AbortSignal;
39
+ /**
40
+ * Normally there is no need to retain the chunks that have been pushed to the response stream.
41
+ *
42
+ * However some implementations use a fake `StreamCreator` and expect the chunks to be retained.
43
+ * When your stream controller implementation doesn't need to retain the chunk, you can set this
44
+ * to `false` to reduce memory usage.
45
+ *
46
+ * @see https://github.com/opennextjs/opennextjs-aws/blob/main/packages/open-next/src/overrides/wrappers/aws-lambda.ts
47
+ *
48
+ * @default true for backward compatibility.
49
+ */
50
+ retainChunks?: boolean;
39
51
  }
40
52
  export type WaitUntil = (promise: Promise<void>) => void;
41
53
  export interface DangerousOptions {
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "access": "public"
4
4
  },
5
5
  "name": "@opennextjs/aws",
6
- "version": "3.8.0",
6
+ "version": "3.8.1",
7
7
  "bin": {
8
8
  "open-next": "./dist/index.js"
9
9
  },