@opennextjs/cloudflare 0.0.0-b997312 → 0.0.0-cf5113b

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.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Deploy Next.js apps to Cloudflare!
4
4
 
5
- OpenNext for Cloudflare is Cloudflare specific adapter that enables deployment of Next.js applications to Cloudflare.
5
+ [OpenNext for Cloudflare](https://opennext.js.org/cloudflare) is Cloudflare specific adapter that enables deployment of Next.js applications to Cloudflare.
6
6
 
7
7
  ## Getting started
8
8
 
@@ -13,7 +13,13 @@ You can use [`create-next-app`](https://nextjs.org/docs/pages/api-reference/cli/
13
13
  - add the following `devDependencies` to the `package.json`:
14
14
 
15
15
  ```bash
16
+ npm add -D wrangler@latest @opennextjs/cloudflare
17
+ # or
16
18
  pnpm add -D wrangler@latest @opennextjs/cloudflare
19
+ # or
20
+ yarn add -D wrangler@latest @opennextjs/cloudflare
21
+ # or
22
+ bun add -D wrangler@latest @opennextjs/cloudflare
17
23
  ```
18
24
 
19
25
  - add a `wrangler.toml` at the root of your project
@@ -27,9 +33,34 @@ You can use [`create-next-app`](https://nextjs.org/docs/pages/api-reference/cli/
27
33
  compatibility_flags = ["nodejs_compat"]
28
34
 
29
35
  # Use the new Workers + Assets to host the static frontend files
30
- experimental_assets = { directory = ".worker-next/assets", binding = "ASSETS" }
36
+ assets = { directory = ".worker-next/assets", binding = "ASSETS" }
31
37
  ```
32
38
 
39
+ You can enable Incremental Static Regeneration ([ISR](https://nextjs.org/docs/app/building-your-application/data-fetching/incremental-static-regeneration)) by adding a KV binding named `NEXT_CACHE_WORKERS_KV` to your `wrangler.toml`:
40
+
41
+ - Create the binding
42
+
43
+ ```bash
44
+ npx wrangler kv namespace create NEXT_CACHE_WORKERS_KV
45
+ # or
46
+ pnpm wrangler kv namespace create NEXT_CACHE_WORKERS_KV
47
+ # or
48
+ yarn wrangler kv namespace create NEXT_CACHE_WORKERS_KV
49
+ # or
50
+ bun wrangler kv namespace create NEXT_CACHE_WORKERS_KV
51
+ ```
52
+
53
+ - Paste the snippet to your `wrangler.toml`:
54
+
55
+ ```bash
56
+ [[kv_namespaces]]
57
+ binding = "NEXT_CACHE_WORKERS_KV"
58
+ id = "..."
59
+ ```
60
+
61
+ > [!WARNING]
62
+ > The current support for ISR is limited.
63
+
33
64
  ## Local development
34
65
 
35
66
  - you can use the regular `next` CLI to start the Next.js dev server:
@@ -41,13 +72,25 @@ Run the following commands to preview the production build of your application l
41
72
  - build the app and adapt it for Cloudflare
42
73
 
43
74
  ```bash
44
- pnpx cloudflare
75
+ npx cloudflare
76
+ # or
77
+ pnpm cloudflare
78
+ # or
79
+ yarn cloudflare
80
+ # or
81
+ bun cloudflare
45
82
  ```
46
83
 
47
84
  - Preview the app in Wrangler
48
85
 
49
86
  ```bash
87
+ npx wrangler dev
88
+ # or
50
89
  pnpm wrangler dev
90
+ # or
91
+ yarn wrangler dev
92
+ # or
93
+ bun wrangler dev
51
94
  ```
52
95
 
53
96
  ## Deploy your app
@@ -57,9 +100,11 @@ Deploy your application to production with the following:
57
100
  - build the app and adapt it for Cloudflare
58
101
 
59
102
  ```bash
60
- pnpx cloudflare
61
- ```
62
-
63
- ```bash
64
- pnpm wrangler deploy
103
+ npx cloudflare && npx wrangler deploy
104
+ # or
105
+ pnpm cloudflare && pnpm wrangler deploy
106
+ # or
107
+ yarn cloudflare && yarn wrangler deploy
108
+ # or
109
+ bun cloudflare && bun wrangler deploy
65
110
  ```
@@ -18,7 +18,7 @@ var CfWorkersKvCacheHandler = class _CfWorkersKvCacheHandler {
18
18
  return null;
19
19
  }
20
20
  }
21
- async set(key, entry, ctx) {
21
+ async set(key, entry, _ctx) {
22
22
  if (_CfWorkersKvCacheHandler.maybeKVNamespace === void 0) {
23
23
  return;
24
24
  }
@@ -213,68 +213,171 @@ var require_brace_expansion = __commonJS({
213
213
  }
214
214
  });
215
215
 
216
- // src/cli/index.ts
217
- import { resolve as resolve2 } from "node:path";
218
-
219
- // src/cli/args.ts
220
- import { mkdirSync, statSync } from "node:fs";
221
- import { parseArgs } from "node:util";
222
- import { resolve } from "node:path";
223
- function getArgs() {
224
- const {
225
- values: { skipBuild: skipBuild2, output }
226
- } = parseArgs({
227
- options: {
228
- skipBuild: {
229
- type: "boolean",
230
- short: "s",
231
- default: false
232
- },
233
- output: {
234
- type: "string",
235
- short: "o"
236
- }
237
- },
238
- allowPositionals: false
239
- });
240
- const outputDir2 = output ? resolve(output) : void 0;
241
- if (outputDir2) {
242
- assertDirArg(outputDir2, "output", true);
216
+ // src/cli/config.ts
217
+ import path, { relative } from "node:path";
218
+ import { readdirSync, statSync } from "node:fs";
219
+ var PACKAGE_NAME = "@opennextjs/cloudflare";
220
+ var UserConfig = {
221
+ cache: {
222
+ bindingName: "NEXT_CACHE_WORKERS_KV"
243
223
  }
224
+ };
225
+ function getConfig(appDir, outputDir2) {
226
+ const dotNext = path.join(outputDir2, ".next");
227
+ const appPath = getNextjsApplicationPath(dotNext).replace(/\/$/, "");
228
+ const standaloneRoot = path.join(dotNext, "standalone");
229
+ const standaloneApp = path.join(standaloneRoot, appPath);
230
+ const standaloneAppDotNext = path.join(standaloneApp, ".next");
231
+ const standaloneAppServer = path.join(standaloneAppDotNext, "server");
232
+ const nodeModules = path.join(standaloneApp, "node_modules");
233
+ const internalPackage = path.join(nodeModules, ...PACKAGE_NAME.split("/"));
244
234
  return {
245
- outputDir: outputDir2,
246
- skipBuild: skipBuild2 || ["1", "true", "yes"].includes(String(process.env.SKIP_NEXT_APP_BUILD))
235
+ paths: {
236
+ nextApp: appDir,
237
+ builderOutput: outputDir2,
238
+ dotNext,
239
+ standaloneRoot,
240
+ standaloneApp,
241
+ standaloneAppDotNext,
242
+ standaloneAppServer,
243
+ internalPackage
244
+ },
245
+ cache: {
246
+ kvBindingName: UserConfig.cache.bindingName
247
+ },
248
+ internalPackageName: PACKAGE_NAME
247
249
  };
248
250
  }
249
- function assertDirArg(path13, argName, make) {
250
- let dirStats;
251
+ function containsDotNextDir(folder) {
251
252
  try {
252
- dirStats = statSync(path13);
253
+ return statSync(path.join(folder, ".next")).isDirectory();
253
254
  } catch {
254
- if (!make) {
255
- throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a valid path`);
255
+ return false;
256
+ }
257
+ }
258
+ function getNextjsApplicationPath(dotNextDir) {
259
+ const serverPath = findServerParentPath(dotNextDir);
260
+ if (!serverPath) {
261
+ throw new Error(`Unexpected Error: no \`.next/server\` folder could be found in \`${serverPath}\``);
262
+ }
263
+ return relative(path.join(dotNextDir, "standalone"), serverPath);
264
+ }
265
+ function findServerParentPath(parentPath) {
266
+ try {
267
+ if (statSync(path.join(parentPath, ".next", "server")).isDirectory()) {
268
+ return parentPath;
256
269
  }
257
- mkdirSync(path13);
258
- return;
270
+ } catch {
259
271
  }
260
- if (!dirStats.isDirectory()) {
261
- throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a directory`);
272
+ const folders = readdirSync(parentPath);
273
+ for (const folder of folders) {
274
+ const subFolder = path.join(parentPath, folder);
275
+ if (statSync(path.join(parentPath, folder)).isDirectory()) {
276
+ const dirServerPath = findServerParentPath(subFolder);
277
+ if (dirServerPath) {
278
+ return dirServerPath;
279
+ }
280
+ }
262
281
  }
263
282
  }
264
283
 
265
- // src/cli/index.ts
266
- import { existsSync as existsSync4 } from "node:fs";
284
+ // ../../node_modules/.pnpm/package-manager-detector@0.2.0/node_modules/package-manager-detector/dist/constants.mjs
285
+ var AGENTS = [
286
+ "npm",
287
+ "yarn",
288
+ "yarn@berry",
289
+ "pnpm",
290
+ "pnpm@6",
291
+ "bun"
292
+ ];
293
+ var LOCKS = {
294
+ "bun.lockb": "bun",
295
+ "pnpm-lock.yaml": "pnpm",
296
+ "yarn.lock": "yarn",
297
+ "package-lock.json": "npm",
298
+ "npm-shrinkwrap.json": "npm"
299
+ };
267
300
 
268
- // src/cli/build/index.ts
269
- import { rm } from "node:fs/promises";
301
+ // ../../node_modules/.pnpm/package-manager-detector@0.2.0/node_modules/package-manager-detector/dist/detect.mjs
302
+ import fs from "node:fs";
303
+ import fsPromises from "node:fs/promises";
304
+ import path2 from "node:path";
305
+ import process2 from "node:process";
306
+ async function detect({ cwd, onUnknown } = {}) {
307
+ for (const directory of lookup(cwd)) {
308
+ for (const lock of Object.keys(LOCKS)) {
309
+ if (await fileExists(path2.join(directory, lock))) {
310
+ const name = LOCKS[lock];
311
+ const result2 = await parsePackageJson(path2.join(directory, "package.json"), onUnknown);
312
+ if (result2)
313
+ return result2;
314
+ else
315
+ return { name, agent: name };
316
+ }
317
+ }
318
+ const result = await parsePackageJson(path2.join(directory, "package.json"), onUnknown);
319
+ if (result)
320
+ return result;
321
+ }
322
+ return null;
323
+ }
324
+ function* lookup(cwd = process2.cwd()) {
325
+ let directory = path2.resolve(cwd);
326
+ const { root } = path2.parse(directory);
327
+ while (directory && directory !== root) {
328
+ yield directory;
329
+ directory = path2.dirname(directory);
330
+ }
331
+ }
332
+ async function parsePackageJson(filepath, onUnknown) {
333
+ if (!filepath || !await fileExists(filepath))
334
+ return null;
335
+ try {
336
+ const pkg = JSON.parse(fs.readFileSync(filepath, "utf8"));
337
+ let agent;
338
+ if (typeof pkg.packageManager === "string") {
339
+ const [name, ver] = pkg.packageManager.replace(/^\^/, "").split("@");
340
+ let version = ver;
341
+ if (name === "yarn" && Number.parseInt(ver) > 1) {
342
+ agent = "yarn@berry";
343
+ version = "berry";
344
+ return { name, agent, version };
345
+ } else if (name === "pnpm" && Number.parseInt(ver) < 7) {
346
+ agent = "pnpm@6";
347
+ return { name, agent, version };
348
+ } else if (AGENTS.includes(name)) {
349
+ agent = name;
350
+ return { name, agent, version };
351
+ } else {
352
+ return onUnknown?.(pkg.packageManager) ?? null;
353
+ }
354
+ }
355
+ } catch {
356
+ }
357
+ return null;
358
+ }
359
+ async function fileExists(filePath) {
360
+ try {
361
+ const stats = await fsPromises.stat(filePath);
362
+ if (stats.isFile()) {
363
+ return true;
364
+ }
365
+ } catch {
366
+ }
367
+ return false;
368
+ }
270
369
 
271
370
  // src/cli/build/build-next-app.ts
272
371
  import { execSync } from "node:child_process";
273
- function buildNextjsApp(nextAppDir2) {
274
- runNextBuildCommand("pnpm", nextAppDir2);
372
+ async function buildNextjsApp(nextAppDir2) {
373
+ const pm = await detect();
374
+ if (!pm) {
375
+ throw new Error("Fatal Error: package manager detection failed, aborting");
376
+ }
377
+ runNextBuildCommand(pm.name, nextAppDir2);
275
378
  }
276
379
  function runNextBuildCommand(packager, nextAppDir2) {
277
- const command = ["bun", "npm"].includes(packager) ? `${packager} next build` : `${packager} next build`;
380
+ const command = `${packager === "npm" ? "npx" : packager} next build`;
278
381
  execSync(command, {
279
382
  stdio: "inherit",
280
383
  cwd: nextAppDir2,
@@ -289,29 +392,21 @@ function runNextBuildCommand(packager, nextAppDir2) {
289
392
 
290
393
  // src/cli/build/build-worker.ts
291
394
  import { build } from "esbuild";
292
- import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
293
395
  import { cp, readFile, writeFile } from "node:fs/promises";
294
- import path10 from "node:path";
295
- import { fileURLToPath as fileURLToPath3 } from "node:url";
296
-
297
- // src/cli/build/patches/investigated/patch-require.ts
298
- function patchRequire(code) {
299
- console.log("# patchRequire");
300
- return code.replace(/__require\d?\(/g, "require(").replace(/__require\d?\./g, "require.");
301
- }
396
+ import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
302
397
 
303
398
  // src/cli/build/patches/investigated/copy-package-cli-files.ts
304
399
  import { cpSync } from "node:fs";
305
- import path from "node:path";
400
+ import path3 from "node:path";
306
401
  function copyPackageCliFiles(packageDistDir2, config) {
307
402
  console.log("# copyPackageTemplateFiles");
308
- const sourceDir = path.join(packageDistDir2, "cli");
309
- const destinationDir = path.join(config.paths.internalPackage, "cli");
403
+ const sourceDir = path3.join(packageDistDir2, "cli");
404
+ const destinationDir = path3.join(config.paths.internalPackage, "cli");
310
405
  cpSync(sourceDir, destinationDir, { recursive: true });
311
406
  }
312
407
 
313
- // src/cli/build/patches/to-investigate/patch-read-file.ts
314
- import { readFileSync } from "node:fs";
408
+ // src/cli/build/build-worker.ts
409
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
315
410
 
316
411
  // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/index.js
317
412
  var import_brace_expansion = __toESM(require_brace_expansion(), 1);
@@ -984,11 +1079,11 @@ var qmarksTestNoExtDot = ([$0]) => {
984
1079
  return (f) => f.length === len && f !== "." && f !== "..";
985
1080
  };
986
1081
  var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
987
- var path2 = {
1082
+ var path4 = {
988
1083
  win32: { sep: "\\" },
989
1084
  posix: { sep: "/" }
990
1085
  };
991
- var sep = defaultPlatform === "win32" ? path2.win32.sep : path2.posix.sep;
1086
+ var sep = defaultPlatform === "win32" ? path4.win32.sep : path4.posix.sep;
992
1087
  minimatch.sep = sep;
993
1088
  var GLOBSTAR = Symbol("globstar **");
994
1089
  minimatch.GLOBSTAR = GLOBSTAR;
@@ -3018,7 +3113,7 @@ var LRUCache = class _LRUCache {
3018
3113
  // ../../node_modules/.pnpm/path-scurry@2.0.0/node_modules/path-scurry/dist/esm/index.js
3019
3114
  import { posix, win32 } from "node:path";
3020
3115
  import { fileURLToPath } from "node:url";
3021
- import { lstatSync, readdir as readdirCB, readdirSync, readlinkSync, realpathSync as rps } from "fs";
3116
+ import { lstatSync, readdir as readdirCB, readdirSync as readdirSync2, readlinkSync, realpathSync as rps } from "fs";
3022
3117
  import * as actualFS from "node:fs";
3023
3118
  import { lstat, readdir, readlink, realpath } from "node:fs/promises";
3024
3119
 
@@ -3905,7 +4000,7 @@ var realpathSync = rps.native;
3905
4000
  var defaultFS = {
3906
4001
  lstatSync,
3907
4002
  readdir: readdirCB,
3908
- readdirSync,
4003
+ readdirSync: readdirSync2,
3909
4004
  readlinkSync,
3910
4005
  realpathSync,
3911
4006
  promises: {
@@ -4165,12 +4260,12 @@ var PathBase = class {
4165
4260
  /**
4166
4261
  * Get the Path object referenced by the string path, resolved from this Path
4167
4262
  */
4168
- resolve(path13) {
4169
- if (!path13) {
4263
+ resolve(path14) {
4264
+ if (!path14) {
4170
4265
  return this;
4171
4266
  }
4172
- const rootPath = this.getRootString(path13);
4173
- const dir = path13.substring(rootPath.length);
4267
+ const rootPath = this.getRootString(path14);
4268
+ const dir = path14.substring(rootPath.length);
4174
4269
  const dirParts = dir.split(this.splitSep);
4175
4270
  const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
4176
4271
  return result;
@@ -4922,8 +5017,8 @@ var PathWin32 = class _PathWin32 extends PathBase {
4922
5017
  /**
4923
5018
  * @internal
4924
5019
  */
4925
- getRootString(path13) {
4926
- return win32.parse(path13).root;
5020
+ getRootString(path14) {
5021
+ return win32.parse(path14).root;
4927
5022
  }
4928
5023
  /**
4929
5024
  * @internal
@@ -4969,8 +5064,8 @@ var PathPosix = class _PathPosix extends PathBase {
4969
5064
  /**
4970
5065
  * @internal
4971
5066
  */
4972
- getRootString(path13) {
4973
- return path13.startsWith("/") ? "/" : "";
5067
+ getRootString(path14) {
5068
+ return path14.startsWith("/") ? "/" : "";
4974
5069
  }
4975
5070
  /**
4976
5071
  * @internal
@@ -5019,8 +5114,8 @@ var PathScurryBase = class {
5019
5114
  *
5020
5115
  * @internal
5021
5116
  */
5022
- constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs2 = defaultFS } = {}) {
5023
- this.#fs = fsFromOption(fs2);
5117
+ constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs3 = defaultFS } = {}) {
5118
+ this.#fs = fsFromOption(fs3);
5024
5119
  if (cwd instanceof URL || cwd.startsWith("file://")) {
5025
5120
  cwd = fileURLToPath(cwd);
5026
5121
  }
@@ -5059,11 +5154,11 @@ var PathScurryBase = class {
5059
5154
  /**
5060
5155
  * Get the depth of a provided path, string, or the cwd
5061
5156
  */
5062
- depth(path13 = this.cwd) {
5063
- if (typeof path13 === "string") {
5064
- path13 = this.cwd.resolve(path13);
5157
+ depth(path14 = this.cwd) {
5158
+ if (typeof path14 === "string") {
5159
+ path14 = this.cwd.resolve(path14);
5065
5160
  }
5066
- return path13.depth();
5161
+ return path14.depth();
5067
5162
  }
5068
5163
  /**
5069
5164
  * Return the cache of child entries. Exposed so subclasses can create
@@ -5442,7 +5537,7 @@ var PathScurryBase = class {
5442
5537
  const dirs = /* @__PURE__ */ new Set();
5443
5538
  const queue = [entry];
5444
5539
  let processing = 0;
5445
- const process2 = () => {
5540
+ const process3 = () => {
5446
5541
  let paused = false;
5447
5542
  while (!paused) {
5448
5543
  const dir = queue.shift();
@@ -5483,9 +5578,9 @@ var PathScurryBase = class {
5483
5578
  }
5484
5579
  }
5485
5580
  if (paused && !results.flowing) {
5486
- results.once("drain", process2);
5581
+ results.once("drain", process3);
5487
5582
  } else if (!sync2) {
5488
- process2();
5583
+ process3();
5489
5584
  }
5490
5585
  };
5491
5586
  let sync2 = true;
@@ -5493,7 +5588,7 @@ var PathScurryBase = class {
5493
5588
  sync2 = false;
5494
5589
  }
5495
5590
  };
5496
- process2();
5591
+ process3();
5497
5592
  return results;
5498
5593
  }
5499
5594
  streamSync(entry = this.cwd, opts = {}) {
@@ -5511,7 +5606,7 @@ var PathScurryBase = class {
5511
5606
  }
5512
5607
  const queue = [entry];
5513
5608
  let processing = 0;
5514
- const process2 = () => {
5609
+ const process3 = () => {
5515
5610
  let paused = false;
5516
5611
  while (!paused) {
5517
5612
  const dir = queue.shift();
@@ -5545,14 +5640,14 @@ var PathScurryBase = class {
5545
5640
  }
5546
5641
  }
5547
5642
  if (paused && !results.flowing)
5548
- results.once("drain", process2);
5643
+ results.once("drain", process3);
5549
5644
  };
5550
- process2();
5645
+ process3();
5551
5646
  return results;
5552
5647
  }
5553
- chdir(path13 = this.cwd) {
5648
+ chdir(path14 = this.cwd) {
5554
5649
  const oldCwd = this.cwd;
5555
- this.cwd = typeof path13 === "string" ? this.cwd.resolve(path13) : path13;
5650
+ this.cwd = typeof path14 === "string" ? this.cwd.resolve(path14) : path14;
5556
5651
  this.cwd[setAsCwd](oldCwd);
5557
5652
  }
5558
5653
  };
@@ -5578,8 +5673,8 @@ var PathScurryWin32 = class extends PathScurryBase {
5578
5673
  /**
5579
5674
  * @internal
5580
5675
  */
5581
- newRoot(fs2) {
5582
- return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs2 });
5676
+ newRoot(fs3) {
5677
+ return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs3 });
5583
5678
  }
5584
5679
  /**
5585
5680
  * Return true if the provided path string is an absolute path
@@ -5607,8 +5702,8 @@ var PathScurryPosix = class extends PathScurryBase {
5607
5702
  /**
5608
5703
  * @internal
5609
5704
  */
5610
- newRoot(fs2) {
5611
- return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs2 });
5705
+ newRoot(fs3) {
5706
+ return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs3 });
5612
5707
  }
5613
5708
  /**
5614
5709
  * Return true if the provided path string is an absolute path
@@ -5908,8 +6003,8 @@ var MatchRecord = class {
5908
6003
  }
5909
6004
  // match, absolute, ifdir
5910
6005
  entries() {
5911
- return [...this.store.entries()].map(([path13, n]) => [
5912
- path13,
6006
+ return [...this.store.entries()].map(([path14, n]) => [
6007
+ path14,
5913
6008
  !!(n & 2),
5914
6009
  !!(n & 1)
5915
6010
  ]);
@@ -6114,9 +6209,9 @@ var GlobUtil = class {
6114
6209
  signal;
6115
6210
  maxDepth;
6116
6211
  includeChildMatches;
6117
- constructor(patterns, path13, opts) {
6212
+ constructor(patterns, path14, opts) {
6118
6213
  this.patterns = patterns;
6119
- this.path = path13;
6214
+ this.path = path14;
6120
6215
  this.opts = opts;
6121
6216
  this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/";
6122
6217
  this.includeChildMatches = opts.includeChildMatches !== false;
@@ -6135,11 +6230,11 @@ var GlobUtil = class {
6135
6230
  });
6136
6231
  }
6137
6232
  }
6138
- #ignored(path13) {
6139
- return this.seen.has(path13) || !!this.#ignore?.ignored?.(path13);
6233
+ #ignored(path14) {
6234
+ return this.seen.has(path14) || !!this.#ignore?.ignored?.(path14);
6140
6235
  }
6141
- #childrenIgnored(path13) {
6142
- return !!this.#ignore?.childrenIgnored?.(path13);
6236
+ #childrenIgnored(path14) {
6237
+ return !!this.#ignore?.childrenIgnored?.(path14);
6143
6238
  }
6144
6239
  // backpressure mechanism
6145
6240
  pause() {
@@ -6354,8 +6449,8 @@ var GlobUtil = class {
6354
6449
  };
6355
6450
  var GlobWalker = class extends GlobUtil {
6356
6451
  matches = /* @__PURE__ */ new Set();
6357
- constructor(patterns, path13, opts) {
6358
- super(patterns, path13, opts);
6452
+ constructor(patterns, path14, opts) {
6453
+ super(patterns, path14, opts);
6359
6454
  }
6360
6455
  matchEmit(e) {
6361
6456
  this.matches.add(e);
@@ -6392,8 +6487,8 @@ var GlobWalker = class extends GlobUtil {
6392
6487
  };
6393
6488
  var GlobStream = class extends GlobUtil {
6394
6489
  results;
6395
- constructor(patterns, path13, opts) {
6396
- super(patterns, path13, opts);
6490
+ constructor(patterns, path14, opts) {
6491
+ super(patterns, path14, opts);
6397
6492
  this.results = new Minipass({
6398
6493
  signal: this.signal,
6399
6494
  objectMode: true
@@ -6686,67 +6781,44 @@ var glob = Object.assign(glob_, {
6686
6781
  });
6687
6782
  glob.glob = glob;
6688
6783
 
6689
- // src/cli/build/patches/to-investigate/patch-read-file.ts
6690
- import path3 from "node:path";
6691
- function patchReadFile(code, config) {
6692
- console.log("# patchReadFile");
6693
- code = code.replace(
6694
- "getBuildId() {",
6695
- `getBuildId() {
6696
- return ${JSON.stringify(readFileSync(path3.join(config.paths.standaloneAppDotNext, "BUILD_ID"), "utf-8"))};
6697
- `
6698
- );
6699
- const manifestJsons = globSync(path3.join(config.paths.standaloneAppDotNext, "**", "*-manifest.json")).map(
6700
- (file) => file.replace(config.paths.standaloneApp + "/", "")
6701
- );
6702
- code = code.replace(
6703
- /function loadManifest\((.+?), .+?\) {/,
6784
+ // src/cli/build/patches/to-investigate/inline-eval-manifest.ts
6785
+ import path5 from "node:path";
6786
+ function inlineEvalManifest(code, config) {
6787
+ console.log("# inlineEvalManifest");
6788
+ const manifestJss = globSync(
6789
+ path5.join(config.paths.standaloneAppDotNext, "**", "*_client-reference-manifest.js")
6790
+ ).map((file) => file.replace(`${config.paths.standaloneApp}/`, ""));
6791
+ return code.replace(
6792
+ /function evalManifest\((.+?), .+?\) {/,
6704
6793
  `$&
6705
- ${manifestJsons.map(
6706
- (manifestJson) => `
6707
- if ($1.endsWith("${manifestJson}")) {
6708
- return ${readFileSync(path3.join(config.paths.standaloneApp, manifestJson), "utf-8")};
6709
- }
6710
- `
6794
+ ${manifestJss.map(
6795
+ (manifestJs) => `
6796
+ if ($1.endsWith("${manifestJs}")) {
6797
+ require("${path5.join(config.paths.standaloneApp, manifestJs)}");
6798
+ return {
6799
+ __RSC_MANIFEST: {
6800
+ "${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}": globalThis.__RSC_MANIFEST["${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}"],
6801
+ },
6802
+ };
6803
+ }
6804
+ `
6711
6805
  ).join("\n")}
6712
- throw new Error("Unknown loadManifest: " + $1);
6713
- `
6714
- );
6715
- return code;
6716
- }
6717
-
6718
- // src/cli/build/patches/to-investigate/patch-find-dir.ts
6719
- import path4 from "node:path";
6720
- import { existsSync } from "node:fs";
6721
- function patchFindDir(code, config) {
6722
- console.log("# patchFindDir");
6723
- return code.replace(
6724
- "function findDir(dir, name) {",
6725
- `function findDir(dir, name) {
6726
- if (dir.endsWith(".next/server")) {
6727
- if (name === "app") {
6728
- return ${existsSync(`${path4.join(config.paths.standaloneAppServer, "app")}`)};
6729
- }
6730
- if (name === "pages") {
6731
- return ${existsSync(`${path4.join(config.paths.standaloneAppServer, "pages")}`)};
6732
- }
6733
- }
6734
- throw new Error("Unknown findDir call: " + dir + " " + name);
6806
+ throw new Error("Unknown evalManifest: " + $1);
6735
6807
  `
6736
6808
  );
6737
6809
  }
6738
6810
 
6739
6811
  // src/cli/build/patches/to-investigate/inline-next-require.ts
6740
- import { readFileSync as readFileSync2, existsSync as existsSync2 } from "node:fs";
6741
- import path5 from "node:path";
6812
+ import { existsSync, readFileSync } from "node:fs";
6813
+ import path6 from "node:path";
6742
6814
  function inlineNextRequire(code, config) {
6743
6815
  console.log("# inlineNextRequire");
6744
- const pagesManifestFile = path5.join(config.paths.standaloneAppServer, "pages-manifest.json");
6745
- const appPathsManifestFile = path5.join(config.paths.standaloneAppServer, "app-paths-manifest.json");
6746
- const pagesManifestFiles = existsSync2(pagesManifestFile) ? Object.values(JSON.parse(readFileSync2(pagesManifestFile, "utf-8"))).map(
6816
+ const pagesManifestFile = path6.join(config.paths.standaloneAppServer, "pages-manifest.json");
6817
+ const appPathsManifestFile = path6.join(config.paths.standaloneAppServer, "app-paths-manifest.json");
6818
+ const pagesManifestFiles = existsSync(pagesManifestFile) ? Object.values(JSON.parse(readFileSync(pagesManifestFile, "utf-8"))).map(
6747
6819
  (file) => ".next/server/" + file
6748
6820
  ) : [];
6749
- const appPathsManifestFiles = existsSync2(appPathsManifestFile) ? Object.values(JSON.parse(readFileSync2(appPathsManifestFile, "utf-8"))).map(
6821
+ const appPathsManifestFiles = existsSync(appPathsManifestFile) ? Object.values(JSON.parse(readFileSync(appPathsManifestFile, "utf-8"))).map(
6750
6822
  (file) => ".next/server/" + file
6751
6823
  ) : [];
6752
6824
  const allManifestFiles = pagesManifestFiles.concat(appPathsManifestFiles);
@@ -6758,14 +6830,14 @@ function inlineNextRequire(code, config) {
6758
6830
  ${htmlPages.map(
6759
6831
  (htmlPage) => `
6760
6832
  if (pagePath.endsWith("${htmlPage}")) {
6761
- return ${JSON.stringify(readFileSync2(path5.join(config.paths.standaloneApp, htmlPage), "utf-8"))};
6833
+ return ${JSON.stringify(readFileSync(path6.join(config.paths.standaloneApp, htmlPage), "utf-8"))};
6762
6834
  }
6763
6835
  `
6764
6836
  ).join("\n")}
6765
6837
  ${pageModules.map(
6766
6838
  (module) => `
6767
6839
  if (pagePath.endsWith("${module}")) {
6768
- return require("${path5.join(config.paths.standaloneApp, module)}");
6840
+ return require("${path6.join(config.paths.standaloneApp, module)}");
6769
6841
  }
6770
6842
  `
6771
6843
  ).join("\n")}
@@ -6774,66 +6846,110 @@ function inlineNextRequire(code, config) {
6774
6846
  );
6775
6847
  }
6776
6848
 
6777
- // src/cli/build/patches/to-investigate/inline-eval-manifest.ts
6778
- import path6 from "node:path";
6779
- function inlineEvalManifest(code, config) {
6780
- console.log("# inlineEvalManifest");
6781
- const manifestJss = globSync(
6782
- path6.join(config.paths.standaloneAppDotNext, "**", "*_client-reference-manifest.js")
6783
- ).map((file) => file.replace(`${config.paths.standaloneApp}/`, ""));
6849
+ // src/cli/build/patches/investigated/patch-cache.ts
6850
+ import path7 from "node:path";
6851
+ function patchCache(code, config) {
6852
+ console.log("# patchCached");
6853
+ const cacheHandler = path7.join(config.paths.internalPackage, "cli", "cache-handler.mjs");
6854
+ const patchedCode = code.replace(
6855
+ "const { cacheHandler } = this.nextConfig;",
6856
+ `const cacheHandler = null;
6857
+ CacheHandler = (await import('${cacheHandler}')).default;
6858
+ CacheHandler.maybeKVNamespace = process.env["${config.cache.kvBindingName}"];
6859
+ `
6860
+ );
6861
+ if (patchedCode === code) {
6862
+ throw new Error("Cache patch not applied");
6863
+ }
6864
+ return patchedCode;
6865
+ }
6866
+
6867
+ // src/cli/build/patches/to-investigate/patch-find-dir.ts
6868
+ import { existsSync as existsSync2 } from "node:fs";
6869
+ import path8 from "node:path";
6870
+ function patchFindDir(code, config) {
6871
+ console.log("# patchFindDir");
6784
6872
  return code.replace(
6785
- /function evalManifest\((.+?), .+?\) {/,
6873
+ "function findDir(dir, name) {",
6874
+ `function findDir(dir, name) {
6875
+ if (dir.endsWith(".next/server")) {
6876
+ if (name === "app") {
6877
+ return ${existsSync2(`${path8.join(config.paths.standaloneAppServer, "app")}`)};
6878
+ }
6879
+ if (name === "pages") {
6880
+ return ${existsSync2(`${path8.join(config.paths.standaloneAppServer, "pages")}`)};
6881
+ }
6882
+ }
6883
+ throw new Error("Unknown findDir call: " + dir + " " + name);
6884
+ `
6885
+ );
6886
+ }
6887
+
6888
+ // src/cli/build/patches/to-investigate/patch-read-file.ts
6889
+ import path9 from "node:path";
6890
+ import { readFileSync as readFileSync2 } from "node:fs";
6891
+ function patchReadFile(code, config) {
6892
+ console.log("# patchReadFile");
6893
+ code = code.replace(
6894
+ "getBuildId() {",
6895
+ `getBuildId() {
6896
+ return ${JSON.stringify(readFileSync2(path9.join(config.paths.standaloneAppDotNext, "BUILD_ID"), "utf-8"))};
6897
+ `
6898
+ );
6899
+ const manifestJsons = globSync(path9.join(config.paths.standaloneAppDotNext, "**", "*-manifest.json")).map(
6900
+ (file) => file.replace(config.paths.standaloneApp + "/", "")
6901
+ );
6902
+ code = code.replace(
6903
+ /function loadManifest\((.+?), .+?\) {/,
6786
6904
  `$&
6787
- ${manifestJss.map(
6788
- (manifestJs) => `
6789
- if ($1.endsWith("${manifestJs}")) {
6790
- require("${path6.join(config.paths.standaloneApp, manifestJs)}");
6791
- return {
6792
- __RSC_MANIFEST: {
6793
- "${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}": globalThis.__RSC_MANIFEST["${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}"],
6794
- },
6795
- };
6796
- }
6797
- `
6905
+ ${manifestJsons.map(
6906
+ (manifestJson) => `
6907
+ if ($1.endsWith("${manifestJson}")) {
6908
+ return ${readFileSync2(path9.join(config.paths.standaloneApp, manifestJson), "utf-8")};
6909
+ }
6910
+ `
6798
6911
  ).join("\n")}
6799
- throw new Error("Unknown evalManifest: " + $1);
6800
- `
6912
+ throw new Error("Unknown loadManifest: " + $1);
6913
+ `
6801
6914
  );
6915
+ return code;
6916
+ }
6917
+
6918
+ // src/cli/build/patches/investigated/patch-require.ts
6919
+ function patchRequire(code) {
6920
+ console.log("# patchRequire");
6921
+ return code.replace(/__require\d?\(/g, "require(").replace(/__require\d?\./g, "require.");
6802
6922
  }
6803
6923
 
6804
6924
  // src/cli/build/patches/to-investigate/wrangler-deps.ts
6805
- import path7 from "node:path";
6806
- import fs, { writeFileSync } from "node:fs";
6925
+ import fs2, { writeFileSync } from "node:fs";
6926
+ import path10 from "node:path";
6807
6927
  function patchWranglerDeps(config) {
6808
6928
  console.log("# patchWranglerDeps");
6809
- const pagesRuntimeFile = path7.join(
6810
- config.paths.standaloneApp,
6811
- "node_modules",
6812
- "next",
6813
- "dist",
6814
- "compiled",
6815
- "next-server",
6816
- "pages.runtime.prod.js"
6817
- );
6818
- const patchedPagesRuntime = fs.readFileSync(pagesRuntimeFile, "utf-8").replace(`e.exports=require("critters")`, `e.exports={}`);
6819
- fs.writeFileSync(pagesRuntimeFile, patchedPagesRuntime);
6820
- const tracerFile = path7.join(
6821
- config.paths.standaloneApp,
6822
- "node_modules",
6823
- "next",
6824
- "dist",
6825
- "server",
6826
- "lib",
6827
- "trace",
6828
- "tracer.js"
6829
- );
6830
- const pacthedTracer = fs.readFileSync(tracerFile, "utf-8").replaceAll(/\w+\s*=\s*require\([^/]*opentelemetry.*\)/g, `throw new Error("@opentelemetry/api")`);
6929
+ const distPath = getDistPath(config);
6930
+ const pagesRuntimeFile = path10.join(distPath, "compiled", "next-server", "pages.runtime.prod.js");
6931
+ const patchedPagesRuntime = fs2.readFileSync(pagesRuntimeFile, "utf-8").replace(`e.exports=require("critters")`, `e.exports={}`);
6932
+ fs2.writeFileSync(pagesRuntimeFile, patchedPagesRuntime);
6933
+ const tracerFile = path10.join(distPath, "server", "lib", "trace", "tracer.js");
6934
+ const pacthedTracer = fs2.readFileSync(tracerFile, "utf-8").replaceAll(/\w+\s*=\s*require\([^/]*opentelemetry.*\)/g, `throw new Error("@opentelemetry/api")`);
6831
6935
  writeFileSync(tracerFile, pacthedTracer);
6832
6936
  }
6937
+ function getDistPath(config) {
6938
+ for (const root of [config.paths.standaloneApp, config.paths.standaloneRoot]) {
6939
+ try {
6940
+ const distPath = path10.join(root, "node_modules", "next", "dist");
6941
+ if (fs2.statSync(distPath).isDirectory()) return distPath;
6942
+ } catch {
6943
+ }
6944
+ }
6945
+ throw new Error("Unexpected error: unable to detect the node_modules/next/dist directory");
6946
+ }
6947
+
6948
+ // src/cli/build/build-worker.ts
6949
+ import path12 from "node:path";
6833
6950
 
6834
6951
  // src/cli/build/patches/investigated/update-webpack-chunks-file/index.ts
6835
- import { readdirSync as readdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
6836
- import path8 from "node:path";
6952
+ import { readFileSync as readFileSync3, readdirSync as readdirSync3, writeFileSync as writeFileSync2 } from "node:fs";
6837
6953
 
6838
6954
  // src/cli/build/patches/investigated/update-webpack-chunks-file/get-chunk-installation-identifiers.ts
6839
6955
  import * as ts from "ts-morph";
@@ -6946,11 +7062,12 @@ async function getUpdatedWebpackChunksFileContent(fileContent, chunks) {
6946
7062
  }
6947
7063
 
6948
7064
  // src/cli/build/patches/investigated/update-webpack-chunks-file/index.ts
7065
+ import path11 from "node:path";
6949
7066
  async function updateWebpackChunksFile(config) {
6950
7067
  console.log("# updateWebpackChunksFile");
6951
- const webpackRuntimeFile = path8.join(config.paths.standaloneAppServer, "webpack-runtime.js");
7068
+ const webpackRuntimeFile = path11.join(config.paths.standaloneAppServer, "webpack-runtime.js");
6952
7069
  const fileContent = readFileSync3(webpackRuntimeFile, "utf-8");
6953
- const chunks = readdirSync2(path8.join(config.paths.standaloneAppServer, "chunks")).filter((chunk) => /^\d+\.js$/.test(chunk)).map((chunk) => {
7070
+ const chunks = readdirSync3(path11.join(config.paths.standaloneAppServer, "chunks")).filter((chunk) => /^\d+\.js$/.test(chunk)).map((chunk) => {
6954
7071
  console.log(` - chunk ${chunk}`);
6955
7072
  return chunk.replace(/\.js$/, "");
6956
7073
  });
@@ -6958,47 +7075,29 @@ async function updateWebpackChunksFile(config) {
6958
7075
  writeFileSync2(webpackRuntimeFile, updatedFileContent);
6959
7076
  }
6960
7077
 
6961
- // src/cli/build/patches/investigated/patch-cache.ts
6962
- import path9 from "node:path";
6963
- function patchCache(code, config) {
6964
- console.log("# patchCached");
6965
- const cacheHandler = path9.join(config.paths.internalPackage, "cli", "cache-handler.mjs");
6966
- const patchedCode = code.replace(
6967
- "const { cacheHandler } = this.nextConfig;",
6968
- `const cacheHandler = null;
6969
- CacheHandler = (await import('${cacheHandler}')).default;
6970
- CacheHandler.maybeKVNamespace = process.env["${config.cache.kvBindingName}"];
6971
- `
6972
- );
6973
- if (patchedCode === code) {
6974
- throw new Error("Cache patch not applied");
6975
- }
6976
- return patchedCode;
6977
- }
6978
-
6979
7078
  // src/cli/build/build-worker.ts
6980
- var packageDistDir = path10.join(path10.dirname(fileURLToPath3(import.meta.url)), "..");
7079
+ var packageDistDir = path12.join(path12.dirname(fileURLToPath3(import.meta.url)), "..");
6981
7080
  async function buildWorker(config) {
6982
7081
  console.log(`\x1B[35m\u2699\uFE0F Copying files...
6983
7082
  \x1B[0m`);
6984
7083
  await cp(
6985
- path10.join(config.paths.dotNext, "static"),
6986
- path10.join(config.paths.builderOutput, "assets", "_next", "static"),
7084
+ path12.join(config.paths.dotNext, "static"),
7085
+ path12.join(config.paths.builderOutput, "assets", "_next", "static"),
6987
7086
  {
6988
7087
  recursive: true
6989
7088
  }
6990
7089
  );
6991
- const publicDir = path10.join(config.paths.nextApp, "public");
7090
+ const publicDir = path12.join(config.paths.nextApp, "public");
6992
7091
  if (existsSync3(publicDir)) {
6993
- await cp(publicDir, path10.join(config.paths.builderOutput, "assets"), {
7092
+ await cp(publicDir, path12.join(config.paths.builderOutput, "assets"), {
6994
7093
  recursive: true
6995
7094
  });
6996
7095
  }
6997
7096
  copyPackageCliFiles(packageDistDir, config);
6998
- const templateDir = path10.join(config.paths.internalPackage, "cli", "templates");
6999
- const workerEntrypoint = path10.join(templateDir, "worker.ts");
7000
- const workerOutputFile = path10.join(config.paths.builderOutput, "index.mjs");
7001
- const nextConfigStr = readFileSync4(path10.join(config.paths.standaloneApp, "/server.js"), "utf8")?.match(
7097
+ const templateDir = path12.join(config.paths.internalPackage, "cli", "templates");
7098
+ const workerEntrypoint = path12.join(templateDir, "worker.ts");
7099
+ const workerOutputFile = path12.join(config.paths.builderOutput, "index.mjs");
7100
+ const nextConfigStr = readFileSync4(path12.join(config.paths.standaloneApp, "/server.js"), "utf8")?.match(
7002
7101
  /const nextConfig = ({.+?})\n/
7003
7102
  )?.[1] ?? {};
7004
7103
  console.log(`\x1B[35m\u2699\uFE0F Bundling the worker file...
@@ -7017,15 +7116,15 @@ async function buildWorker(config) {
7017
7116
  // Note: we apply an empty shim to next/dist/compiled/ws because it generates two `eval`s:
7018
7117
  // eval("require")("bufferutil");
7019
7118
  // eval("require")("utf-8-validate");
7020
- "next/dist/compiled/ws": path10.join(templateDir, "shims", "empty.ts"),
7119
+ "next/dist/compiled/ws": path12.join(templateDir, "shims", "empty.ts"),
7021
7120
  // Note: we apply an empty shim to next/dist/compiled/edge-runtime since (amongst others) it generated the following `eval`:
7022
7121
  // eval(getModuleCode)(module, module.exports, throwingRequire, params.context, ...Object.values(params.scopedContext));
7023
7122
  // which comes from https://github.com/vercel/edge-runtime/blob/6e96b55f/packages/primitives/src/primitives/load.js#L57-L63
7024
7123
  // QUESTION: Why did I encountered this but mhart didn't?
7025
- "next/dist/compiled/edge-runtime": path10.join(templateDir, "shims", "empty.ts"),
7124
+ "next/dist/compiled/edge-runtime": path12.join(templateDir, "shims", "empty.ts"),
7026
7125
  // `@next/env` is a library Next.js uses for loading dotenv files, for obvious reasons we need to stub it here
7027
7126
  // source: https://github.com/vercel/next.js/tree/0ac10d79720/packages/next-env
7028
- "@next/env": path10.join(templateDir, "shims", "env.ts")
7127
+ "@next/env": path12.join(templateDir, "shims", "env.ts")
7029
7128
  },
7030
7129
  define: {
7031
7130
  // config file used by Next.js, see: https://github.com/vercel/next.js/blob/68a7128/packages/next/src/build/utils.ts#L2137-L2139
@@ -7104,103 +7203,88 @@ function createFixRequiresESBuildPlugin(templateDir) {
7104
7203
  return {
7105
7204
  name: "replaceRelative",
7106
7205
  setup(build3) {
7107
- build3.onResolve({ filter: /^\.\/require-hook$/ }, (args) => ({
7108
- path: path10.join(templateDir, "shims", "empty.ts")
7206
+ build3.onResolve({ filter: /^\.\/require-hook$/ }, () => ({
7207
+ path: path12.join(templateDir, "shims", "empty.ts")
7109
7208
  }));
7110
- build3.onResolve({ filter: /\.\/lib\/node-fs-methods$/ }, (args) => ({
7111
- path: path10.join(templateDir, "shims", "empty.ts")
7209
+ build3.onResolve({ filter: /\.\/lib\/node-fs-methods$/ }, () => ({
7210
+ path: path12.join(templateDir, "shims", "empty.ts")
7112
7211
  }));
7113
7212
  }
7114
7213
  };
7115
7214
  }
7116
7215
 
7117
- // src/cli/config.ts
7118
- import { readdirSync as readdirSync3, statSync as statSync2 } from "node:fs";
7119
- import path11, { relative } from "node:path";
7120
- var PACKAGE_NAME = "@opennextjs/cloudflare";
7121
- var UserConfig = {
7122
- cache: {
7123
- bindingName: "NEXT_CACHE_WORKERS_KV"
7124
- }
7125
- };
7126
- function getConfig(appDir, outputDir2) {
7127
- const dotNext = path11.join(outputDir2, ".next");
7128
- const appPath = getNextjsApplicationPath(dotNext).replace(/\/$/, "");
7129
- const standaloneApp = path11.join(dotNext, "standalone", appPath);
7130
- const standaloneAppDotNext = path11.join(standaloneApp, ".next");
7131
- const standaloneAppServer = path11.join(standaloneAppDotNext, "server");
7132
- const nodeModules = path11.join(standaloneApp, "node_modules");
7133
- const internalPackage = path11.join(nodeModules, ...PACKAGE_NAME.split("/"));
7134
- return {
7135
- paths: {
7136
- nextApp: appDir,
7137
- builderOutput: outputDir2,
7138
- dotNext,
7139
- standaloneApp,
7140
- standaloneAppDotNext,
7141
- standaloneAppServer,
7142
- internalPackage
7143
- },
7144
- cache: {
7145
- kvBindingName: UserConfig.cache.bindingName
7146
- },
7147
- internalPackageName: PACKAGE_NAME
7148
- };
7149
- }
7150
- function containsDotNextDir(folder) {
7151
- try {
7152
- return statSync2(path11.join(folder, ".next")).isDirectory();
7153
- } catch (e) {
7154
- return false;
7155
- }
7156
- }
7157
- function getNextjsApplicationPath(dotNextDir) {
7158
- const serverPath = findServerParentPath(dotNextDir);
7159
- if (!serverPath) {
7160
- throw new Error(`Unexpected Error: no \`.next/server\` folder could be found in \`${serverPath}\``);
7161
- }
7162
- return relative(path11.join(dotNextDir, "standalone"), serverPath);
7163
- }
7164
- function findServerParentPath(parentPath) {
7165
- try {
7166
- if (statSync2(path11.join(parentPath, ".next", "server")).isDirectory()) {
7167
- return parentPath;
7168
- }
7169
- } catch {
7170
- }
7171
- const folders = readdirSync3(parentPath);
7172
- for (const folder of folders) {
7173
- const subFolder = path11.join(parentPath, folder);
7174
- if (statSync2(path11.join(parentPath, folder)).isDirectory()) {
7175
- const dirServerPath = findServerParentPath(subFolder);
7176
- if (dirServerPath) {
7177
- return dirServerPath;
7178
- }
7179
- }
7180
- }
7181
- }
7182
-
7183
7216
  // src/cli/build/index.ts
7184
7217
  import { cpSync as cpSync2 } from "node:fs";
7185
- import path12 from "node:path";
7218
+ import path13 from "node:path";
7219
+ import { rm } from "node:fs/promises";
7186
7220
  async function build2(appDir, opts) {
7187
7221
  if (!opts.skipBuild) {
7188
- buildNextjsApp(appDir);
7222
+ await buildNextjsApp(appDir);
7189
7223
  }
7190
7224
  if (!containsDotNextDir(appDir)) {
7191
7225
  throw new Error(`.next folder not found in ${appDir}`);
7192
7226
  }
7193
- const outputDir2 = path12.resolve(opts.outputDir ?? appDir, ".worker-next");
7227
+ const outputDir2 = path13.resolve(opts.outputDir ?? appDir, ".worker-next");
7194
7228
  await cleanDirectory(outputDir2);
7195
- cpSync2(path12.join(appDir, ".next"), path12.join(outputDir2, ".next"), { recursive: true });
7229
+ cpSync2(path13.join(appDir, ".next"), path13.join(outputDir2, ".next"), { recursive: true });
7196
7230
  const config = getConfig(appDir, outputDir2);
7197
7231
  await buildWorker(config);
7198
7232
  }
7199
- async function cleanDirectory(path13) {
7200
- return await rm(path13, { recursive: true, force: true });
7233
+ async function cleanDirectory(path14) {
7234
+ return await rm(path14, { recursive: true, force: true });
7201
7235
  }
7202
7236
 
7203
7237
  // src/cli/index.ts
7238
+ import { existsSync as existsSync4 } from "node:fs";
7239
+
7240
+ // src/cli/args.ts
7241
+ import { mkdirSync, statSync as statSync2 } from "node:fs";
7242
+ import { parseArgs } from "node:util";
7243
+ import { resolve } from "node:path";
7244
+ function getArgs() {
7245
+ const {
7246
+ values: { skipBuild: skipBuild2, output }
7247
+ } = parseArgs({
7248
+ options: {
7249
+ skipBuild: {
7250
+ type: "boolean",
7251
+ short: "s",
7252
+ default: false
7253
+ },
7254
+ output: {
7255
+ type: "string",
7256
+ short: "o"
7257
+ }
7258
+ },
7259
+ allowPositionals: false
7260
+ });
7261
+ const outputDir2 = output ? resolve(output) : void 0;
7262
+ if (outputDir2) {
7263
+ assertDirArg(outputDir2, "output", true);
7264
+ }
7265
+ return {
7266
+ outputDir: outputDir2,
7267
+ skipBuild: skipBuild2 || ["1", "true", "yes"].includes(String(process.env.SKIP_NEXT_APP_BUILD))
7268
+ };
7269
+ }
7270
+ function assertDirArg(path14, argName, make) {
7271
+ let dirStats;
7272
+ try {
7273
+ dirStats = statSync2(path14);
7274
+ } catch {
7275
+ if (!make) {
7276
+ throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a valid path`);
7277
+ }
7278
+ mkdirSync(path14);
7279
+ return;
7280
+ }
7281
+ if (!dirStats.isDirectory()) {
7282
+ throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a directory`);
7283
+ }
7284
+ }
7285
+
7286
+ // src/cli/index.ts
7287
+ import { resolve as resolve2 } from "node:path";
7204
7288
  var nextAppDir = resolve2(".");
7205
7289
  console.log(`Building the Next.js app in the current folder (${nextAppDir})`);
7206
7290
  if (!["js", "cjs", "mjs", "ts"].some((ext2) => existsSync4(`./next.config.${ext2}`))) {
@@ -17,7 +17,7 @@ function existsSync(path: string) {
17
17
  return FILES.has(path);
18
18
  }
19
19
 
20
- async function readFile(path: string, options: unknown): Promise<any> {
20
+ async function readFile(path: string, options: unknown): Promise<unknown> {
21
21
  console.log(
22
22
  "readFile",
23
23
  { path, options }
@@ -1,17 +1,18 @@
1
- import { AsyncLocalStorage } from "node:async_hooks";
2
- import Stream from "node:stream";
3
- import type { NextConfig } from "next";
4
- import { NodeNextRequest, NodeNextResponse } from "next/dist/server/base-http/node";
5
- import { MockedResponse } from "next/dist/server/lib/mock-request";
6
1
  import NextNodeServer, { NodeRequestHandler } from "next/dist/server/next-server";
7
- import type { IncomingMessage } from "node:http";
2
+ import { NodeNextRequest, NodeNextResponse } from "next/dist/server/base-http/node";
3
+ import { AsyncLocalStorage } from "node:async_hooks";
8
4
  import { type CloudflareContext } from "../../api";
5
+ import type { IncomingMessage } from "node:http";
6
+ import { MockedResponse } from "next/dist/server/lib/mock-request";
7
+ import type { NextConfig } from "next";
8
+ import Stream from "node:stream";
9
9
 
10
10
  const NON_BODY_RESPONSES = new Set([101, 204, 205, 304]);
11
11
 
12
12
  const cloudflareContextALS = new AsyncLocalStorage<CloudflareContext>();
13
13
 
14
14
  // Note: this symbol needs to be kept in sync with the one defined in `src/api/get-cloudflare-context.ts`
15
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
15
16
  (globalThis as any)[Symbol.for("__cloudflare-context__")] = new Proxy(
16
17
  {},
17
18
  {
@@ -29,6 +30,7 @@ const nextConfig: NextConfig = JSON.parse(process.env.__NEXT_PRIVATE_STANDALONE_
29
30
  let requestHandler: NodeRequestHandler | null = null;
30
31
 
31
32
  export default {
33
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
32
34
  async fetch(request: Request & { cf: IncomingRequestCfProperties }, env: any, ctx: any) {
33
35
  return cloudflareContextALS.run({ env, ctx, cf: request.cf }, async () => {
34
36
  if (requestHandler == null) {
@@ -45,12 +47,13 @@ export default {
45
47
  const url = new URL(request.url);
46
48
 
47
49
  if (url.pathname === "/_next/image") {
48
- let imageUrl =
50
+ const imageUrl =
49
51
  url.searchParams.get("url") ?? "https://developers.cloudflare.com/_astro/logo.BU9hiExz.svg";
50
52
  if (imageUrl.startsWith("/")) {
51
53
  return env.ASSETS.fetch(new URL(imageUrl, request.url));
52
54
  }
53
- return fetch(imageUrl, { cf: { cacheEverything: true } } as any);
55
+ // @ts-ignore
56
+ return fetch(imageUrl, { cf: { cacheEverything: true } } as unknown);
54
57
  }
55
58
 
56
59
  const { req, res, webResponse } = getWrappedStreams(request, ctx);
@@ -62,12 +65,12 @@ export default {
62
65
  },
63
66
  };
64
67
 
65
- function getWrappedStreams(request: Request, ctx: any) {
68
+ function getWrappedStreams(request: Request, ctx: ExecutionContext) {
66
69
  const url = new URL(request.url);
67
70
 
68
- const req = (
69
- request.body ? Stream.Readable.fromWeb(request.body as any) : Stream.Readable.from([])
70
- ) as IncomingMessage;
71
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
72
+ const reqBody = request.body && Stream.Readable.fromWeb(request.body as any);
73
+ const req = (reqBody ?? Stream.Readable.from([])) as IncomingMessage;
71
74
  req.httpVersion = "1.0";
72
75
  req.httpVersionMajor = 1;
73
76
  req.httpVersionMinor = 0;
@@ -94,7 +97,7 @@ function getWrappedStreams(request: Request, ctx: any) {
94
97
 
95
98
  const res = new MockedResponse({
96
99
  resWriter: (chunk) => {
97
- resBodyWriter.write(typeof chunk === "string" ? Buffer.from(chunk) : chunk).catch((err: any) => {
100
+ resBodyWriter.write(typeof chunk === "string" ? Buffer.from(chunk) : chunk).catch((err) => {
98
101
  if (
99
102
  err.message.includes("WritableStream has been closed") ||
100
103
  err.message.includes("Network connection lost")
@@ -110,6 +113,7 @@ function getWrappedStreams(request: Request, ctx: any) {
110
113
  });
111
114
 
112
115
  // It's implemented as a no-op, but really it should mark the headers as done
116
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
113
117
  res.flushHeaders = () => (res as any).headPromiseResolve();
114
118
 
115
119
  // Only allow statusCode to be modified if not sent
@@ -127,6 +131,7 @@ function getWrappedStreams(request: Request, ctx: any) {
127
131
  });
128
132
 
129
133
  // Make sure the writer is eventually closed
134
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
130
135
  ctx.waitUntil((res as any).hasStreamed.finally(() => resBodyWriter.close().catch(() => {})));
131
136
 
132
137
  return {
@@ -138,6 +143,7 @@ function getWrappedStreams(request: Request, ctx: any) {
138
143
  res.setHeader("content-encoding", "identity");
139
144
  return new Response(NON_BODY_RESPONSES.has(res.statusCode) ? null : readable, {
140
145
  status: res.statusCode,
146
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
141
147
  headers: (res as any).headers,
142
148
  });
143
149
  },
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@opennextjs/cloudflare",
3
3
  "description": "Cloudflare builder for next apps",
4
- "version": "0.0.0-b997312",
4
+ "version": "0.0.0-cf5113b",
5
5
  "bin": "dist/cli/index.mjs",
6
6
  "main": "./dist/api/index.mjs",
7
7
  "types": "./dist/api/index.d.mts",
@@ -31,24 +31,32 @@
31
31
  },
32
32
  "homepage": "https://github.com/opennextjs/opennextjs-cloudflare",
33
33
  "devDependencies": {
34
- "@cloudflare/workers-types": "^4.20240919.0",
34
+ "@cloudflare/workers-types": "^4.20240925.0",
35
+ "@eslint/js": "^9.11.1",
35
36
  "@types/node": "^22.2.0",
36
37
  "esbuild": "^0.23.0",
38
+ "eslint": "^9.11.1",
39
+ "eslint-plugin-unicorn": "^55.0.0",
37
40
  "glob": "^11.0.0",
41
+ "globals": "^15.9.0",
38
42
  "next": "14.2.11",
43
+ "package-manager-detector": "^0.2.0",
39
44
  "tsup": "^8.2.4",
40
45
  "typescript": "^5.5.4",
46
+ "typescript-eslint": "^8.7.0",
41
47
  "vitest": "^2.1.1"
42
48
  },
43
49
  "dependencies": {
44
50
  "ts-morph": "^23.0.0"
45
51
  },
46
52
  "peerDependencies": {
47
- "wrangler": "^3.78.6"
53
+ "wrangler": "^3.78.10"
48
54
  },
49
55
  "scripts": {
50
56
  "build": "tsup",
51
57
  "build:watch": "tsup --watch src",
58
+ "lint:check": "eslint",
59
+ "lint:fix": "eslint --fix",
52
60
  "test": "vitest --run",
53
61
  "test:watch": "vitest"
54
62
  }