@opennextjs/aws 3.1.6 → 3.2.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 (152) hide show
  1. package/README.md +27 -22
  2. package/dist/adapters/binary.js +2 -0
  3. package/dist/adapters/cache.d.ts +4 -2
  4. package/dist/adapters/cache.js +14 -8
  5. package/dist/adapters/config/util.d.ts +2 -2
  6. package/dist/adapters/image-optimization-adapter.d.ts +2 -2
  7. package/dist/adapters/middleware.js +5 -52
  8. package/dist/adapters/plugins/image-optimization/image-optimization.d.ts +7 -4
  9. package/dist/adapters/plugins/image-optimization/image-optimization.js +2 -3
  10. package/dist/adapters/plugins/image-optimization/image-optimization.replacement.d.ts +3 -0
  11. package/dist/adapters/plugins/image-optimization/image-optimization.replacement.js +4 -7
  12. package/dist/adapters/warmer-function.js +2 -67
  13. package/dist/build/buildNextApp.d.ts +3 -0
  14. package/dist/build/buildNextApp.js +19 -0
  15. package/dist/build/bundleNextServer.js +2 -2
  16. package/dist/build/compileCache.d.ts +9 -0
  17. package/dist/build/compileCache.js +30 -0
  18. package/dist/build/compileConfig.d.ts +17 -3
  19. package/dist/build/compileConfig.js +56 -34
  20. package/dist/build/compileTagCacheProvider.d.ts +2 -0
  21. package/dist/build/compileTagCacheProvider.js +26 -0
  22. package/dist/build/copyTracedFiles.js +2 -2
  23. package/dist/build/createAssets.d.ts +11 -0
  24. package/dist/build/createAssets.js +161 -0
  25. package/dist/build/createImageOptimizationBundle.d.ts +2 -0
  26. package/dist/build/createImageOptimizationBundle.js +82 -0
  27. package/dist/build/createMiddleware.d.ts +10 -0
  28. package/dist/build/createMiddleware.js +47 -0
  29. package/dist/build/createRevalidationBundle.d.ts +2 -0
  30. package/dist/build/createRevalidationBundle.js +35 -0
  31. package/dist/build/createServerBundle.d.ts +2 -2
  32. package/dist/build/createServerBundle.js +35 -39
  33. package/dist/build/createWarmerBundle.d.ts +2 -0
  34. package/dist/build/createWarmerBundle.js +44 -0
  35. package/dist/build/edge/createEdgeBundle.d.ts +6 -8
  36. package/dist/build/edge/createEdgeBundle.js +11 -15
  37. package/dist/build/helper.d.ts +22 -5
  38. package/dist/build/helper.js +42 -11
  39. package/dist/build/installDeps.d.ts +2 -0
  40. package/dist/build/installDeps.js +46 -0
  41. package/dist/build/utils.d.ts +5 -0
  42. package/dist/build/utils.js +22 -0
  43. package/dist/build/validateConfig.d.ts +1 -1
  44. package/dist/build.d.ts +0 -4
  45. package/dist/build.js +26 -486
  46. package/dist/core/createGenericHandler.js +5 -5
  47. package/dist/core/createMainHandler.d.ts +3 -3
  48. package/dist/core/createMainHandler.js +5 -5
  49. package/dist/core/requestHandler.d.ts +2 -2
  50. package/dist/core/requestHandler.js +2 -2
  51. package/dist/core/resolve.d.ts +13 -4
  52. package/dist/core/resolve.js +30 -5
  53. package/dist/core/routing/cacheInterceptor.d.ts +1 -1
  54. package/dist/core/routing/i18n/index.d.ts +1 -1
  55. package/dist/core/routing/i18n/index.js +3 -0
  56. package/dist/core/routing/matcher.d.ts +2 -1
  57. package/dist/core/routing/matcher.js +13 -6
  58. package/dist/core/routing/middleware.d.ts +6 -2
  59. package/dist/core/routing/middleware.js +13 -7
  60. package/dist/core/routing/util.d.ts +3 -2
  61. package/dist/core/routing/util.js +16 -7
  62. package/dist/core/routingHandler.d.ts +1 -1
  63. package/dist/core/routingHandler.js +1 -1
  64. package/dist/helpers/withCloudflare.d.ts +1 -1
  65. package/dist/helpers/withSST.d.ts +1 -1
  66. package/dist/http/openNextResponse.d.ts +10 -2
  67. package/dist/http/openNextResponse.js +27 -0
  68. package/dist/http/request.d.ts +1 -0
  69. package/dist/http/util.d.ts +1 -1
  70. package/dist/{converters → overrides/converters}/aws-apigw-v1.d.ts +1 -1
  71. package/dist/{converters → overrides/converters}/aws-apigw-v1.js +2 -2
  72. package/dist/{converters → overrides/converters}/aws-apigw-v2.d.ts +1 -1
  73. package/dist/{converters → overrides/converters}/aws-apigw-v2.js +4 -4
  74. package/dist/{converters → overrides/converters}/aws-cloudfront.d.ts +1 -1
  75. package/dist/{converters → overrides/converters}/aws-cloudfront.js +6 -7
  76. package/dist/{converters → overrides/converters}/dummy.d.ts +1 -1
  77. package/dist/overrides/converters/edge.d.ts +9 -0
  78. package/dist/{converters → overrides/converters}/edge.js +6 -3
  79. package/dist/{converters → overrides/converters}/node.d.ts +1 -1
  80. package/dist/{converters → overrides/converters}/node.js +1 -1
  81. package/dist/overrides/converters/sqs-revalidate.d.ts +4 -0
  82. package/dist/overrides/imageLoader/dummy.d.ts +3 -0
  83. package/dist/overrides/imageLoader/dummy.js +8 -0
  84. package/dist/overrides/imageLoader/host.d.ts +1 -1
  85. package/dist/overrides/imageLoader/s3.d.ts +1 -1
  86. package/dist/overrides/incrementalCache/dummy.d.ts +3 -0
  87. package/dist/overrides/incrementalCache/dummy.js +13 -0
  88. package/dist/{cache/incremental → overrides/incrementalCache}/s3-lite.d.ts +1 -1
  89. package/dist/{cache/incremental → overrides/incrementalCache}/s3.d.ts +1 -1
  90. package/dist/{cache/incremental → overrides/incrementalCache}/types.d.ts +1 -1
  91. package/dist/overrides/originResolver/dummy.d.ts +3 -0
  92. package/dist/overrides/originResolver/dummy.js +7 -0
  93. package/dist/overrides/originResolver/pattern-env.d.ts +3 -0
  94. package/dist/overrides/originResolver/pattern-env.js +39 -0
  95. package/dist/overrides/queue/dummy.d.ts +3 -0
  96. package/dist/overrides/queue/dummy.js +7 -0
  97. package/dist/{queue → overrides/queue}/sqs-lite.d.ts +1 -1
  98. package/dist/{queue → overrides/queue}/sqs-lite.js +3 -3
  99. package/dist/{queue → overrides/queue}/sqs.d.ts +1 -1
  100. package/dist/{queue → overrides/queue}/sqs.js +1 -1
  101. package/dist/overrides/tagCache/dummy.d.ts +3 -0
  102. package/dist/overrides/tagCache/dummy.js +17 -0
  103. package/dist/{cache/tag → overrides/tagCache}/dynamodb-lite.d.ts +1 -1
  104. package/dist/{cache/tag → overrides/tagCache}/dynamodb-lite.js +1 -1
  105. package/dist/{cache/tag → overrides/tagCache}/dynamodb.d.ts +1 -1
  106. package/dist/{cache/tag → overrides/tagCache}/dynamodb.js +1 -1
  107. package/dist/overrides/warmer/aws-lambda.d.ts +3 -0
  108. package/dist/overrides/warmer/aws-lambda.js +59 -0
  109. package/dist/overrides/warmer/dummy.d.ts +3 -0
  110. package/dist/overrides/warmer/dummy.js +7 -0
  111. package/dist/overrides/wrappers/aws-lambda-streaming.d.ts +7 -0
  112. package/dist/{wrappers → overrides/wrappers}/aws-lambda-streaming.js +1 -1
  113. package/dist/overrides/wrappers/aws-lambda.d.ts +7 -0
  114. package/dist/{wrappers → overrides/wrappers}/cloudflare.d.ts +2 -2
  115. package/dist/{wrappers → overrides/wrappers}/cloudflare.js +1 -1
  116. package/dist/overrides/wrappers/dummy.d.ts +7 -0
  117. package/dist/overrides/wrappers/dummy.js +6 -0
  118. package/dist/overrides/wrappers/node.d.ts +7 -0
  119. package/dist/{wrappers → overrides/wrappers}/node.js +1 -1
  120. package/dist/plugins/edge.d.ts +5 -4
  121. package/dist/plugins/edge.js +27 -29
  122. package/dist/plugins/replacement.d.ts +2 -2
  123. package/dist/plugins/replacement.js +4 -5
  124. package/dist/plugins/resolve.d.ts +4 -2
  125. package/dist/plugins/resolve.js +32 -20
  126. package/dist/types/aws-lambda.d.ts +3 -2
  127. package/dist/{cache/next-types.d.ts → types/cache.d.ts} +1 -0
  128. package/dist/types/next-types.d.ts +3 -1
  129. package/dist/types/open-next.d.ts +44 -13
  130. package/package.json +2 -2
  131. package/dist/adapters/plugins/without-routing/requestHandler.d.ts +0 -2
  132. package/dist/adapters/plugins/without-routing/requestHandler.js +0 -10
  133. package/dist/converters/edge.d.ts +0 -6
  134. package/dist/converters/sqs-revalidate.d.ts +0 -4
  135. package/dist/wrappers/aws-lambda-streaming.d.ts +0 -7
  136. package/dist/wrappers/aws-lambda.d.ts +0 -7
  137. package/dist/wrappers/node.d.ts +0 -7
  138. /package/dist/{converters → overrides/converters}/dummy.js +0 -0
  139. /package/dist/{converters → overrides/converters}/sqs-revalidate.js +0 -0
  140. /package/dist/{converters → overrides/converters}/utils.d.ts +0 -0
  141. /package/dist/{converters → overrides/converters}/utils.js +0 -0
  142. /package/dist/{cache/incremental → overrides/incrementalCache}/s3-lite.js +0 -0
  143. /package/dist/{cache/incremental → overrides/incrementalCache}/s3.js +0 -0
  144. /package/dist/{cache/incremental → overrides/incrementalCache}/types.js +0 -0
  145. /package/dist/{queue → overrides/queue}/types.d.ts +0 -0
  146. /package/dist/{cache/tag → overrides/queue}/types.js +0 -0
  147. /package/dist/{cache/tag → overrides/tagCache}/constants.d.ts +0 -0
  148. /package/dist/{cache/tag → overrides/tagCache}/constants.js +0 -0
  149. /package/dist/{cache/tag → overrides/tagCache}/types.d.ts +0 -0
  150. /package/dist/{queue → overrides/tagCache}/types.js +0 -0
  151. /package/dist/{wrappers → overrides/wrappers}/aws-lambda.js +0 -0
  152. /package/dist/{cache/next-types.js → types/cache.js} +0 -0
