@opennextjs/cloudflare 0.0.0-42320e7 → 0.0.0-5105d31

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.
@@ -1,29 +1,8 @@
1
1
  #!/usr/bin/env node
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __commonJS = (cb, mod) => function __require() {
9
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
- // If the importer is in node compatibility mode or this is not an ESM
21
- // file that has been converted to a CommonJS file using a Babel-
22
- // compatible transform (i.e. "__esModule" has not been set), then set
23
- // "default" to the CommonJS "module.exports" for node compatibility.
24
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
- mod
26
- ));
2
+ import {
3
+ __commonJS,
4
+ __toESM
5
+ } from "./chunk-UJCSKKID.mjs";
27
6
 
28
7
  // ../../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
29
8
  var require_balanced_match = __commonJS({
@@ -234,68 +213,171 @@ var require_brace_expansion = __commonJS({
234
213
  }
235
214
  });
236
215
 
237
- // src/index.ts
238
- import { resolve as resolve3 } from "node:path";
239
-
240
- // src/args.ts
241
- import { mkdirSync, statSync } from "node:fs";
242
- import { parseArgs } from "node:util";
243
- import { resolve } from "node:path";
244
- function getArgs() {
245
- const {
246
- values: { skipBuild: skipBuild2, output }
247
- } = parseArgs({
248
- options: {
249
- skipBuild: {
250
- type: "boolean",
251
- short: "s",
252
- default: false
253
- },
254
- output: {
255
- type: "string",
256
- short: "o"
257
- }
258
- },
259
- allowPositionals: false
260
- });
261
- const outputDir2 = output ? resolve(output) : void 0;
262
- if (outputDir2) {
263
- 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"
264
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("/"));
265
234
  return {
266
- outputDir: outputDir2,
267
- 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
268
249
  };
269
250
  }
270
- function assertDirArg(path6, argName, make) {
271
- let dirStats;
251
+ function containsDotNextDir(folder) {
272
252
  try {
273
- dirStats = statSync(path6);
253
+ return statSync(path.join(folder, ".next")).isDirectory();
274
254
  } catch {
275
- if (!make) {
276
- 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;
277
269
  }
278
- mkdirSync(path6);
279
- return;
270
+ } catch {
280
271
  }
281
- if (!dirStats.isDirectory()) {
282
- 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
+ }
283
281
  }
284
282
  }
285
283
 
286
- // src/index.ts
287
- 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
+ };
288
300
 
289
- // src/build/build.ts
290
- 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
+ }
291
369
 
292
- // src/build/build-next-app.ts
370
+ // src/cli/build/build-next-app.ts
293
371
  import { execSync } from "node:child_process";
294
- function buildNextjsApp(nextAppDir2) {
295
- 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);
296
378
  }
