@opennextjs/aws 3.4.2 → 3.5.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.
Files changed (82) hide show
  1. package/dist/adapters/cache.d.ts +2 -61
  2. package/dist/adapters/cache.js +68 -34
  3. package/dist/adapters/config/index.d.ts +1 -0
  4. package/dist/adapters/config/index.js +3 -1
  5. package/dist/adapters/config/util.d.ts +2 -1
  6. package/dist/adapters/config/util.js +13 -3
  7. package/dist/adapters/dynamo-provider.js +8 -0
  8. package/dist/adapters/edge-adapter.js +4 -10
  9. package/dist/adapters/image-optimization-adapter.d.ts +3 -2
  10. package/dist/adapters/image-optimization-adapter.js +3 -3
  11. package/dist/adapters/middleware.js +12 -8
  12. package/dist/build/compileConfig.js +1 -1
  13. package/dist/build/compileTagCacheProvider.js +1 -0
  14. package/dist/build/constant.d.ts +1 -0
  15. package/dist/build/constant.js +2 -0
  16. package/dist/build/copyTracedFiles.d.ts +10 -1
  17. package/dist/build/copyTracedFiles.js +22 -12
  18. package/dist/build/createAssets.d.ts +3 -1
  19. package/dist/build/createAssets.js +2 -2
  20. package/dist/build/createMiddleware.js +18 -5
  21. package/dist/build/createServerBundle.js +7 -1
  22. package/dist/build/edge/createEdgeBundle.js +14 -12
  23. package/dist/build/generateOutput.js +4 -6
  24. package/dist/build/middleware/buildNodeMiddleware.d.ts +3 -0
  25. package/dist/build/middleware/buildNodeMiddleware.js +97 -0
  26. package/dist/core/createMainHandler.js +0 -1
  27. package/dist/core/edgeFunctionHandler.js +3 -1
  28. package/dist/core/nodeMiddlewareHandler.d.ts +4 -0
  29. package/dist/core/nodeMiddlewareHandler.js +25 -0
  30. package/dist/core/requestHandler.d.ts +3 -2
  31. package/dist/core/requestHandler.js +58 -25
  32. package/dist/core/routing/cacheInterceptor.js +7 -6
  33. package/dist/core/routing/i18n/index.d.ts +29 -1
  34. package/dist/core/routing/i18n/index.js +98 -4
  35. package/dist/core/routing/matcher.js +17 -13
  36. package/dist/core/routing/middleware.js +14 -29
  37. package/dist/core/routing/queue.d.ts +1 -0
  38. package/dist/core/routing/queue.js +41 -0
  39. package/dist/core/routing/util.d.ts +12 -3
  40. package/dist/core/routing/util.js +25 -50
  41. package/dist/core/routingHandler.d.ts +2 -1
  42. package/dist/core/routingHandler.js +10 -4
  43. package/dist/core/util.d.ts +1 -4
  44. package/dist/core/util.js +7 -15
  45. package/dist/overrides/converters/aws-apigw-v1.js +4 -3
  46. package/dist/overrides/converters/aws-apigw-v2.js +4 -3
  47. package/dist/overrides/converters/aws-cloudfront.js +6 -4
  48. package/dist/overrides/converters/edge.js +1 -10
  49. package/dist/overrides/converters/node.js +10 -8
  50. package/dist/overrides/converters/utils.d.ts +7 -0
  51. package/dist/overrides/converters/utils.js +9 -0
  52. package/dist/overrides/imageLoader/s3-lite.d.ts +3 -0
  53. package/dist/overrides/imageLoader/s3-lite.js +61 -0
  54. package/dist/overrides/tagCache/dummy.js +1 -0
  55. package/dist/overrides/tagCache/dynamodb-lite.js +1 -0
  56. package/dist/overrides/tagCache/dynamodb-nextMode.d.ts +7 -0
  57. package/dist/overrides/tagCache/dynamodb-nextMode.js +119 -0
  58. package/dist/overrides/tagCache/dynamodb.js +1 -0
  59. package/dist/overrides/tagCache/fs-dev.js +1 -0
  60. package/dist/overrides/wrappers/aws-lambda-streaming.js +1 -1
  61. package/dist/overrides/wrappers/aws-lambda.js +3 -1
  62. package/dist/overrides/wrappers/cloudflare-edge.js +3 -2
  63. package/dist/overrides/wrappers/cloudflare-node.js +5 -8
  64. package/dist/overrides/wrappers/dummy.js +2 -2
  65. package/dist/overrides/wrappers/express-dev.js +4 -4
  66. package/dist/overrides/wrappers/node.js +2 -2
  67. package/dist/plugins/edge.d.ts +1 -3
  68. package/dist/plugins/edge.js +4 -11
  69. package/dist/plugins/externalMiddleware.d.ts +2 -0
  70. package/dist/plugins/externalMiddleware.js +10 -0
  71. package/dist/plugins/resolve.js +2 -2
  72. package/dist/types/cache.d.ts +34 -4
  73. package/dist/types/global.d.ts +19 -31
  74. package/dist/types/next-types.d.ts +20 -0
  75. package/dist/types/open-next.d.ts +12 -5
  76. package/dist/types/overrides.d.ts +72 -6
  77. package/dist/utils/cache.d.ts +3 -0
  78. package/dist/utils/cache.js +32 -0
  79. package/dist/utils/promise.d.ts +3 -1
  80. package/dist/utils/promise.js +18 -11
  81. package/dist/utils/regex.js +1 -1
  82. package/package.json +5 -4