@@ -1,19 +1,15 @@
1
- import { existsSync } from "node:fs";
2
- import { createRequire as topLevelCreateRequire } from "node:module";
3
- import fs from "fs";
4
- import path from "path";
5
- import url from "url";
6
- import { compileCache } from "../build.js";
1
+ import fs from "node:fs";
2
+ import path from "node:path";
7
3
  import logger from "../logger.js";
8
4
  import { minifyAll } from "../minimize-js.js";
9
5
  import { openNextReplacementPlugin } from "../plugins/replacement.js";
10
6
  import { openNextResolvePlugin } from "../plugins/resolve.js";
11
7
  import { bundleNextServer } from "./bundleNextServer.js";
8
+ import { compileCache } from "./compileCache.js";
12
9
  import { copyTracedFiles } from "./copyTracedFiles.js";
13
10
  import { generateEdgeBundle } from "./edge/createEdgeBundle.js";
14
- import { compareSemver, copyEnvFile, copyOpenNextConfig, esbuildAsync, traverseFiles, } from "./helper.js";
15
- const require = topLevelCreateRequire(import.meta.url);
16
- const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
11
+ import * as buildHelper from "./helper.js";
12
+ import { installDependencies } from "./installDeps.js";
17
13
  export async function createServerBundle(options) {
18
14
  const { config } = options;
19
15
  const foundRoutes = new Set();
@@ -29,24 +25,24 @@ export async function createServerBundle(options) {
29
25
  const routes = fnOptions.routes;
30
26
  routes.forEach((route) => foundRoutes.add(route));
31
27
  if (fnOptions.runtime === "edge") {
32
- await generateEdgeBundle(name, config, options, fnOptions);
28
+ await generateEdgeBundle(name, options, fnOptions);
33
29
  }
34
30
  else {
35
- await generateBundle(name, config, options, fnOptions);
31
+ await generateBundle(name, options, fnOptions);
36
32
  }
37
33
  });