297
379
  function runNextBuildCommand(packager, nextAppDir2) {
298
- const command = ["bun", "npm"].includes(packager) ? `${packager} next build` : `${packager} next build`;
380
+ const command = `${packager === "npm" ? "npx" : packager} next build`;
299
381
  execSync(command, {
300
382
  stdio: "inherit",
301
383
  cwd: nextAppDir2,
@@ -308,31 +390,23 @@ function runNextBuildCommand(packager, nextAppDir2) {
308
390
  });
309
391
  }
310
392
 
311
- // src/build/build-worker.ts
393
+ // src/cli/build/build-worker.ts
312
394
  import { build } from "esbuild";
313
- import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
314
395
  import { cp, readFile, writeFile } from "node:fs/promises";
315
- import path4 from "node:path";
316
- import { fileURLToPath as fileURLToPath3 } from "node:url";
317
-
318
- // src/build/patches/investigated/patch-require.ts
319
- function patchRequire(code) {
320
- console.log("# patchRequire");
321
- return code.replace(/__require\d?\(/g, "require(").replace(/__require\d?\./g, "require.");
322
- }
396
+ import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
323
397
 
324
- // src/build/patches/investigated/copy-templates.ts
325
- import path from "node:path";
398
+ // src/cli/build/patches/investigated/copy-package-cli-files.ts
326
399
  import { cpSync } from "node:fs";
327
- function copyTemplates(srcDir, nextjsAppPaths) {
328
- console.log("# copyTemplates");
329
- const destDir = path.join(nextjsAppPaths.standaloneAppDir, "node_modules/cf/templates");
330
- cpSync(srcDir, destDir, { recursive: true });
331
- return destDir;
400
+ import path3 from "node:path";
401
+ function copyPackageCliFiles(packageDistDir2, config) {
402
+ console.log("# copyPackageTemplateFiles");
403
+ const sourceDir = path3.join(packageDistDir2, "cli");
404
+ const destinationDir = path3.join(config.paths.internalPackage, "cli");
405
+ cpSync(sourceDir, destinationDir, { recursive: true });
332
406
  }
333
407
 
334
- // src/build/patches/to-investigate/patch-read-file.ts
335
- import { readFileSync } from "node:fs";
408
+ // src/cli/build/build-worker.ts
409
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
336
410
 
337
411
  // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/index.js
338
412
  var import_brace_expansion = __toESM(require_brace_expansion(), 1);
@@ -1005,11 +1079,11 @@ var qmarksTestNoExtDot = ([$0]) => {
1005
1079
  return (f) => f.length === len && f !== "." && f !== "..";
1006
1080
  };
1007
1081
  var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
1008
- var path2 = {
1082
+ var path4 = {
1009
1083
  win32: { sep: "\\" },
1010
1084
  posix: { sep: "/" }
1011
1085
  };
1012
- var sep = defaultPlatform === "win32" ? path2.win32.sep : path2.posix.sep;
1086
+ var sep = defaultPlatform === "win32" ? path4.win32.sep : path4.posix.sep;
1013
1087
  minimatch.sep = sep;
1014
1088
  var GLOBSTAR = Symbol("globstar **");
1015
1089
  minimatch.GLOBSTAR = GLOBSTAR;
@@ -3039,7 +3113,7 @@ var LRUCache = class _LRUCache {
3039
3113
  // ../../node_modules/.pnpm/path-scurry@2.0.0/node_modules/path-scurry/dist/esm/index.js
3040
3114
  import { posix, win32 } from "node:path";
3041
3115
  import { fileURLToPath } from "node:url";
3042
- 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";
3043
3117
  import * as actualFS from "node:fs";
3044
3118
  import { lstat, readdir, readlink, realpath } from "node:fs/promises";
3045
3119
 
@@ -3772,10 +3846,10 @@ var Minipass = class extends EventEmitter {
3772
3846
  * Return a void Promise that resolves once the stream ends.
3773
3847
  */
3774
3848
  async promise() {
3775
- return new Promise((resolve4, reject) => {
3849
+ return new Promise((resolve3, reject) => {
3776
3850
  this.on(DESTROYED, () => reject(new Error("stream destroyed")));
3777
3851
  this.on("error", (er) => reject(er));
3778
- this.on("end", () => resolve4());
3852
+ this.on("end", () => resolve3());
3779
3853
  });
3780
3854
  }
3781
3855
  /**
@@ -3799,7 +3873,7 @@ var Minipass = class extends EventEmitter {
3799
3873
  return Promise.resolve({ done: false, value: res });
3800
3874
  if (this[EOF])
3801
3875
  return stop();
3802
- let resolve4;
3876
+ let resolve3;
3803
3877
  let reject;
3804
3878
  const onerr = (er) => {
3805
3879
  this.off("data", ondata);
@@ -3813,19 +3887,19 @@ var Minipass = class extends EventEmitter {
3813
3887
  this.off("end", onend);
3814
3888
  this.off(DESTROYED, ondestroy);
3815
3889
  this.pause();
3816
- resolve4({ value, done: !!this[EOF] });
3890
+ resolve3({ value, done: !!this[EOF] });
3817
3891
  };
3818
3892
  const onend = () => {
3819
3893
  this.off("error", onerr);
3820
3894
  this.off("data", ondata);
3821
3895
  this.off(DESTROYED, ondestroy);
3822
3896
  stop();
3823
- resolve4({ done: true, value: void 0 });
3897
+ resolve3({ done: true, value: void 0 });
3824
3898
  };
3825
3899
  const ondestroy = () => onerr(new Error("stream destroyed"));
3826
3900
  return new Promise((res2, rej) => {
3827
3901
  reject = rej;
3828
- resolve4 = res2;
3902
+ resolve3 = res2;
3829
3903
  this.once(DESTROYED, ondestroy);
3830
3904
  this.once("error", onerr);
3831
3905
  this.once("end", onend);
@@ -3926,7 +4000,7 @@ var realpathSync = rps.native;
3926
4000
  var defaultFS = {
3927
4001
  lstatSync,
3928
4002
  readdir: readdirCB,
3929
- readdirSync,
4003
+ readdirSync: readdirSync2,
3930
4004
  readlinkSync,
3931
4005
  realpathSync,
3932
4006
  promises: {
@@ -4186,12 +4260,12 @@ var PathBase = class {
4186
4260
  /**
4187
4261
  * Get the Path object referenced by the string path, resolved from this Path
4188
4262
  */
4189
- resolve(path6) {
4190
- if (!path6) {
4263
+ resolve(path14) {
4264
+ if (!path14) {
4191
4265
  return this;
4192
4266
  }
4193
- const rootPath = this.getRootString(path6);
4194
- const dir = path6.substring(rootPath.length);
4267
+ const rootPath = this.getRootString(path14);
4268
+ const dir = path14.substring(rootPath.length);
4195
4269
  const dirParts = dir.split(this.splitSep);
4196
4270
  const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
4197
4271
  return result;
@@ -4795,9 +4869,9 @@ var PathBase = class {
4795
4869
  if (this.#asyncReaddirInFlight) {
4796
4870
  await this.#asyncReaddirInFlight;
4797
4871
  } else {
4798
- let resolve4 = () => {
4872
+ let resolve3 = () => {
4799
4873
  };
4800
- this.#asyncReaddirInFlight = new Promise((res) => resolve4 = res);
4874
+ this.#asyncReaddirInFlight = new Promise((res) => resolve3 = res);
4801
4875
  try {
4802
4876
  for (const e of await this.#fs.promises.readdir(fullpath, {
4803
4877
  withFileTypes: true
@@ -4810,7 +4884,7 @@ var PathBase = class {
4810
4884
  children.provisional = 0;
4811
4885
  }
4812
4886
  this.#asyncReaddirInFlight = void 0;
4813
- resolve4();
4887
+ resolve3();
4814
4888
  }
4815
4889
  return children.slice(0, children.provisional);
4816
4890
  }
@@ -4943,8 +5017,8 @@ var PathWin32 = class _PathWin32 extends PathBase {
4943
5017
  /**
4944
5018
  * @internal
4945
5019
  */
4946
- getRootString(path6) {
4947
- return win32.parse(path6).root;
5020
+ getRootString(path14) {
5021
+ return win32.parse(path14).root;
4948
5022
  }
4949
5023
  /**
4950
5024
  * @internal
@@ -4990,8 +5064,8 @@ var PathPosix = class _PathPosix extends PathBase {
4990
5064
  /**
4991
5065
  * @internal
4992
5066
  */
4993
- getRootString(path6) {
4994
- return path6.startsWith("/") ? "/" : "";
5067
+ getRootString(path14) {
5068
+ return path14.startsWith("/") ? "/" : "";
4995
5069
  }
4996
5070
  /**
4997
5071
  * @internal
@@ -5040,8 +5114,8 @@ var PathScurryBase = class {
5040
5114
  *
5041
5115
  * @internal
5042
5116
  */
5043
- constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs2 = defaultFS } = {}) {
5044
- this.#fs = fsFromOption(fs2);
5117
+ constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs3 = defaultFS } = {}) {
5118
+ this.#fs = fsFromOption(fs3);
5045
5119
  if (cwd instanceof URL || cwd.startsWith("file://")) {
5046
5120
  cwd = fileURLToPath(cwd);
5047
5121
  }
@@ -5080,11 +5154,11 @@ var PathScurryBase = class {
5080
5154
  /**
5081
5155
  * Get the depth of a provided path, string, or the cwd
5082
5156
  */
5083
- depth(path6 = this.cwd) {
5084
- if (typeof path6 === "string") {
5085
- path6 = this.cwd.resolve(path6);
5157
+ depth(path14 = this.cwd) {
5158
+ if (typeof path14 === "string") {
5159
+ path14 = this.cwd.resolve(path14);
5086
5160
  }
5087
- return path6.depth();
5161
+ return path14.depth();
5088
5162
  }
5089
5163
  /**
5090
5164
  * Return the cache of child entries. Exposed so subclasses can create
@@ -5463,7 +5537,7 @@ var PathScurryBase = class {
5463
5537
  const dirs = /* @__PURE__ */ new Set();
5464
5538
  const queue = [entry];
5465
5539
  let processing = 0;
5466
- const process2 = () => {
5540
+ const process3 = () => {
5467
5541
  let paused = false;
5468
5542
  while (!paused) {
5469
5543
  const dir = queue.shift();
@@ -5504,9 +5578,9 @@ var PathScurryBase = class {
5504
5578
  }
5505
5579
  }
5506
5580
  if (paused && !results.flowing) {
5507
- results.once("drain", process2);
5581
+ results.once("drain", process3);
5508
5582
  } else if (!sync2) {
5509
- process2();
5583
+ process3();
5510
5584
  }
5511
5585
  };
5512
5586
  let sync2 = true;
@@ -5514,7 +5588,7 @@ var PathScurryBase = class {
5514
5588
  sync2 = false;
5515
5589
  }
5516
5590
  };
5517
- process2();
5591
+ process3();
5518
5592
  return results;
5519
5593
  }
5520
5594
  streamSync(entry = this.cwd, opts = {}) {
@@ -5532,7 +5606,7 @@ var PathScurryBase = class {
5532
5606
  }
5533
5607
  const queue = [entry];
5534
5608
  let processing = 0;
5535
- const process2 = () => {
5609
+ const process3 = () => {
5536
5610
  let paused = false;
5537
5611
  while (!paused) {
5538
5612
  const dir = queue.shift();
@@ -5566,14 +5640,14 @@ var PathScurryBase = class {
5566
5640
  }
5567
5641
  }
5568
5642
  if (paused && !results.flowing)
5569
- results.once("drain", process2);
5643
+ results.once("drain", process3);
5570
5644
  };
5571
- process2();
5645
+ process3();
5572
5646
  return results;
5573
5647
  }
5574
- chdir(path6 = this.cwd) {
5648
+ chdir(path14 = this.cwd) {
5575
5649
  const oldCwd = this.cwd;
5576
- this.cwd = typeof path6 === "string" ? this.cwd.resolve(path6) : path6;
5650
+ this.cwd = typeof path14 === "string" ? this.cwd.resolve(path14) : path14;
5577
5651
  this.cwd[setAsCwd](oldCwd);
5578
5652
  }
5579
5653
  };
@@ -5599,8 +5673,8 @@ var PathScurryWin32 = class extends PathScurryBase {
5599
5673
  /**
5600
5674
  * @internal
5601
5675
  */
5602
- newRoot(fs2) {
5603
- 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 });
5604
5678
  }
5605
5679
  /**
5606
5680
  * Return true if the provided path string is an absolute path
@@ -5628,8 +5702,8 @@ var PathScurryPosix = class extends PathScurryBase {
5628
5702
  /**
5629
5703
  * @internal
5630
5704
  */
5631
- newRoot(fs2) {
5632
- 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 });
5633
5707
  }
5634
5708
  /**
5635
5709
  * Return true if the provided path string is an absolute path
@@ -5929,8 +6003,8 @@ var MatchRecord = class {
5929
6003
  }
5930
6004
  // match, absolute, ifdir
5931
6005
  entries() {
5932
- return [...this.store.entries()].map(([path6, n]) => [
5933
- path6,
6006
+ return [...this.store.entries()].map(([path14, n]) => [
6007
+ path14,
5934
6008
  !!(n & 2),
5935
6009
  !!(n & 1)
5936
6010
  ]);
@@ -6135,9 +6209,9 @@ var GlobUtil = class {
6135
6209
  signal;
6136
6210
  maxDepth;
6137
6211
  includeChildMatches;
6138
- constructor(patterns, path6, opts) {
6212
+ constructor(patterns, path14, opts) {
6139
6213
  this.patterns = patterns;
6140
- this.path = path6;
6214
+ this.path = path14;
6141
6215
  this.opts = opts;
6142
6216
  this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/";
6143
6217
  this.includeChildMatches = opts.includeChildMatches !== false;
@@ -6156,11 +6230,11 @@ var GlobUtil = class {
6156
6230
  });
6157
6231
  }
6158
6232
  }
6159
- #ignored(path6) {
6160
- return this.seen.has(path6) || !!this.#ignore?.ignored?.(path6);
6233
+ #ignored(path14) {
6234
+ return this.seen.has(path14) || !!this.#ignore?.ignored?.(path14);
6161
6235
  }
6162
- #childrenIgnored(path6) {
6163
- return !!this.#ignore?.childrenIgnored?.(path6);
6236
+ #childrenIgnored(path14) {
6237
+ return !!this.#ignore?.childrenIgnored?.(path14);
6164
6238
  }
6165
6239
  // backpressure mechanism
6166
6240
  pause() {
@@ -6375,8 +6449,8 @@ var GlobUtil = class {
6375
6449
  };
6376
6450
  var GlobWalker = class extends GlobUtil {
6377
6451
  matches = /* @__PURE__ */ new Set();
6378
- constructor(patterns, path6, opts) {
6379
- super(patterns, path6, opts);
6452
+ constructor(patterns, path14, opts) {
6453
+ super(patterns, path14, opts);
6380
6454
  }
6381
6455
  matchEmit(e) {
6382
6456
  this.matches.add(e);
@@ -6413,8 +6487,8 @@ var GlobWalker = class extends GlobUtil {
6413
6487
  };
6414
6488
  var GlobStream = class extends GlobUtil {
6415
6489
  results;
6416
- constructor(patterns, path6, opts) {
6417
- super(patterns, path6, opts);
6490
+ constructor(patterns, path14, opts) {
6491
+ super(patterns, path14, opts);
6418
6492
  this.results = new Minipass({
6419
6493
  signal: this.signal,
6420
6494
  objectMode: true
@@ -6707,60 +6781,44 @@ var glob = Object.assign(glob_, {
6707
6781
  });
6708
6782
  glob.glob = glob;
6709
6783
 
6710
- // src/build/patches/to-investigate/patch-read-file.ts
6711
- function patchReadFile(code, nextjsAppPaths) {
6712
- console.log("# patchReadFile");
6713
- code = code.replace(
6714
- "getBuildId() {",
6715
- `getBuildId() {
6716
- return ${JSON.stringify(readFileSync(`${nextjsAppPaths.standaloneAppDotNextDir}/BUILD_ID`, "utf-8"))};
6717
- `
6718
- );
6719
- const manifestJsons = globSync(`${nextjsAppPaths.standaloneAppDotNextDir}/**/*-manifest.json`).map(
6720
- (file) => file.replace(nextjsAppPaths.standaloneAppDir + "/", "")
6721
- );
6722
- code = code.replace(
6723
- /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\((.+?), .+?\) {/,
6724
6793
  `$&
6725
- ${manifestJsons.map(
6726
- (manifestJson) => `
6727
- if ($1.endsWith("${manifestJson}")) {
6728
- return ${readFileSync(`${nextjsAppPaths.standaloneAppDir}/${manifestJson}`, "utf-8")};
6729
- }
6730
- `
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
+ `
6731
6805
  ).join("\n")}
6732
- throw new Error("Unknown loadManifest: " + $1);
6733
- `
6734
- );
6735
- return code;
6736
- }
6737
-
6738
- // src/build/patches/to-investigate/patch-find-dir.ts
6739
- import { existsSync } from "node:fs";
6740
- function patchFindDir(code, nextjsAppPaths) {
6741
- console.log("# patchFindDir");
6742
- return code.replace(
6743
- "function findDir(dir, name) {",
6744
- `function findDir(dir, name) {
6745
- if (dir.endsWith(".next/server")) {
6746
- if (name === "app") return ${existsSync(`${nextjsAppPaths.standaloneAppServerDir}/app`)};
6747
- if (name === "pages") return ${existsSync(`${nextjsAppPaths.standaloneAppServerDir}/pages`)};
6748
- }
6749
- throw new Error("Unknown findDir call: " + dir + " " + name);
6806
+ throw new Error("Unknown evalManifest: " + $1);
6750
6807
  `
6751
6808
  );
6752
6809
  }
6753
6810
 
6754
- // src/build/patches/to-investigate/inline-next-require.ts
6755
- import { readFileSync as readFileSync2, existsSync as existsSync2 } from "node:fs";
6756
- function inlineNextRequire(code, nextjsAppPaths) {
6811
+ // src/cli/build/patches/to-investigate/inline-next-require.ts
6812
+ import { existsSync, readFileSync } from "node:fs";
6813
+ import path6 from "node:path";
6814
+ function inlineNextRequire(code, config) {
6757
6815
  console.log("# inlineNextRequire");
6758
- const pagesManifestFile = `${nextjsAppPaths.standaloneAppServerDir}/pages-manifest.json`;
6759
- const appPathsManifestFile = `${nextjsAppPaths.standaloneAppServerDir}/app-paths-manifest.json`;
6760
- 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(
6761
6819
  (file) => ".next/server/" + file
6762
6820
  ) : [];
6763
- 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(
6764
6822
  (file) => ".next/server/" + file
6765
6823
  ) : [];
6766
6824
  const allManifestFiles = pagesManifestFiles.concat(appPathsManifestFiles);
@@ -6772,14 +6830,14 @@ function inlineNextRequire(code, nextjsAppPaths) {
6772
6830
  ${htmlPages.map(
6773
6831
  (htmlPage) => `
6774
6832
  if (pagePath.endsWith("${htmlPage}")) {
6775
- return ${JSON.stringify(readFileSync2(`${nextjsAppPaths.standaloneAppDir}/${htmlPage}`, "utf-8"))};
6833
+ return ${JSON.stringify(readFileSync(path6.join(config.paths.standaloneApp, htmlPage), "utf-8"))};
6776
6834
  }
6777
6835
  `
6778
6836
  ).join("\n")}
6779
6837
  ${pageModules.map(
6780
6838
  (module) => `
6781
6839
  if (pagePath.endsWith("${module}")) {
6782
- return require("${nextjsAppPaths.standaloneAppDir}/${module}");
6840
+ return require("${path6.join(config.paths.standaloneApp, module)}");
6783
6841
  }
6784
6842
  `
6785
6843
  ).join("\n")}
@@ -6788,67 +6846,112 @@ function inlineNextRequire(code, nextjsAppPaths) {
6788
6846
  );
6789
6847
  }
6790
6848
 
6791
- // src/build/patches/to-investigate/inline-eval-manifest.ts
6792
- function inlineEvalManifest(code, nextjsAppPaths) {
6793
- console.log("# inlineEvalManifest");
6794
- const manifestJss = globSync(
6795
- `${nextjsAppPaths.standaloneAppDotNextDir}/**/*_client-reference-manifest.js`
6796
- ).map((file) => file.replace(`${nextjsAppPaths.standaloneAppDir}/`, ""));
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");
6797
6872
  return code.replace(
6798
- /function evalManifest\((.+?), .+?\) {/,
6799
- `$&
6800
- ${manifestJss.map(
6801
- (manifestJs) => `
6802
- if ($1.endsWith("${manifestJs}")) {
6803
- require("${nextjsAppPaths.standaloneAppDir}/${manifestJs}");
6804
- return {
6805
- __RSC_MANIFEST: {
6806
- "${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}": globalThis.__RSC_MANIFEST["${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}"],
6807
- },
6808
- };
6809
- }
6810
- `
6811
- ).join("\n")}
6812
- throw new Error("Unknown evalManifest: " + $1);
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);
6813
6884
  `
6814
6885
  );
6815
6886
  }
6816
6887
 
6817
- // src/build/patches/to-investigate/wrangler-deps.ts
6818
- import path3 from "node:path";
6819
- import fs, { writeFileSync } from "node:fs";
6820
- function patchWranglerDeps(paths) {
6821
- console.log("# patchWranglerDeps");
6822
- console.log({ base: paths.standaloneAppDotNextDir });
6823
- const pagesRuntimeFile = path3.join(
6824
- paths.standaloneAppDir,
6825
- "node_modules",
6826
- "next",
6827
- "dist",
6828
- "compiled",
6829
- "next-server",
6830
- "pages.runtime.prod.js"
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
+ `
6831
6898
  );
6832
- const patchedPagesRuntime = fs.readFileSync(pagesRuntimeFile, "utf-8").replace(`e.exports=require("critters")`, `e.exports={}`);
6833
- fs.writeFileSync(pagesRuntimeFile, patchedPagesRuntime);
6834
- const tracerFile = path3.join(
6835
- paths.standaloneAppDir,
6836
- "node_modules",
6837
- "next",
6838
- "dist",
6839
- "server",
6840
- "lib",
6841
- "trace",
6842
- "tracer.js"
6899
+ const manifestJsons = globSync(path9.join(config.paths.standaloneAppDotNext, "**", "*-manifest.json")).map(
6900
+ (file) => file.replace(config.paths.standaloneApp + "/", "")
6843
6901
  );
6844
- const pacthedTracer = fs.readFileSync(tracerFile, "utf-8").replaceAll(/\w+\s*=\s*require\([^/]*opentelemetry.*\)/g, `throw new Error("@opentelemetry/api")`);
6902
+ code = code.replace(
6903
+ /function loadManifest\((.+?), .+?\) {/,
6904
+ `$&
6905
+ ${manifestJsons.map(
6906
+ (manifestJson) => `
6907
+ if ($1.endsWith("${manifestJson}")) {
6908
+ return ${readFileSync2(path9.join(config.paths.standaloneApp, manifestJson), "utf-8")};
6909
+ }
6910
+ `
6911
+ ).join("\n")}
6912
+ throw new Error("Unknown loadManifest: " + $1);
6913
+ `
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.");
6922
+ }
6923
+
6924
+ // src/cli/build/patches/to-investigate/wrangler-deps.ts
6925
+ import fs2, { writeFileSync } from "node:fs";
6926
+ import path10 from "node:path";
6927
+ function patchWranglerDeps(config) {
6928
+ console.log("# patchWranglerDeps");
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")`);
6845
6935
  writeFileSync(tracerFile, pacthedTracer);
6846
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
+ }
6847
6947
 
6848
- // src/build/patches/investigated/update-webpack-chunks-file/index.ts
6849
- import { readdirSync as readdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
6948
+ // src/cli/build/build-worker.ts
6949
+ import path12 from "node:path";
6850
6950
 
6851
- // src/build/patches/investigated/update-webpack-chunks-file/get-chunk-installation-identifiers.ts
6951
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/index.ts
6952
+ import { readFileSync as readFileSync3, readdirSync as readdirSync3, writeFileSync as writeFileSync2 } from "node:fs";
6953
+
6954
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/get-chunk-installation-identifiers.ts
6852
6955
  import * as ts from "ts-morph";
6853
6956
  async function getChunkInstallationIdentifiers(sourceFile) {
6854
6957
  const installChunkDeclaration = getInstallChunkDeclaration(sourceFile);
@@ -6894,7 +6997,7 @@ function getInstalledChunksDeclaration(sourceFile, installChunkDeclaration) {
6894
6997
  return installedChunksDeclaration;
6895
6998
  }
6896
6999
 
6897
- // src/build/patches/investigated/update-webpack-chunks-file/get-file-content-with-updated-webpack-f-require-code.ts
7000
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/get-file-content-with-updated-webpack-f-require-code.ts
6898
7001
  import * as ts2 from "ts-morph";
6899
7002
  async function getFileContentWithUpdatedWebpackFRequireCode(sourceFile, { installedChunks, installChunk }, chunks) {
6900
7003
  const webpackFRequireFunction = sourceFile.getDescendantsOfKind(ts2.SyntaxKind.ArrowFunction).find((arrowFunction) => {
@@ -6938,7 +7041,7 @@ if(${chunkId} === ${chunk}) return ${installChunk}(require("./chunks/${chunk}.js
6938
7041
  return sourceFile.print();
6939
7042
  }
6940
7043
 
6941
- // src/build/utils/ts-parse-file.ts
7044
+ // src/cli/build/utils/ts-parse-file.ts
6942
7045
  import * as ts3 from "ts-morph";
6943
7046
  function tsParseFile(fileContent) {
6944
7047
  const project = new ts3.Project();
@@ -6946,7 +7049,7 @@ function tsParseFile(fileContent) {
6946
7049
  return sourceFile;
6947
7050
  }
6948
7051
 
6949
- // src/build/patches/investigated/update-webpack-chunks-file/get-updated-webpack-chunks-file-content.ts
7052
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/get-updated-webpack-chunks-file-content.ts
6950
7053
  async function getUpdatedWebpackChunksFileContent(fileContent, chunks) {
6951
7054
  const tsSourceFile = tsParseFile(fileContent);
6952
7055
  const chunkInstallationIdentifiers = await getChunkInstallationIdentifiers(tsSourceFile);
@@ -6958,12 +7061,13 @@ async function getUpdatedWebpackChunksFileContent(fileContent, chunks) {
6958
7061
  return updatedFileContent;
6959
7062
  }
6960
7063
 
6961
- // src/build/patches/investigated/update-webpack-chunks-file/index.ts
6962
- async function updateWebpackChunksFile(nextjsAppPaths) {
7064
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/index.ts
7065
+ import path11 from "node:path";
7066
+ async function updateWebpackChunksFile(config) {
6963
7067
  console.log("# updateWebpackChunksFile");
6964
- const webpackRuntimeFile = `${nextjsAppPaths.standaloneAppServerDir}/webpack-runtime.js`;
7068
+ const webpackRuntimeFile = path11.join(config.paths.standaloneAppServer, "webpack-runtime.js");
6965
7069
  const fileContent = readFileSync3(webpackRuntimeFile, "utf-8");
6966
- const chunks = readdirSync2(`${nextjsAppPaths.standaloneAppServerDir}/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) => {
6967
7071
  console.log(` - chunk ${chunk}`);
6968
7072
  return chunk.replace(/\.js$/, "");
6969
7073
  });
@@ -6971,19 +7075,35 @@ async function updateWebpackChunksFile(nextjsAppPaths) {
6971
7075
  writeFileSync2(webpackRuntimeFile, updatedFileContent);
6972
7076
  }
6973
7077
 
6974
- // src/build/build-worker.ts
6975
- var templateSrcDir = path4.join(path4.dirname(fileURLToPath3(import.meta.url)), "templates");
6976
- async function buildWorker(appDir, outputDir2, nextjsAppPaths) {
6977
- const templateDir = copyTemplates(templateSrcDir, nextjsAppPaths);
6978
- const workerEntrypoint = `${templateDir}/worker.ts`;
6979
- const workerOutputFile = `${outputDir2}/index.mjs`;
6980
- const nextConfigStr = readFileSync4(nextjsAppPaths.standaloneAppDir + "/server.js", "utf8")?.match(
7078
+ // src/cli/build/build-worker.ts
7079
+ var packageDistDir = path12.join(path12.dirname(fileURLToPath3(import.meta.url)), "..");
7080
+ async function buildWorker(config) {
7081
+ console.log(`\x1B[35m\u2699\uFE0F Copying files...
7082
+ \x1B[0m`);
7083
+ await cp(
7084
+ path12.join(config.paths.dotNext, "static"),
7085
+ path12.join(config.paths.builderOutput, "assets", "_next", "static"),
7086
+ {
7087
+ recursive: true
7088
+ }
7089
+ );
7090
+ const publicDir = path12.join(config.paths.nextApp, "public");
7091
+ if (existsSync3(publicDir)) {
7092
+ await cp(publicDir, path12.join(config.paths.builderOutput, "assets"), {
7093
+ recursive: true
7094
+ });
7095
+ }
7096
+ copyPackageCliFiles(packageDistDir, config);
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(
6981
7101
  /const nextConfig = ({.+?})\n/
6982
7102
  )?.[1] ?? {};
6983
7103
  console.log(`\x1B[35m\u2699\uFE0F Bundling the worker file...
6984
7104
  \x1B[0m`);
6985
- patchWranglerDeps(nextjsAppPaths);
6986
- updateWebpackChunksFile(nextjsAppPaths);
7105
+ patchWranglerDeps(config);
7106
+ updateWebpackChunksFile(config);
6987
7107
  await build({
6988
7108
  entryPoints: [workerEntrypoint],
6989
7109
  bundle: true,
@@ -6996,15 +7116,15 @@ async function buildWorker(appDir, outputDir2, nextjsAppPaths) {
6996
7116
  // Note: we apply an empty shim to next/dist/compiled/ws because it generates two `eval`s:
6997
7117
  // eval("require")("bufferutil");
6998
7118
  // eval("require")("utf-8-validate");
6999
- "next/dist/compiled/ws": `${templateDir}/shims/empty.ts`,
7119
+ "next/dist/compiled/ws": path12.join(templateDir, "shims", "empty.ts"),
7000
7120
  // Note: we apply an empty shim to next/dist/compiled/edge-runtime since (amongst others) it generated the following `eval`:
7001
7121
  // eval(getModuleCode)(module, module.exports, throwingRequire, params.context, ...Object.values(params.scopedContext));
7002
7122
  // which comes from https://github.com/vercel/edge-runtime/blob/6e96b55f/packages/primitives/src/primitives/load.js#L57-L63
7003
7123
  // QUESTION: Why did I encountered this but mhart didn't?
7004
- "next/dist/compiled/edge-runtime": `${templateDir}/shims/empty.ts`,
7124
+ "next/dist/compiled/edge-runtime": path12.join(templateDir, "shims", "empty.ts"),
7005
7125
  // `@next/env` is a library Next.js uses for loading dotenv files, for obvious reasons we need to stub it here
7006
7126
  // source: https://github.com/vercel/next.js/tree/0ac10d79720/packages/next-env
7007
- "@next/env": `${templateDir}/shims/env.ts`
7127
+ "@next/env": path12.join(templateDir, "shims", "env.ts")
7008
7128
  },
7009
7129
  define: {
7010
7130
  // config file used by Next.js, see: https://github.com/vercel/next.js/blob/68a7128/packages/next/src/build/utils.ts#L2137-L2139
@@ -7038,22 +7158,21 @@ async function buildWorker(appDir, outputDir2, nextjsAppPaths) {
7038
7158
  // Do not crash on cache not supported
7039
7159
  // https://github.com/cloudflare/workerd/pull/2434
7040
7160
  // compatibility flag "cache_option_enabled" -> does not support "force-cache"
7041
- let isPatchedAlready = globalThis.fetch.__nextPatched;
7042
7161
  const curFetch = globalThis.fetch;
7043
7162
  globalThis.fetch = (input, init) => {
7044
- console.log("globalThis.fetch", input);
7045
- if (init) delete init.cache;
7163
+ if (init) {
7164
+ delete init.cache;
7165
+ }
7046
7166
  return curFetch(input, init);
7047
7167
  };
7048
7168
  import { Readable } from 'node:stream';
7049
- globalThis.fetch.__nextPatched = isPatchedAlready;
7050
7169
  fetch = globalThis.fetch;
7051
7170
  const CustomRequest = class extends globalThis.Request {
7052
7171
  constructor(input, init) {
7053
- console.log("CustomRequest", input);
7054
7172
  if (init) {
7055
7173
  delete init.cache;
7056
7174
  if (init.body?.__node_stream__ === true) {
7175
+ // https://github.com/cloudflare/workerd/issues/2746
7057
7176
  init.body = Readable.toWeb(init.body);
7058
7177
  }
7059
7178
  }
@@ -7062,115 +7181,111 @@ const CustomRequest = class extends globalThis.Request {
7062
7181
  };
7063
7182
  globalThis.Request = CustomRequest;
7064
7183
  Request = globalThis.Request;
7065
- `
7184
+ `
7066
7185
  }
7067
7186
  });
7068
- await updateWorkerBundledCode(workerOutputFile, nextjsAppPaths);
7069
- console.log(`\x1B[35m\u2699\uFE0F Copying asset files...
7070
- \x1B[0m`);
7071
- await cp(`${nextjsAppPaths.dotNextDir}/static`, `${outputDir2}/assets/_next/static`, {
7072
- recursive: true
7073
- });
7074
- if (existsSync3(`${appDir}/public`)) {
7075
- await cp(`${appDir}/public`, `${outputDir2}/assets`, {
7076
- recursive: true
7077
- });
7078
- }
7187
+ await updateWorkerBundledCode(workerOutputFile, config);
7079
7188
  console.log(`\x1B[35mWorker saved in \`${workerOutputFile}\` \u{1F680}
7080
7189
  \x1B[0m`);
7081
7190
  }
7082
- async function updateWorkerBundledCode(workerOutputFile, nextjsAppPaths) {
7191
+ async function updateWorkerBundledCode(workerOutputFile, config) {
7083
7192
  const originalCode = await readFile(workerOutputFile, "utf8");
7084
7193
  let patchedCode = originalCode;
7085
7194
  patchedCode = patchRequire(patchedCode);
7086
- patchedCode = patchReadFile(patchedCode, nextjsAppPaths);
7087
- patchedCode = inlineNextRequire(patchedCode, nextjsAppPaths);
7088
- patchedCode = patchFindDir(patchedCode, nextjsAppPaths);
7089
- patchedCode = inlineEvalManifest(patchedCode, nextjsAppPaths);
7195
+ patchedCode = patchReadFile(patchedCode, config);
7196
+ patchedCode = inlineNextRequire(patchedCode, config);
7197
+ patchedCode = patchFindDir(patchedCode, config);
7198
+ patchedCode = inlineEvalManifest(patchedCode, config);
7199
+ patchedCode = patchCache(patchedCode, config);
7090
7200
  await writeFile(workerOutputFile, patchedCode);
7091
7201
  }
7092
7202
  function createFixRequiresESBuildPlugin(templateDir) {
7093
7203
  return {
7094
7204
  name: "replaceRelative",
7095
7205
  setup(build3) {
7096
- build3.onResolve({ filter: /^\.\/require-hook$/ }, (args) => ({
7097
- path: `${templateDir}/shims/empty.ts`
7206
+ build3.onResolve({ filter: /^\.\/require-hook$/ }, () => ({
7207
+ path: path12.join(templateDir, "shims", "empty.ts")
7098
7208
  }));
7099
- build3.onResolve({ filter: /\.\/lib\/node-fs-methods$/ }, (args) => ({
7100
- path: `${templateDir}/shims/node-fs.ts`
7209
+ build3.onResolve({ filter: /\.\/lib\/node-fs-methods$/ }, () => ({
7210
+ path: path12.join(templateDir, "shims", "empty.ts")
7101
7211
  }));
7102
7212
  }
7103
7213
  };
7104
7214
  }
7105
7215
 
7106
- // src/nextjs-paths.ts
7107
- import { readdirSync as readdirSync3, statSync as statSync2 } from "node:fs";
7108
- import path5, { relative } from "node:path";
7109
- function getNextjsAppPaths(baseDir) {
7110
- const dotNextDir = getDotNextDirPath(baseDir);
7111
- const appPath = getNextjsApplicationPath(dotNextDir).replace(/\/$/, "");
7112
- const standaloneAppDir = path5.join(dotNextDir, "standalone", appPath);
7216
+ // src/cli/build/index.ts
7217
+ import { cpSync as cpSync2 } from "node:fs";
7218
+ import path13 from "node:path";
7219
+ import { rm } from "node:fs/promises";
7220
+ async function build2(appDir, opts) {
7221
+ if (!opts.skipBuild) {
7222
+ await buildNextjsApp(appDir);
7223
+ }
7224
+ if (!containsDotNextDir(appDir)) {
7225
+ throw new Error(`.next folder not found in ${appDir}`);
7226
+ }
7227
+ const outputDir2 = path13.resolve(opts.outputDir ?? appDir, ".worker-next");
7228
+ await cleanDirectory(outputDir2);
7229
+ cpSync2(path13.join(appDir, ".next"), path13.join(outputDir2, ".next"), { recursive: true });
7230
+ const config = getConfig(appDir, outputDir2);
7231
+ await buildWorker(config);
7232
+ }
7233
+ async function cleanDirectory(path14) {
7234
+ return await rm(path14, { recursive: true, force: true });
7235
+ }
7236
+
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
+ }
7113
7265
  return {
7114
- dotNextDir,
7115
- standaloneAppDir,
7116
- standaloneAppDotNextDir: path5.join(standaloneAppDir, ".next"),
7117
- standaloneAppServerDir: path5.join(standaloneAppDir, ".next", "server")
7266
+ outputDir: outputDir2,
7267
+ skipBuild: skipBuild2 || ["1", "true", "yes"].includes(String(process.env.SKIP_NEXT_APP_BUILD))
7118
7268
  };
7119
7269
  }
7120
- function getDotNextDirPath(nextAppDir2) {
7121
- const dotNextDirPath = `${nextAppDir2}/.next`;
7270
+ function assertDirArg(path14, argName, make) {
7271
+ let dirStats;
7122
7272
  try {
7123
- const dirStats = statSync2(dotNextDirPath);
7124
- if (!dirStats.isDirectory()) throw new Error();
7273
+ dirStats = statSync2(path14);
7125
7274
  } catch {
7126
- throw new Error(`Error: \`.next\` directory not found!`);
7127
- }
7128
- return dotNextDirPath;
7129
- }
7130
- function getNextjsApplicationPath(dotNextDir) {
7131
- const serverPath = findServerParentPath(dotNextDir);
7132
- if (!serverPath) {
7133
- throw new Error(`Unexpected Error: no \`.next/server\` folder could be found in \`${serverPath}\``);
7134
- }
7135
- return relative(`${dotNextDir}/standalone`, serverPath);
7136
- function findServerParentPath(path6) {
7137
- try {
7138
- if (statSync2(`${path6}/.next/server`).isDirectory()) {
7139
- return path6;
7140
- }
7141
- } catch {
7142
- }
7143
- const files = readdirSync3(path6);
7144
- for (const file of files) {
7145
- if (statSync2(`${path6}/${file}`).isDirectory()) {
7146
- const dirServerPath = findServerParentPath(`${path6}/${file}`);
7147
- if (dirServerPath) {
7148
- return dirServerPath;
7149
- }
7150
- }
7275
+ if (!make) {
7276
+ throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a valid path`);
7151
7277
  }
7278
+ mkdirSync(path14);
7279
+ return;
7152
7280
  }
7153
- }
7154
-
7155
- // src/build/build.ts
7156
- import { cpSync as cpSync2 } from "node:fs";
7157
- import { resolve as resolve2 } from "node:path";
7158
- async function build2(appDir, opts) {
7159
- if (!opts.skipBuild) {
7160
- buildNextjsApp(appDir);
7281
+ if (!dirStats.isDirectory()) {
7282
+ throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a directory`);
7161
7283
  }
7162
- const outputDir2 = resolve2(opts.outputDir ?? appDir, ".worker-next");
7163
- await cleanDirectory(outputDir2);
7164
- cpSync2(resolve2(`${appDir}/.next`), resolve2(`${outputDir2}/.next`), { recursive: true });
7165
- const nextjsAppPaths = getNextjsAppPaths(outputDir2);
7166
- await buildWorker(appDir, outputDir2, nextjsAppPaths);
7167
- }
7168
- async function cleanDirectory(path6) {
7169
- return await rm(path6, { recursive: true, force: true });
7170
7284
  }
7171
7285
 
7172
- // src/index.ts
7173
- var nextAppDir = resolve3(".");
7286
+ // src/cli/index.ts
7287
+ import { resolve as resolve2 } from "node:path";
7288
+ var nextAppDir = resolve2(".");
7174
7289
  console.log(`Building the Next.js app in the current folder (${nextAppDir})`);
7175
7290
  if (!["js", "cjs", "mjs", "ts"].some((ext2) => existsSync4(`./next.config.${ext2}`))) {
7176
7291
  throw new Error("Error: Not in a Next.js app project");