@@ -2,7 +2,7 @@ import { parseCookies } from "../../http/util";
2
2
  import { fromReadableStream } from "../../utils/stream";
3
3
  import { debug } from "../../adapters/logger";
4
4
  import { convertToQuery } from "../../core/routing/util";
5
- import { removeUndefinedFromQuery } from "./utils";
5
+ import { extractHostFromHeaders, removeUndefinedFromQuery } from "./utils";
6
6
  // Not sure which one is really needed as this is not documented anywhere but server actions redirect are not working without this,
7
7
  // it causes a 500 error from cloudfront itself with a 'x-amzErrortype: InternalFailure' header
8
8
  const CloudFrontBlacklistedHeaders = [
@@ -54,13 +54,14 @@ function normalizeAPIGatewayProxyEventV2Headers(event) {
54
54
  }
55
55
  async function convertFromAPIGatewayProxyEventV2(event) {
56
56
  const { rawPath, rawQueryString, requestContext } = event;
57
+ const headers = normalizeAPIGatewayProxyEventV2Headers(event);
57
58
  return {
58
59
  type: "core",
59
60
  method: requestContext.http.method,
60
61
  rawPath,
61
- url: rawPath + (rawQueryString ? `?${rawQueryString}` : ""),
62
+ url: `https://${extractHostFromHeaders(headers)}${rawPath}${rawQueryString ? `?${rawQueryString}` : ""}`,
62
63
  body: normalizeAPIGatewayProxyEventV2Body(event),
63
- headers: normalizeAPIGatewayProxyEventV2Headers(event),
64
+ headers,
64
65
  remoteAddress: requestContext.http.sourceIp,
65
66
  query: removeUndefinedFromQuery(convertToQuery(rawQueryString)),
66
67
  cookies: event.cookies?.reduce((acc, cur) => {
@@ -2,6 +2,7 @@ import { parseCookies } from "../../http/util";
2
2
  import { fromReadableStream } from "../../utils/stream";
3
3
  import { debug } from "../../adapters/logger";
4
4
  import { convertToQuery, convertToQueryString } from "../../core/routing/util";
5
+ import { extractHostFromHeaders } from "./utils";
5
6
  const cloudfrontBlacklistedHeaders = [
6
7
  // Disallowed headers, see: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-function-restrictions-all.html#function-restrictions-disallowed-headers
7
8
  "connection",
@@ -56,17 +57,18 @@ function normalizeCloudFrontRequestEventHeaders(rawHeaders) {
56
57
  return headers;
57
58
  }
58
59
  async function convertFromCloudFrontRequestEvent(event) {
59
- const { method, uri, querystring, body, headers, clientIp } = event.Records[0].cf.request;
60
+ const { method, uri, querystring, body, headers: cfHeaders, clientIp, } = event.Records[0].cf.request;
61
+ const headers = normalizeCloudFrontRequestEventHeaders(cfHeaders);
60
62
  return {
61
63
  type: "core",
62
64
  method,
63
65
  rawPath: uri,
64
- url: uri + (querystring ? `?${querystring}` : ""),
66
+ url: `https://${extractHostFromHeaders(headers)}${uri}${querystring ? `?${querystring}` : ""}`,
65
67
  body: Buffer.from(body?.data ?? "", body?.encoding === "base64" ? "base64" : "utf8"),
66
- headers: normalizeCloudFrontRequestEventHeaders(headers),
68
+ headers,
67
69
  remoteAddress: clientIp,
68
70
  query: convertToQuery(querystring),
69
- cookies: headers.cookie?.reduce((acc, cur) => {
71
+ cookies: cfHeaders.cookie?.reduce((acc, cur) => {
70
72
  const { key = "", value } = cur;
71
73
  acc[key] = value;
72
74
  return acc;
@@ -42,16 +42,7 @@ const converter = {
42
42
  },
43
43
  convertTo: async (result) => {
44
44
  if ("internalEvent" in result) {
45
- let url = result.internalEvent.url;
46
- if (!result.isExternalRewrite) {
47
- if (result.origin) {
48
- url = `${result.origin.protocol}://${result.origin.host}${result.origin.port ? `:${result.origin.port}` : ""}${url}`;
49
- }
50
- else {
51
- url = `https://${result.internalEvent.headers.host}${url}`;
52
- }
53
- }
54
- const request = new Request(url, {
45
+ const request = new Request(result.internalEvent.url, {
55
46
  body: result.internalEvent.body,
56
47
  method: result.internalEvent.method,
57
48
  headers: {
@@ -1,4 +1,5 @@
1
1
  import { parseCookies } from "../../http/util";
2
+ import { extractHostFromHeaders } from "./utils";
2
3
  const converter = {
3
4
  convertFrom: async (req) => {
4
5
  const body = await new Promise((resolve) => {
@@ -10,20 +11,21 @@ const converter = {
10
11
  resolve(Buffer.concat(chunks));
11
12
  });
12
13
  });
13
- const url = new URL(req.url, `http://${req.headers.host}`);
14
+ const headers = Object.fromEntries(Object.entries(req.headers ?? {})
15
+ .map(([key, value]) => [
16
+ key.toLowerCase(),
17
+ Array.isArray(value) ? value.join(",") : value,
18
+ ])
19
+ .filter(([key]) => key));
20
+ const url = new URL(req.url, `http://${extractHostFromHeaders(headers)}`);
14
21
  const query = Object.fromEntries(url.searchParams.entries());
15
22
  return {
16
23
  type: "core",
17
24
  method: req.method ?? "GET",
18
25
  rawPath: url.pathname,
19
- url: url.pathname + url.search,
26
+ url: url.href,
20
27
  body,
21
- headers: Object.fromEntries(Object.entries(req.headers ?? {})
22
- .map(([key, value]) => [
23
- key.toLowerCase(),
24
- Array.isArray(value) ? value.join(",") : value,
25
- ])
26
- .filter(([key]) => key)),
28
+ headers,
27
29
  remoteAddress: req.headers["x-forwarded-for"] ??
28
30
  req.socket.remoteAddress ??
29
31
  "::1",
@@ -1 +1,8 @@
1
1
  export declare function removeUndefinedFromQuery(query: Record<string, string | string[] | undefined>): Record<string, string | string[]>;
2
+ /**
3
+ * Extract the host from the headers (default to "on")
4
+ *
5
+ * @param headers
6
+ * @returns The host
7
+ */
8
+ export declare function extractHostFromHeaders(headers: Record<string, string>): string;
@@ -7,3 +7,12 @@ export function removeUndefinedFromQuery(query) {
7
7
  }
8
8
  return newQuery;
9
9
  }
10
+ /**
11
+ * Extract the host from the headers (default to "on")
12
+ *
13
+ * @param headers
14
+ * @returns The host
15
+ */
16
+ export function extractHostFromHeaders(headers) {
17
+ return headers["x-forwarded-host"] ?? headers.host ?? "on";
18
+ }
@@ -0,0 +1,3 @@
1
+ import type { ImageLoader } from "../../types/overrides";
2
+ declare const s3Loader: ImageLoader;
3
+ export default s3Loader;
@@ -0,0 +1,61 @@
1
+ import { Readable } from "node:stream";
2
+ import { AwsClient } from "aws4fetch";
3
+ import { FatalError } from "../../utils/error";
4
+ let awsClient = null;
5
+ const { BUCKET_NAME, BUCKET_KEY_PREFIX } = process.env;
6
+ // https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime
7
+ // If AWS_REGION is defined it will override AWS_DEFAULT_REGION
8
+ const BUCKET_REGION = process.env.BUCKET_REGION ??
9
+ process.env.AWS_REGION ??
10
+ process.env.AWS_DEFAULT_REGION;
11
+ const getAwsClient = () => {
12
+ if (awsClient) {
13
+ return awsClient;
14
+ }
15
+ awsClient = new AwsClient({
16
+ accessKeyId: process.env.AWS_ACCESS_KEY_ID,
17
+ secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
18
+ sessionToken: process.env.AWS_SESSION_TOKEN,
19
+ region: BUCKET_REGION,
20
+ });
21
+ return awsClient;
22
+ };
23
+ function ensureEnvExists() {
24
+ if (!(BUCKET_NAME || BUCKET_KEY_PREFIX || BUCKET_REGION)) {
25
+ throw new FatalError("Bucket name, region and key prefix must be defined!");
26
+ }
27
+ }
28
+ const awsFetch = async (key, options) => {
29
+ const client = getAwsClient();
30
+ const url = `https://${BUCKET_NAME}.s3.${BUCKET_REGION}.amazonaws.com/${key}`;
31
+ return client.fetch(url, options);
32
+ };
33
+ const s3Loader = {
34
+ name: "s3-lite",
35
+ load: async (key) => {
36
+ ensureEnvExists();
37
+ const keyPrefix = BUCKET_KEY_PREFIX?.replace(/^\/|\/$/g, "");
38
+ const response = await awsFetch(keyPrefix
39
+ ? `${keyPrefix}/${key.replace(/^\//, "")}`
40
+ : key.replace(/^\//, ""), {
41
+ method: "GET",
42
+ });
43
+ if (response.status === 404) {
44
+ throw new FatalError("The specified key does not exist.");
45
+ }
46
+ if (response.status !== 200) {
47
+ throw new FatalError(`Failed to get image. Status code: ${response.status}`);
48
+ }
49
+ if (!response.body) {
50
+ throw new FatalError("No body in aws4fetch s3 response");
51
+ }
52
+ // We need to cast it else there will be a TypeError: o.pipe is not a function
53
+ const body = Readable.fromWeb(response.body);
54
+ return {
55
+ body: body,
56
+ contentType: response.headers.get("content-type") ?? undefined,
57
+ cacheControl: response.headers.get("cache-control") ?? undefined,
58
+ };
59
+ },
60
+ };
61
+ export default s3Loader;
@@ -1,6 +1,7 @@
1
1
  // We don't want to throw error on this one because we might use it when we don't need tag cache
2
2
  const dummyTagCache = {
3
3
  name: "dummy",
4
+ mode: "original",
4
5
  getByPath: async () => {
5
6
  return [];
6
7
  },
@@ -47,6 +47,7 @@ function buildDynamoObject(path, tags, revalidatedAt) {
47
47
  };
48
48
  }
49
49
  const tagCache = {
50
+ mode: "original",
50
51
  async getByPath(path) {
51
52
  try {
52
53
  if (globalThis.openNextConfig.dangerous?.disableTagCache) {
@@ -0,0 +1,7 @@
1
+ declare const _default: {
2
+ name: string;
3
+ mode: "nextMode";
4
+ hasBeenRevalidated: (tags: string[], lastModified?: number) => Promise<boolean>;
5
+ writeTags: (tags: string[]) => Promise<void>;
6
+ };
7
+ export default _default;
@@ -0,0 +1,119 @@
1
+ import { AwsClient } from "aws4fetch";
2
+ import { RecoverableError } from "../../utils/error";
3
+ import { customFetchClient } from "../../utils/fetch";
4
+ import path from "node:path";
5
+ import { debug, error } from "../../adapters/logger";
6
+ import { chunk, parseNumberFromEnv } from "../../adapters/util";
7
+ import { MAX_DYNAMO_BATCH_WRITE_ITEM_COUNT, getDynamoBatchWriteCommandConcurrency, } from "./constants";
8
+ let awsClient = null;
9
+ const getAwsClient = () => {
10
+ const { CACHE_BUCKET_REGION } = process.env;
11
+ if (awsClient) {
12
+ return awsClient;
13
+ }
14
+ awsClient = new AwsClient({
15
+ accessKeyId: process.env.AWS_ACCESS_KEY_ID,
16
+ secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
17
+ sessionToken: process.env.AWS_SESSION_TOKEN,
18
+ region: CACHE_BUCKET_REGION,
19
+ retries: parseNumberFromEnv(process.env.AWS_SDK_S3_MAX_ATTEMPTS),
20
+ });
21
+ return awsClient;
22
+ };
23
+ const awsFetch = (body, type = "query") => {
24
+ const { CACHE_BUCKET_REGION } = process.env;
25
+ const client = getAwsClient();
26
+ return customFetchClient(client)(`https://dynamodb.${CACHE_BUCKET_REGION}.amazonaws.com`, {
27
+ method: "POST",
28
+ headers: {
29
+ "Content-Type": "application/x-amz-json-1.0",
30
+ "X-Amz-Target": `DynamoDB_20120810.${type === "query" ? "BatchGetItem" : "BatchWriteItem"}`,
31
+ },
32
+ body,
33
+ });
34
+ };
35
+ function buildDynamoKey(key) {
36
+ const { NEXT_BUILD_ID } = process.env;
37
+ // FIXME: We should probably use something else than path.join here
38
+ // this could transform some fetch cache key into a valid path
39
+ return path.posix.join(NEXT_BUILD_ID ?? "", "_tag", key);
40
+ }
41
+ // We use the same key for both path and tag
42
+ // That's mostly for compatibility reason so that it's easier to use this with existing infra
43
+ // FIXME: Allow a simpler object without an unnecessary path key
44
+ function buildDynamoObject(tag, revalidatedAt) {
45
+ return {
46
+ path: { S: buildDynamoKey(tag) },
47
+ tag: { S: buildDynamoKey(tag) },
48
+ revalidatedAt: { N: `${revalidatedAt ?? Date.now()}` },
49
+ };
50
+ }
51
+ // This implementation does not support automatic invalidation of paths by the cdn
52
+ export default {
53
+ name: "ddb-nextMode",
54
+ mode: "nextMode",
55
+ hasBeenRevalidated: async (tags, lastModified) => {
56
+ if (globalThis.openNextConfig.dangerous?.disableTagCache) {
57
+ return false;
58
+ }
59
+ if (tags.length > 100) {
60
+ throw new RecoverableError("Cannot query more than 100 tags at once. You should not be using this tagCache implementation for this amount of tags");
61
+ }
62
+ const { CACHE_DYNAMO_TABLE } = process.env;
63
+ // It's unlikely that we will have more than 100 items to query
64
+ // If that's the case, you should not use this tagCache implementation
65
+ const response = await awsFetch(JSON.stringify({
66
+ RequestItems: {
67
+ [CACHE_DYNAMO_TABLE ?? ""]: {
68
+ Keys: tags.map((tag) => ({
69
+ path: { S: buildDynamoKey(tag) },
70
+ tag: { S: buildDynamoKey(tag) },
71
+ })),
72
+ },
73
+ },
74
+ }), "query");
75
+ if (response.status !== 200) {
76
+ throw new RecoverableError(`Failed to query dynamo item: ${response.status}`);
77
+ }
78
+ // Now we need to check for every item if lastModified is greater than the revalidatedAt
79
+ const { Responses } = await response.json();
80
+ if (!Responses) {
81
+ return false;
82
+ }
83
+ const revalidatedTags = Responses[CACHE_DYNAMO_TABLE ?? ""].filter((item) => Number.parseInt(item.revalidatedAt.N) > (lastModified ?? 0));
84
+ debug("retrieved tags", revalidatedTags);
85
+ return revalidatedTags.length > 0;
86
+ },
87
+ writeTags: async (tags) => {
88
+ try {
89
+ const { CACHE_DYNAMO_TABLE } = process.env;
90
+ if (globalThis.openNextConfig.dangerous?.disableTagCache) {
91
+ return;
92
+ }
93
+ const dataChunks = chunk(tags, MAX_DYNAMO_BATCH_WRITE_ITEM_COUNT).map((Items) => ({
94
+ RequestItems: {
95
+ [CACHE_DYNAMO_TABLE ?? ""]: Items.map((tag) => ({
96
+ PutRequest: {
97
+ Item: {
98
+ ...buildDynamoObject(tag),
99
+ },
100
+ },
101
+ })),
102
+ },
103
+ }));
104
+ const toInsert = chunk(dataChunks, getDynamoBatchWriteCommandConcurrency());
105
+ for (const paramsChunk of toInsert) {
106
+ await Promise.all(paramsChunk.map(async (params) => {
107
+ const response = await awsFetch(JSON.stringify(params), "batchWrite");
108
+ if (response.status !== 200) {
109
+ throw new RecoverableError(`Failed to batch write dynamo item: ${response.status}`);
110
+ }
111
+ return response;
112
+ }));
113
+ }
114
+ }
115
+ catch (e) {
116
+ error("Failed to batch write dynamo item", e);
117
+ }
118
+ },
119
+ };
@@ -25,6 +25,7 @@ function buildDynamoObject(path, tags, revalidatedAt) {
25
25
  };
26
26
  }
27
27
  const tagCache = {
28
+ mode: "original",
28
29
  async getByPath(path) {
29
30
  try {
30
31
  if (globalThis.openNextConfig.dangerous?.disableTagCache) {
@@ -4,6 +4,7 @@ const tagContent = fs.readFileSync(tagFile, "utf-8");
4
4
  let tags = JSON.parse(tagContent);
5
5
  const tagCache = {
6
6
  name: "fs-dev",
7
+ mode: "original",
7
8
  getByPath: async (path) => {
8
9
  return tags
9
10
  .filter((tagPathMapping) => tagPathMapping.path.S === path)
@@ -63,7 +63,7 @@ const handler = async (handler, converter) => awslambda.streamifyResponse(async
63
63
  return compressedStream ?? responseStream;
64
64
  },
65
65
  };
66
- const response = await handler(internalEvent, streamCreator);
66
+ const response = await handler(internalEvent, { streamCreator });
67
67
  const isUsingEdge = globalThis.isEdgeRuntime ?? false;
68
68
  if (isUsingEdge) {
69
69
  debug("Headers has not been set, we must be in the edge runtime");
@@ -26,7 +26,9 @@ const handler = async (handler, converter) => async (event) => {
26
26
  });
27
27
  },
28
28
  };
29
- const response = await handler(internalEvent, fakeStream);
29
+ const response = await handler(internalEvent, {
30
+ streamCreator: fakeStream,
31
+ });
30
32
  return converter.convertTo(response, event);
31
33
  };
32
34
  export default {
@@ -9,7 +9,6 @@ const cfPropNameMapping = {
9
9
  };
10
10
  const handler = async (handler, converter) => async (request, env, ctx) => {
11
11
  globalThis.process = process;
12
- globalThis.openNextWaitUntil = ctx.waitUntil.bind(ctx);
13
12
  // Set the environment variables
14
13
  // Cloudflare suggests to not override the process.env object but instead apply the values to it
15
14
  for (const [key, value] of Object.entries(env)) {
@@ -33,7 +32,9 @@ const handler = async (handler, converter) => async (request, env, ctx) => {
33
32
  : propValue;
34
33
  }
35
34
  }
36
- const response = await handler(internalEvent);
35
+ const response = await handler(internalEvent, {
36
+ waitUntil: ctx.waitUntil.bind(ctx),
37
+ });
37
38
  const result = await converter.convertTo(response);
38
39
  return result;
39
40
  };
@@ -3,7 +3,6 @@ import { Writable } from "node:stream";
3
3
  const NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
4
4
  const handler = async (handler, converter) => async (request, env, ctx) => {
5
5
  globalThis.process = process;
6
- globalThis.openNextWaitUntil = ctx.waitUntil.bind(ctx);
7
6
  // Set the environment variables
8
7
  // Cloudflare suggests to not override the process.env object but instead apply the values to it
9
8
  for (const [key, value] of Object.entries(env)) {
@@ -12,12 +11,7 @@ const handler = async (handler, converter) => async (request, env, ctx) => {
12
11
  }
13
12
  }
14
13
  const internalEvent = await converter.convertFrom(request);
15
- // TODO:
16
- // The edge converter populate event.url with the url including the origin.
17
- // This is required for middleware to keep track of the protocol (i.e. http with wrangler dev).
18
- // However the server expects that the origin is not included.
19
- const url = new URL(internalEvent.url);
20
- internalEvent.url = url.href.slice(url.origin.length);
14
+ const url = new URL(request.url);
21
15
  const { promise: promiseResponse, resolve: resolveResponse } = Promise.withResolvers();
22
16
  const streamCreator = {
23
17
  writeHeaders(prelude) {
@@ -45,7 +39,10 @@ const handler = async (handler, converter) => async (request, env, ctx) => {
45
39
  return Writable.fromWeb(writable);
46
40
  },
47
41
  };
48
- ctx.waitUntil(handler(internalEvent, streamCreator));
42
+ ctx.waitUntil(handler(internalEvent, {
43
+ streamCreator,
44
+ waitUntil: ctx.waitUntil.bind(ctx),
45
+ }));
49
46
  return promiseResponse;
50
47
  };
51
48
  export default {
@@ -1,6 +1,6 @@
1
1
  const dummyWrapper = async (handler, converter) => {
2
- return async (event, responseStream) => {
3
- return await handler(event, responseStream);
2
+ return async (event, options) => {
3
+ return await handler(event, options);
4
4
  };
5
5
  };
6
6
  export default {
@@ -7,24 +7,24 @@ const wrapper = async (handler, converter) => {
7
7
  const imageHandler = await import(imageHandlerPath).then((m) => m.handler);
8
8
  app.all("/_next/image", async (req, res) => {
9
9
  const internalEvent = await converter.convertFrom(req);
10
- const _res = {
10
+ const streamCreator = {
11
11
  writeHeaders: (prelude) => {
12
12
  res.writeHead(prelude.statusCode, prelude.headers);
13
13
  return res;
14
14
  },
15
15
  };
16
- await imageHandler(internalEvent, _res);
16
+ await imageHandler(internalEvent, { streamCreator });
17
17
  });
18
18
  app.all("*paths", async (req, res) => {
19
19
  const internalEvent = await converter.convertFrom(req);
20
- const _res = {
20
+ const streamCreator = {
21
21
  writeHeaders: (prelude) => {
22
22
  res.writeHead(prelude.statusCode, prelude.headers);
23
23
  return res;
24
24
  },
25
25
  onFinish: () => { },
26
26
  };
27
- await handler(internalEvent, _res);
27
+ await handler(internalEvent, { streamCreator });
28
28
  });
29
29
  const server = app.listen(Number.parseInt(process.env.PORT ?? "3000", 10), () => {
30
30
  console.log(`Server running on port ${process.env.PORT ?? 3000}`);
@@ -3,7 +3,7 @@ import { debug, error } from "../../adapters/logger";
3
3
  const wrapper = async (handler, converter) => {
4
4
  const server = createServer(async (req, res) => {
5
5
  const internalEvent = await converter.convertFrom(req);
6
- const _res = {
6
+ const streamCreator = {
7
7
  writeHeaders: (prelude) => {
8
8
  res.setHeader("Set-Cookie", prelude.cookies);
9
9
  res.writeHead(prelude.statusCode, prelude.headers);
@@ -19,7 +19,7 @@ const wrapper = async (handler, converter) => {
19
19
  res.end("OK");
20
20
  }
21
21
  else {
22
- await handler(internalEvent, _res);
22
+ await handler(internalEvent, { streamCreator });
23
23
  }
24
24
  });
25
25
  await new Promise((resolve) => {
@@ -2,15 +2,13 @@ import type { Plugin } from "esbuild";
2
2
  import type { MiddlewareInfo } from "../types/next-types.js";
3
3
  export interface IPluginSettings {
4
4
  nextDir: string;
5
- edgeFunctionHandlerPath?: string;
6
5
  middlewareInfo?: MiddlewareInfo;
7
6
  isInCloudfare?: boolean;
8
7
  }
9
8
  /**
10
9
  * @param opts.nextDir - The path to the .next directory
11
- * @param opts.edgeFunctionHandlerPath - The path to the edgeFunctionHandler.js file that we'll use to bundle the routing
12
10
  * @param opts.middlewareInfo - Information about the middleware
13
11
  * @param opts.isInCloudfare - Whether the code runs on the cloudflare runtime
14
12
  * @returns
15
13
  */
16
- export declare function openNextEdgePlugins({ nextDir, edgeFunctionHandlerPath, middlewareInfo, isInCloudfare, }: IPluginSettings): Plugin;
14
+ export declare function openNextEdgePlugins({ nextDir, middlewareInfo, isInCloudfare, }: IPluginSettings): Plugin;
@@ -1,17 +1,16 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import chalk from "chalk";
4
- import { loadAppPathRoutesManifest, loadAppPathsManifest, loadAppPathsManifestKeys, loadBuildId, loadConfig, loadConfigHeaders, loadHtmlPages, loadMiddlewareManifest, loadPrerenderManifest, loadRoutesManifest, } from "../adapters/config/util.js";
4
+ import { loadAppPathRoutesManifest, loadAppPathsManifest, loadAppPathsManifestKeys, loadBuildId, loadConfig, loadConfigHeaders, loadFunctionsConfigManifest, loadHtmlPages, loadMiddlewareManifest, loadPrerenderManifest, loadRoutesManifest, } from "../adapters/config/util.js";
5
5
  import logger from "../logger.js";
6
6
  import { getCrossPlatformPathRegex } from "../utils/regex.js";
7
7
  /**
8
8
  * @param opts.nextDir - The path to the .next directory
9
- * @param opts.edgeFunctionHandlerPath - The path to the edgeFunctionHandler.js file that we'll use to bundle the routing
10
9
  * @param opts.middlewareInfo - Information about the middleware
11
10
  * @param opts.isInCloudfare - Whether the code runs on the cloudflare runtime
12
11
  * @returns
13
12
  */
14
- export function openNextEdgePlugins({ nextDir, edgeFunctionHandlerPath, middlewareInfo, isInCloudfare, }) {
13
+ export function openNextEdgePlugins({ nextDir, middlewareInfo, isInCloudfare, }) {
15
14
  const entryFiles = middlewareInfo?.files.map((file) => path.join(nextDir, file)) ?? [];
16
15
  const routes = middlewareInfo
17
16
  ? [
@@ -27,14 +26,6 @@ export function openNextEdgePlugins({ nextDir, edgeFunctionHandlerPath, middlewa
27
26
  name: "opennext-edge",
28
27
  setup(build) {
29
28
  logger.debug(chalk.blue("OpenNext Edge plugin"));
30
- if (edgeFunctionHandlerPath) {
31
- // If we bundle the routing, we need to resolve the middleware
32
- build.onResolve({ filter: getCrossPlatformPathRegex("./middleware.mjs") }, () => {
33
- return {
34
- path: edgeFunctionHandlerPath,
35
- };
36
- });
37
- }
38
29
  build.onResolve({ filter: /\.(mjs|wasm)$/g }, () => {
39
30
  return {
40
31
  external: true,
@@ -129,6 +120,7 @@ ${contents}
129
120
  const MiddlewareManifest = loadMiddlewareManifest(nextDir);
130
121
  const AppPathsManifest = loadAppPathsManifest(nextDir);
131
122
  const AppPathRoutesManifest = loadAppPathRoutesManifest(nextDir);
123
+ const FunctionsConfigManifest = loadFunctionsConfigManifest(nextDir);
132
124
  const contents = `
133
125
  import path from "node:path";
134
126
 
@@ -151,6 +143,7 @@ ${contents}
151
143
  export const MiddlewareManifest = ${JSON.stringify(MiddlewareManifest)};
152
144
  export const AppPathsManifest = ${JSON.stringify(AppPathsManifest)};
153
145
  export const AppPathRoutesManifest = ${JSON.stringify(AppPathRoutesManifest)};
146
+ export const FunctionsConfigManifest = ${JSON.stringify(FunctionsConfigManifest)};
154
147
 
155
148
 
156
149
  process.env.NEXT_BUILD_ID = BuildId;
@@ -0,0 +1,2 @@
1
+ import type { Plugin } from "esbuild";
2
+ export declare function openNextExternalMiddlewarePlugin(functionPath: string): Plugin;
@@ -0,0 +1,10 @@
1
+ import { getCrossPlatformPathRegex } from "../utils/regex.js";
2
+ export function openNextExternalMiddlewarePlugin(functionPath) {
3
+ return {
4
+ name: "open-next-external-node-middleware",
5
+ setup(build) {
6
+ // If we bundle the routing, we need to resolve the middleware
7
+ build.onResolve({ filter: getCrossPlatformPathRegex("./middleware.mjs") }, () => ({ path: functionPath }));
8
+ },
9
+ };
10
+ }
@@ -1,4 +1,4 @@
1
- import { readFileSync } from "node:fs";
1
+ import { readFile } from "node:fs/promises";
2
2
  import chalk from "chalk";
3
3
  import logger from "../logger.js";
4
4
  import { getCrossPlatformPathRegex } from "../utils/regex.js";
@@ -44,7 +44,7 @@ export function openNextResolvePlugin({ overrides, fnName, }) {
44
44
  setup(build) {
45
45
  logger.debug(chalk.blue("OpenNext Resolve plugin"), fnName ? `for ${fnName}` : "");
46
46
  build.onLoad({ filter: getCrossPlatformPathRegex("core/resolve.js") }, async (args) => {
47
- let contents = readFileSync(args.path, "utf-8");
47
+ let contents = await readFile(args.path, "utf-8");
48
48
  const overridesEntries = Object.entries(overrides ?? {});
49
49
  for (let [overrideName, overrideValue] of overridesEntries) {
50
50
  if (!overrideValue) {