38
34
  //TODO: throw an error if not all edge runtime routes has been bundled in a separate function
39
35
  // We build every other function than default before so we know which route there is left
40
36
  await Promise.all(promises);
41
37
  const remainingRoutes = new Set();
42
- const { monorepoRoot, appBuildOutputPath } = options;
38
+ const { appBuildOutputPath, monorepoRoot } = options;
43
39
  const packagePath = path.relative(monorepoRoot, appBuildOutputPath);
44
40
  // Find remaining routes
45
41
  const serverPath = path.join(appBuildOutputPath, ".next", "standalone", packagePath, ".next", "server");
46
42
  // Find app dir routes
47
- if (existsSync(path.join(serverPath, "app"))) {
43
+ if (fs.existsSync(path.join(serverPath, "app"))) {
48
44
  const appPath = path.join(serverPath, "app");
49
- traverseFiles(appPath, (file) => {
45
+ buildHelper.traverseFiles(appPath, (file) => {
50
46
  if (file.endsWith("page.js") || file.endsWith("route.js")) {
51
47
  const route = `app/${file.replace(/\.js$/, "")}`;
52
48
  if (!foundRoutes.has(route)) {
@@ -57,9 +53,9 @@ export async function createServerBundle(options) {
57
53
  }, () => { });
58
54
  }
59
55
  // Find pages dir routes
60
- if (existsSync(path.join(serverPath, "pages"))) {
56
+ if (fs.existsSync(path.join(serverPath, "pages"))) {
61
57
  const pagePath = path.join(serverPath, "pages");
62
- traverseFiles(pagePath, (file) => {
58
+ buildHelper.traverseFiles(pagePath, (file) => {
63
59
  if (file.endsWith(".js")) {
64
60
  const route = `pages/${file.replace(/\.js$/, "")}`;
65
61
  if (!foundRoutes.has(route)) {
@@ -70,15 +66,15 @@ export async function createServerBundle(options) {
70
66
  }, () => { });
71
67
  }
72
68
  // Generate default function
73
- await generateBundle("default", config, options, {
69
+ await generateBundle("default", options, {
74
70
  ...defaultFn,
75
71
  // @ts-expect-error - Those string are RouteTemplate
76
72
  routes: Array.from(remainingRoutes),
77
73
  patterns: ["*"],
78
74
  });
79
75
  }
80
- async function generateBundle(name, config, options, fnOptions) {
81
- const { appPath, appBuildOutputPath, outputDir, monorepoRoot } = options;
76
+ async function generateBundle(name, options, fnOptions) {
77
+ const { appPath, appBuildOutputPath, config, outputDir, monorepoRoot } = options;
82
78
  logger.info(`Building server function: ${name}...`);
83
79
  // Create output folder
84
80
  const outputPath = path.join(outputDir, "server-functions", name);
@@ -91,7 +87,7 @@ async function generateBundle(name, config, options, fnOptions) {
91
87
  const packagePath = path.relative(monorepoRoot, appBuildOutputPath);
92
88
  fs.mkdirSync(path.join(outputPath, packagePath), { recursive: true });
93
89
  const ext = fnOptions.runtime === "deno" ? "mjs" : "cjs";
94
- fs.copyFileSync(path.join(outputDir, ".build", `cache.${ext}`), path.join(outputPath, packagePath, "cache.cjs"));
90
+ fs.copyFileSync(path.join(options.buildDir, `cache.${ext}`), path.join(outputPath, packagePath, "cache.cjs"));
95
91
  if (fnOptions.runtime === "deno") {
96
92
  addDenoJson(outputPath, packagePath);
97
93
  }
@@ -100,37 +96,34 @@ async function generateBundle(name, config, options, fnOptions) {
100
96
  if (isBundled) {
101
97
  await bundleNextServer(path.join(outputPath, packagePath), appPath);
102
98
  }
103
- // // Copy middleware
104
- if (!config.middleware?.external &&
105
- existsSync(path.join(outputDir, ".build", "middleware.mjs"))) {
106
- fs.copyFileSync(path.join(outputDir, ".build", "middleware.mjs"), path.join(outputPath, packagePath, "middleware.mjs"));
99
+ // Copy middleware
100
+ if (!config.middleware?.external) {
101
+ fs.copyFileSync(path.join(options.buildDir, "middleware.mjs"), path.join(outputPath, packagePath, "middleware.mjs"));
107
102
  }
108
103
  // Copy open-next.config.mjs
109
- copyOpenNextConfig(path.join(outputDir, ".build"), path.join(outputPath, packagePath));
110
- //Copy env files
111
- copyEnvFile(appBuildOutputPath, packagePath, outputPath);
104
+ buildHelper.copyOpenNextConfig(options.buildDir, path.join(outputPath, packagePath));
105
+ // Copy env files
106
+ buildHelper.copyEnvFile(appBuildOutputPath, packagePath, outputPath);
112
107
  // Copy all necessary traced files
113
108
  await copyTracedFiles(appBuildOutputPath, packagePath, outputPath, fnOptions.routes ?? ["app/page.tsx"], isBundled);
114
109
  // Build Lambda code
115
110
  // note: bundle in OpenNext package b/c the adapter relies on the
116
111
  // "serverless-http" package which is not a dependency in user's
117
112
  // Next.js app.
118
- const disableNextPrebundledReact = compareSemver(options.nextVersion, "13.5.1") >= 0 ||
119
- compareSemver(options.nextVersion, "13.4.1") <= 0;
113
+ const disableNextPrebundledReact = buildHelper.compareSemver(options.nextVersion, "13.5.1") >= 0 ||
114
+ buildHelper.compareSemver(options.nextVersion, "13.4.1") <= 0;
120
115
  const overrides = fnOptions.override ?? {};
121
- const isBefore13413 = compareSemver(options.nextVersion, "13.4.13") <= 0;
122
- const isAfter141 = compareSemver(options.nextVersion, "14.0.4") >= 0;
116
+ const isBefore13413 = buildHelper.compareSemver(options.nextVersion, "13.4.13") <= 0;
117
+ const isAfter141 = buildHelper.compareSemver(options.nextVersion, "14.0.4") >= 0;
123
118
  const disableRouting = isBefore13413 || config.middleware?.external;
124
119
  const plugins = [
125
120
  openNextReplacementPlugin({
126
121
  name: `requestHandlerOverride ${name}`,
127
122
  target: /core(\/|\\)requestHandler\.js/g,
128
- deletes: disableNextPrebundledReact ? ["applyNextjsPrebundledReact"] : [],
129
- replacements: disableRouting
130
- ? [
131
- require.resolve("../adapters/plugins/without-routing/requestHandler.js"),
132
- ]
133
- : [],
123
+ deletes: [
124
+ ...(disableNextPrebundledReact ? ["applyNextjsPrebundledReact"] : []),
125
+ ...(disableRouting ? ["withRouting"] : []),
126
+ ],
134
127
  }),
135
128
  openNextReplacementPlugin({
136
129
  name: `utilOverride ${name}`,
@@ -154,8 +147,10 @@ async function generateBundle(name, config, options, fnOptions) {
154
147
  .join(",")}] for Next version: ${options.nextVersion}`);
155
148
  }
156
149
  const outfileExt = fnOptions.runtime === "deno" ? "ts" : "mjs";
157
- await esbuildAsync({
158
- entryPoints: [path.join(__dirname, "../adapters", "server-adapter.js")],
150
+ await buildHelper.esbuildAsync({
151
+ entryPoints: [
152
+ path.join(options.openNextDistDir, "adapters", "server-adapter.js"),
153
+ ],
159
154
  external: ["next", "./middleware.mjs", "./next-server.runtime.prod.js"],
160
155
  outfile: path.join(outputPath, packagePath, `index.${outfileExt}`),
161
156
  banner: {
@@ -180,6 +175,7 @@ async function generateBundle(name, config, options, fnOptions) {
180
175
  if (isMonorepo) {
181
176
  addMonorepoEntrypoint(outputPath, packagePath);
182
177
  }
178
+ installDependencies(outputPath, fnOptions.install);
183
179
  if (fnOptions.minify) {
184
180
  await minifyServerBundle(outputPath);
185
181
  }
@@ -0,0 +1,2 @@
1
+ import * as buildHelper from "./helper.js";
2
+ export declare function createWarmerBundle(options: buildHelper.BuildOptions): Promise<void>;
@@ -0,0 +1,44 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import logger from "../logger.js";
4
+ import { openNextResolvePlugin } from "../plugins/resolve.js";
5
+ import * as buildHelper from "./helper.js";
6
+ import { installDependencies } from "./installDeps.js";
7
+ export async function createWarmerBundle(options) {
8
+ logger.info(`Bundling warmer function...`);
9
+ const { config, outputDir } = options;
10
+ // Create output folder
11
+ const outputPath = path.join(outputDir, "warmer-function");
12
+ fs.mkdirSync(outputPath, { recursive: true });
13
+ // Copy open-next.config.mjs into the bundle
14
+ buildHelper.copyOpenNextConfig(options.buildDir, outputPath);
15
+ // Build Lambda code
16
+ // note: bundle in OpenNext package b/c the adatper relys on the
17
+ // "serverless-http" package which is not a dependency in user's
18
+ // Next.js app.
19
+ await buildHelper.esbuildAsync({
20
+ entryPoints: [
21
+ path.join(options.openNextDistDir, "adapters", "warmer-function.js"),
22
+ ],
23
+ external: ["next"],
24
+ outfile: path.join(outputPath, "index.mjs"),
25
+ plugins: [
26
+ openNextResolvePlugin({
27
+ overrides: {
28
+ converter: config.warmer?.override?.converter ?? "dummy",
29
+ wrapper: config.warmer?.override?.wrapper,
30
+ },
31
+ fnName: "warmer",
32
+ }),
33
+ ],
34
+ banner: {
35
+ js: [
36
+ "import { createRequire as topLevelCreateRequire } from 'module';",
37
+ "const require = topLevelCreateRequire(import.meta.url);",
38
+ "import bannerUrl from 'url';",
39
+ "const __dirname = bannerUrl.fileURLToPath(new URL('.', import.meta.url));",
40
+ ].join(""),
41
+ },
42
+ }, options);
43
+ installDependencies(outputPath, config.warmer?.install);
44
+ }
@@ -1,9 +1,8 @@
1
- import { MiddlewareInfo } from "../../types/next-types";
2
- import { IncludedConverter, OpenNextConfig, OverrideOptions, SplittedFunctionOptions } from "../../types/open-next";
3
- import { BuildOptions } from "../helper.js";
1
+ import type { MiddlewareInfo } from "../../types/next-types";
2
+ import type { IncludedConverter, OverrideOptions, SplittedFunctionOptions } from "../../types/open-next";
3
+ import type { BuildOptions } from "../helper.js";
4
4
  interface BuildEdgeBundleOptions {
5
- appBuildOutputPath: string;
6
- middlewareInfo: MiddlewareInfo;
5
+ middlewareInfo?: MiddlewareInfo;
7
6
  entrypoint: string;
8
7
  outfile: string;
9
8
  options: BuildOptions;
@@ -14,7 +13,6 @@ interface BuildEdgeBundleOptions {
14
13
  additionalExternals?: string[];
15
14
  onlyBuildOnce?: boolean;
16
15
  }
17
- export declare function buildEdgeBundle({ appBuildOutputPath, middlewareInfo, entrypoint, outfile, options, defaultConverter, overrides, additionalInject, includeCache, additionalExternals, onlyBuildOnce, }: BuildEdgeBundleOptions): Promise<void>;
18
- export declare function copyMiddlewareAssetsAndWasm({}: {}): void;
19
- export declare function generateEdgeBundle(name: string, config: OpenNextConfig, options: BuildOptions, fnOptions: SplittedFunctionOptions): Promise<void>;
16
+ export declare function buildEdgeBundle({ middlewareInfo, entrypoint, outfile, options, defaultConverter, overrides, additionalInject, includeCache, additionalExternals, onlyBuildOnce, }: BuildEdgeBundleOptions): Promise<void>;
17
+ export declare function generateEdgeBundle(name: string, options: BuildOptions, fnOptions: SplittedFunctionOptions): Promise<void>;
20
18
  export {};
@@ -1,5 +1,4 @@
1
1
  import { mkdirSync } from "node:fs";
2
- import url from "node:url";
3
2
  import { build } from "esbuild";
4
3
  import fs from "fs";
5
4
  import path from "path";
@@ -8,8 +7,7 @@ import { openNextEdgePlugins } from "../../plugins/edge.js";
8
7
  import { openNextReplacementPlugin } from "../../plugins/replacement.js";
9
8
  import { openNextResolvePlugin } from "../../plugins/resolve.js";
10
9
  import { copyOpenNextConfig, esbuildAsync } from "../helper.js";
11
- const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
12
- export async function buildEdgeBundle({ appBuildOutputPath, middlewareInfo, entrypoint, outfile, options, defaultConverter, overrides, additionalInject, includeCache, additionalExternals, onlyBuildOnce, }) {
10
+ export async function buildEdgeBundle({ middlewareInfo, entrypoint, outfile, options, defaultConverter, overrides, additionalInject, includeCache, additionalExternals, onlyBuildOnce, }) {
13
11
  const isInCloudfare = typeof overrides?.wrapper === "string"
14
12
  ? overrides.wrapper === "cloudflare"
15
13
  : (await overrides?.wrapper?.())?.edgeRuntime;
@@ -52,8 +50,8 @@ export async function buildEdgeBundle({ appBuildOutputPath, middlewareInfo, entr
52
50
  }),
53
51
  openNextEdgePlugins({
54
52
  middlewareInfo,
55
- nextDir: path.join(appBuildOutputPath, ".next"),
56
- edgeFunctionHandlerPath: path.join(__dirname, "../../core", "edgeFunctionHandler.js"),
53
+ nextDir: path.join(options.appBuildOutputPath, ".next"),
54
+ edgeFunctionHandlerPath: path.join(options.openNextDistDir, "core", "edgeFunctionHandler.js"),
57
55
  isInCloudfare,
58
56
  }),
59
57
  ],
@@ -108,15 +106,14 @@ globalThis.AsyncLocalStorage = AsyncLocalStorage;
108
106
  });
109
107
  }
110
108
  }
111
- export function copyMiddlewareAssetsAndWasm({}) { }
112
- export async function generateEdgeBundle(name, config, options, fnOptions) {
109
+ export async function generateEdgeBundle(name, options, fnOptions) {
113
110
  const { appBuildOutputPath, outputDir } = options;
114
111
  logger.info(`Generating edge bundle for: ${name}`);
115
112
  // Create output folder
116
113
  const outputPath = path.join(outputDir, "server-functions", name);
117
114
  fs.mkdirSync(outputPath, { recursive: true });
118
115
  // Copy open-next.config.mjs
119
- copyOpenNextConfig(path.join(outputDir, ".build"), outputPath, true);
116
+ copyOpenNextConfig(options.buildDir, outputPath, true);
120
117
  // Load middleware manifest
121
118
  const middlewareManifest = JSON.parse(fs.readFileSync(path.join(appBuildOutputPath, ".next/server/middleware-manifest.json"), "utf8"));
122
119
  // Find functions
@@ -124,26 +121,25 @@ export async function generateEdgeBundle(name, config, options, fnOptions) {
124
121
  if (functions.length > 1) {
125
122
  throw new Error("Only one function is supported for now");
126
123
  }
127
- const fn = functions[0];
124
+ const middlewareInfo = functions[0];
128
125
  //Copy wasm files
129
- const wasmFiles = fn.wasm;
126
+ const wasmFiles = middlewareInfo.wasm;
130
127
  mkdirSync(path.join(outputPath, "wasm"), { recursive: true });
131
128
  for (const wasmFile of wasmFiles) {
132
129
  fs.copyFileSync(path.join(appBuildOutputPath, ".next", wasmFile.filePath), path.join(outputPath, `wasm/${wasmFile.name}.wasm`));
133
130
  }
134
131
  // Copy assets
135
- const assets = fn.assets;
132
+ const assets = middlewareInfo.assets;
136
133
  mkdirSync(path.join(outputPath, "assets"), { recursive: true });
137
134
  for (const asset of assets) {
138
135
  fs.copyFileSync(path.join(appBuildOutputPath, ".next", asset.filePath), path.join(outputPath, `assets/${asset.name}`));
139
136
  }
140
137
  await buildEdgeBundle({
141
- appBuildOutputPath,
142
- middlewareInfo: fn,
143
- entrypoint: path.join(__dirname, "../../adapters", "edge-adapter.js"),
138
+ middlewareInfo,
139
+ entrypoint: path.join(options.openNextDistDir, "adapters", "edge-adapter.js"),
144
140
  outfile: path.join(outputPath, "index.mjs"),
145
141
  options,
146
142
  overrides: fnOptions.override,
147
- additionalExternals: config.edgeExternals,
143
+ additionalExternals: options.config.edgeExternals,
148
144
  });
149
145
  }
@@ -1,19 +1,21 @@
1
- import { BuildOptions as ESBuildOptions } from "esbuild";
2
- import { OpenNextConfig } from "../types/open-next.js";
1
+ import type { BuildOptions as ESBuildOptions } from "esbuild";
2
+ import type { OpenNextConfig } from "../types/open-next.js";
3
3
  export type BuildOptions = ReturnType<typeof normalizeOptions>;
4
- export declare function normalizeOptions(config: OpenNextConfig): {
4
+ export declare function normalizeOptions(config: OpenNextConfig, distDir: string, tempBuildDir: string): {
5
5
  appBuildOutputPath: string;
6
6
  appPackageJsonPath: string;
7
7
  appPath: string;
8
8
  appPublicPath: string;
9
+ buildDir: string;
9
10
  config: OpenNextConfig;
10
11
  debug: boolean;
11
12
  monorepoRoot: string;
12
13
  nextVersion: string;
13
14
  openNextVersion: string;
15
+ openNextDistDir: string;
14
16
  outputDir: string;
15
17
  packager: "npm" | "yarn" | "pnpm" | "bun";
16
- tempDir: string;
18
+ tempBuildDir: string;
17
19
  };
18
20
  export declare function esbuildSync(esbuildOptions: ESBuildOptions, options: BuildOptions): void;
19
21
  export declare function esbuildAsync(esbuildOptions: ESBuildOptions, options: BuildOptions): Promise<void>;
@@ -31,5 +33,20 @@ export declare function getBuildId(dotNextPath: string): string;
31
33
  export declare function getOpenNextVersion(): string;
32
34
  export declare function getNextVersion(appPath: string): string;
33
35
  export declare function compareSemver(v1: string, v2: string): number;
34
- export declare function copyOpenNextConfig(tempDir: string, outputPath: string, isEdge?: boolean): void;
36
+ export declare function copyOpenNextConfig(inputDir: string, outputDir: string, isEdge?: boolean): void;
35
37
  export declare function copyEnvFile(appPath: string, packagePath: string, outputPath: string): void;
38
+ /**
39
+ * Check we are in a Nextjs app by looking for the Nextjs config file.
40
+ */
41
+ export declare function checkRunningInsideNextjsApp(options: BuildOptions): void;
42
+ export declare function printNextjsVersion(options: BuildOptions): void;
43
+ export declare function printOpenNextVersion(options: BuildOptions): void;
44
+ /**
45
+ * Populates the build directory with the compiled configuration files.
46
+ *
47
+ * We need to get the build relative to the cwd to find the compiled config.
48
+ * This is needed for the case where the app is a single-version monorepo
49
+ * and the package.json is in the root of the monorepo where the build is in
50
+ * the app directory, but the compiled config is in the root of the monorepo.
51
+ */
52
+ export declare function initOutputDir(options: BuildOptions): void;
@@ -1,12 +1,12 @@
1
1
  import fs from "node:fs";
2
- import { createRequire as topLevelCreateRequire } from "node:module";
2
+ import { createRequire } from "node:module";
3
3
  import path from "node:path";
4
4
  import url from "node:url";
5
- import { build as buildAsync, buildSync, } from "esbuild";
5
+ import { build as buildAsync, buildSync } from "esbuild";
6
6
  import logger from "../logger.js";
7
- const require = topLevelCreateRequire(import.meta.url);
7
+ const require = createRequire(import.meta.url);
8
8
  const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
9
- export function normalizeOptions(config) {
9
+ export function normalizeOptions(config, distDir, tempBuildDir) {
10
10
  const appPath = path.join(process.cwd(), config.appPath || ".");
11
11
  const buildOutputPath = path.join(process.cwd(), config.buildOutputPath || ".");
12
12
  const outputDir = path.join(buildOutputPath, ".open-next");
@@ -26,14 +26,16 @@ export function normalizeOptions(config) {
26
26
  appPackageJsonPath,
27
27
  appPath,
28
28
  appPublicPath: path.join(appPath, "public"),
29
+ buildDir: path.join(outputDir, ".build"),
29
30
  config,
30
31
  debug: Boolean(process.env.OPEN_NEXT_DEBUG) ?? false,
31
32
  monorepoRoot,
32
33
  nextVersion: getNextVersion(appPath),
33
34
  openNextVersion: getOpenNextVersion(),
35
+ openNextDistDir: distDir,
34
36
  outputDir,
35
37
  packager,
36
- tempDir: path.join(outputDir, ".build"),
38
+ tempBuildDir,
37
39
  };
38
40
  }
39
41
  function findMonorepoRoot(appPath) {
@@ -56,6 +58,7 @@ function findMonorepoRoot(appPath) {
56
58
  // note: a lock file (package-lock.json, yarn.lock, or pnpm-lock.yaml) is
57
59
  // not found in the app's directory or any of its parent directories.
58
60
  // We are going to assume that the app is not part of a monorepo.
61
+ logger.warn("No lockfile found");
59
62
  return { root: appPath, packager: "npm" };
60
63
  }
61
64
  function findNextPackageJsonPath(appPath, root) {
@@ -158,10 +161,7 @@ export function getHtmlPages(dotNextPath) {
158
161
  return Object.entries(JSON.parse(manifest))
159
162
  .filter(([_, value]) => value.endsWith(".html"))
160
163
  .map(([_, value]) => value.replace(/^pages\//, ""))
161
- .reduce((acc, page) => {
162
- acc.add(page);
163
- return acc;
164
- }, new Set());
164
+ .reduce((acc, page) => acc.add(page), new Set());
165
165
  }
166
166
  export function getBuildId(dotNextPath) {
167
167
  return fs
@@ -200,9 +200,9 @@ export function compareSemver(v1, v2) {
200
200
  return minor1 - minor2;
201
201
  return patch1 - patch2;
202
202
  }
203
- export function copyOpenNextConfig(tempDir, outputPath, isEdge = false) {
203
+ export function copyOpenNextConfig(inputDir, outputDir, isEdge = false) {
204
204
  // Copy open-next.config.mjs
205
- fs.copyFileSync(path.join(tempDir, isEdge ? "open-next.config.edge.mjs" : "open-next.config.mjs"), path.join(outputPath, "open-next.config.mjs"));
205
+ fs.copyFileSync(path.join(inputDir, isEdge ? "open-next.config.edge.mjs" : "open-next.config.mjs"), path.join(outputDir, "open-next.config.mjs"));
206
206
  }
207
207
  export function copyEnvFile(appPath, packagePath, outputPath) {
208
208
  const baseAppPath = path.join(appPath, ".next/standalone", packagePath);
@@ -216,3 +216,34 @@ export function copyEnvFile(appPath, packagePath, outputPath) {
216
216
  fs.copyFileSync(envProdPath, path.join(baseOutputPath, ".env.production"));
217
217
  }
218
218
  }
219
+ /**
220
+ * Check we are in a Nextjs app by looking for the Nextjs config file.
221
+ */
222
+ export function checkRunningInsideNextjsApp(options) {
223
+ const { appPath } = options;
224
+ const extension = ["js", "cjs", "mjs", "ts"].find((ext) => fs.existsSync(path.join(appPath, `next.config.${ext}`)));
225
+ if (!extension) {
226
+ logger.error("Error: next.config.js not found. Please make sure you are running this command inside a Next.js app.");
227
+ process.exit(1);
228
+ }
229
+ }
230
+ export function printNextjsVersion(options) {
231
+ logger.info(`Next.js version : ${options.nextVersion}`);
232
+ }
233
+ export function printOpenNextVersion(options) {
234
+ logger.info(`OpenNext v${options.openNextVersion}`);
235
+ }
236
+ /**
237
+ * Populates the build directory with the compiled configuration files.
238
+ *
239
+ * We need to get the build relative to the cwd to find the compiled config.
240
+ * This is needed for the case where the app is a single-version monorepo
241
+ * and the package.json is in the root of the monorepo where the build is in
242
+ * the app directory, but the compiled config is in the root of the monorepo.
243
+ */
244
+ export function initOutputDir(options) {
245
+ fs.rmSync(options.outputDir, { recursive: true, force: true });
246
+ const { buildDir } = options;
247
+ fs.mkdirSync(buildDir, { recursive: true });
248
+ fs.cpSync(options.tempBuildDir, buildDir, { recursive: true });
249
+ }
@@ -0,0 +1,2 @@
1
+ import type { InstallOptions } from "../types/open-next";
2
+ export declare function installDependencies(outputDir: string, installOptions?: InstallOptions): void;
@@ -0,0 +1,46 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { execSync } from "child_process";
5
+ import logger from "../logger.js";
6
+ export function installDependencies(outputDir, installOptions) {
7
+ try {
8
+ if (!installOptions) {
9
+ return;
10
+ }
11
+ const name = outputDir.split("/").pop();
12
+ // First we create a tempDir
13
+ const tempInstallDir = fs.mkdtempSync(path.join(os.tmpdir(), `open-next-install-${name}`));
14
+ logger.info(`Installing dependencies for ${name}...`);
15
+ // We then need to run install in the tempDir
16
+ // We don't install in the output dir directly because it could contain a package.json, and npm would then try to reinstall not complete deps from tracing the files
17
+ const archOption = installOptions.arch
18
+ ? `--arch=${installOptions.arch}`
19
+ : "";
20
+ const targetOption = installOptions.nodeVersion
21
+ ? `--target=${installOptions.nodeVersion}`
22
+ : "";
23
+ const libcOption = installOptions.libc
24
+ ? `--libc=${installOptions.libc}`
25
+ : "";
26
+ const additionalArgs = installOptions.additionalArgs ?? "";
27
+ const installCommand = `npm install --platform=linux ${archOption} ${targetOption} ${libcOption} ${additionalArgs} ${installOptions.packages.join(" ")}`;
28
+ execSync(installCommand, {
29
+ stdio: "pipe",
30
+ cwd: tempInstallDir,
31
+ env: {
32
+ ...process.env,
33
+ SHARP_IGNORE_GLOBAL_LIBVIPS: "1",
34
+ },
35
+ });
36
+ // Copy the node_modules to the outputDir
37
+ fs.cpSync(path.join(tempInstallDir, "node_modules"), path.join(outputDir, "node_modules"), { recursive: true, force: true, dereference: true });
38
+ // Cleanup tempDir
39
+ fs.rmSync(tempInstallDir, { recursive: true, force: true });
40
+ logger.info(`Dependencies installed for ${name}`);
41
+ }
42
+ catch (e) {
43
+ logger.error(e.stdout.toString());
44
+ logger.error("Could not install dependencies");
45
+ }
46
+ }
@@ -0,0 +1,5 @@
1
+ export declare function printHeader(header: string): void;
2
+ /**
3
+ * Displays a warning on windows platform.
4
+ */
5
+ export declare function showWarningOnWindows(): void;
@@ -0,0 +1,22 @@
1
+ import os from "node:os";
2
+ import logger from "../logger.js";
3
+ export function printHeader(header) {
4
+ header = `OpenNext — ${header}`;
5
+ logger.info([
6
+ "",
7
+ "┌" + "─".repeat(header.length + 2) + "┐",
8
+ `│ ${header} │`,
9
+ "└" + "─".repeat(header.length + 2) + "┘",
10
+ "",
11
+ ].join("\n"));
12
+ }
13
+ /**
14
+ * Displays a warning on windows platform.
15
+ */
16
+ export function showWarningOnWindows() {
17
+ if (os.platform() !== "win32")
18
+ return;
19
+ logger.warn("OpenNext is not fully compatible with Windows.");
20
+ logger.warn("For optimal performance, it is recommended to use Windows Subsystem for Linux (WSL).");
21
+ logger.warn("While OpenNext may function on Windows, it could encounter unpredictable failures during runtime.");
22
+ }
@@ -1,2 +1,2 @@
1
- import { OpenNextConfig } from "../types/open-next";
1
+ import type { OpenNextConfig } from "../types/open-next";
2
2
  export declare function validateConfig(config: OpenNextConfig): void;
package/dist/build.d.ts CHANGED
@@ -1,8 +1,4 @@
1
- import { BuildOptions } from "./build/helper.js";
2
1
  export type PublicFiles = {
3
2
  files: string[];
4
3
  };
5
4
  export declare function build(openNextConfigPath?: string, nodeExternals?: string): Promise<void>;
6
- /***************************/
7
- /***************************/
8
- export declare function compileCache(options: BuildOptions, format?: "cjs" | "esm"): string;