@opennextjs/cloudflare 0.0.0-9758666 → 0.0.0-9aff12e

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.
@@ -213,68 +213,169 @@ var require_brace_expansion = __commonJS({
213
213
  }
214
214
  });
215
215
 
216
- // src/index.ts
217
- import { resolve as resolve2 } from "node:path";
218
-
219
- // src/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 standaloneApp = path.join(dotNext, "standalone", appPath);
229
+ const standaloneAppDotNext = path.join(standaloneApp, ".next");
230
+ const standaloneAppServer = path.join(standaloneAppDotNext, "server");
231
+ const nodeModules = path.join(standaloneApp, "node_modules");
232
+ const internalPackage = path.join(nodeModules, ...PACKAGE_NAME.split("/"));
244
233
  return {
245
- outputDir: outputDir2,
246
- skipBuild: skipBuild2 || ["1", "true", "yes"].includes(String(process.env.SKIP_NEXT_APP_BUILD))
234
+ paths: {
235
+ nextApp: appDir,
236
+ builderOutput: outputDir2,
237
+ dotNext,
238
+ standaloneApp,
239
+ standaloneAppDotNext,
240
+ standaloneAppServer,
241
+ internalPackage
242
+ },
243
+ cache: {
244
+ kvBindingName: UserConfig.cache.bindingName
245
+ },
246
+ internalPackageName: PACKAGE_NAME
247
247
  };
248
248
  }
249
- function assertDirArg(path12, argName, make) {
250
- let dirStats;
249
+ function containsDotNextDir(folder) {
251
250
  try {
252
- dirStats = statSync(path12);
251
+ return statSync(path.join(folder, ".next")).isDirectory();
253
252
  } catch {
254
- if (!make) {
255
- throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a valid path`);
253
+ return false;
254
+ }
255
+ }
256
+ function getNextjsApplicationPath(dotNextDir) {
257
+ const serverPath = findServerParentPath(dotNextDir);
258
+ if (!serverPath) {
259
+ throw new Error(`Unexpected Error: no \`.next/server\` folder could be found in \`${serverPath}\``);
260
+ }
261
+ return relative(path.join(dotNextDir, "standalone"), serverPath);
262
+ }
263
+ function findServerParentPath(parentPath) {
264
+ try {
265
+ if (statSync(path.join(parentPath, ".next", "server")).isDirectory()) {
266
+ return parentPath;
256
267
  }
257
- mkdirSync(path12);
258
- return;
268
+ } catch {
259
269
  }
260
- if (!dirStats.isDirectory()) {
261
- throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a directory`);
270
+ const folders = readdirSync(parentPath);
271
+ for (const folder of folders) {
272
+ const subFolder = path.join(parentPath, folder);
273
+ if (statSync(path.join(parentPath, folder)).isDirectory()) {
274
+ const dirServerPath = findServerParentPath(subFolder);
275
+ if (dirServerPath) {
276
+ return dirServerPath;
277
+ }
278
+ }
262
279
  }
263
280
  }
264
281
 
265
- // src/index.ts
266
- import { existsSync as existsSync4 } from "node:fs";
282
+ // ../../node_modules/.pnpm/package-manager-detector@0.2.0/node_modules/package-manager-detector/dist/constants.mjs
283
+ var AGENTS = [
284
+ "npm",
285
+ "yarn",
286
+ "yarn@berry",
287
+ "pnpm",
288
+ "pnpm@6",
289
+ "bun"
290
+ ];
291
+ var LOCKS = {
292
+ "bun.lockb": "bun",
293
+ "pnpm-lock.yaml": "pnpm",
294
+ "yarn.lock": "yarn",
295
+ "package-lock.json": "npm",
296
+ "npm-shrinkwrap.json": "npm"
297
+ };
267
298
 
268
- // src/build/build.ts
269
- import { rm } from "node:fs/promises";
299
+ // ../../node_modules/.pnpm/package-manager-detector@0.2.0/node_modules/package-manager-detector/dist/detect.mjs
300
+ import fs from "node:fs";
301
+ import fsPromises from "node:fs/promises";
302
+ import path2 from "node:path";
303
+ import process2 from "node:process";
304
+ async function detect({ cwd, onUnknown } = {}) {
305
+ for (const directory of lookup(cwd)) {
306
+ for (const lock of Object.keys(LOCKS)) {
307
+ if (await fileExists(path2.join(directory, lock))) {
308
+ const name = LOCKS[lock];
309
+ const result2 = await parsePackageJson(path2.join(directory, "package.json"), onUnknown);
310
+ if (result2)
311
+ return result2;
312
+ else
313
+ return { name, agent: name };
314
+ }
315
+ }
316
+ const result = await parsePackageJson(path2.join(directory, "package.json"), onUnknown);
317
+ if (result)
318
+ return result;
319
+ }
320
+ return null;
321
+ }
322
+ function* lookup(cwd = process2.cwd()) {
323
+ let directory = path2.resolve(cwd);
324
+ const { root } = path2.parse(directory);
325
+ while (directory && directory !== root) {
326
+ yield directory;
327
+ directory = path2.dirname(directory);
328
+ }
329
+ }
330
+ async function parsePackageJson(filepath, onUnknown) {
331
+ if (!filepath || !await fileExists(filepath))
332
+ return null;
333
+ try {
334
+ const pkg = JSON.parse(fs.readFileSync(filepath, "utf8"));
335
+ let agent;
336
+ if (typeof pkg.packageManager === "string") {
337
+ const [name, ver] = pkg.packageManager.replace(/^\^/, "").split("@");
338
+ let version = ver;
339
+ if (name === "yarn" && Number.parseInt(ver) > 1) {
340
+ agent = "yarn@berry";
341
+ version = "berry";
342
+ return { name, agent, version };
343
+ } else if (name === "pnpm" && Number.parseInt(ver) < 7) {
344
+ agent = "pnpm@6";
345
+ return { name, agent, version };
346
+ } else if (AGENTS.includes(name)) {
347
+ agent = name;
348
+ return { name, agent, version };
349
+ } else {
350
+ return onUnknown?.(pkg.packageManager) ?? null;
351
+ }
352
+ }
353
+ } catch {
354
+ }
355
+ return null;
356
+ }
357
+ async function fileExists(filePath) {
358
+ try {
359
+ const stats = await fsPromises.stat(filePath);
360
+ if (stats.isFile()) {
361
+ return true;
362
+ }
363
+ } catch {
364
+ }
365
+ return false;
366
+ }
270
367
 
271
- // src/build/build-next-app.ts
368
+ // src/cli/build/build-next-app.ts
272
369
  import { execSync } from "node:child_process";
273
- function buildNextjsApp(nextAppDir2) {
274
- runNextBuildCommand("pnpm", nextAppDir2);
370
+ async function buildNextjsApp(nextAppDir2) {
371
+ const pm = await detect();
372
+ if (!pm) {
373
+ throw new Error("Fatal Error: package manager detection failed, aborting");
374
+ }
375
+ runNextBuildCommand(pm.name, nextAppDir2);
275
376
  }
276
377
  function runNextBuildCommand(packager, nextAppDir2) {
277
- const command = ["bun", "npm"].includes(packager) ? `${packager} next build` : `${packager} next build`;
378
+ const command = `${packager === "npm" ? "npx" : packager} next build`;
278
379
  execSync(command, {
279
380
  stdio: "inherit",
280
381
  cwd: nextAppDir2,
@@ -287,28 +388,23 @@ function runNextBuildCommand(packager, nextAppDir2) {
287
388
  });
288
389
  }
289
390
 
290
- // src/build/build-worker.ts
391
+ // src/cli/build/build-worker.ts
291
392
  import { build } from "esbuild";
292
- import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
293
393
  import { cp, readFile, writeFile } from "node:fs/promises";
294
- import path9 from "node:path";
295
- import { fileURLToPath as fileURLToPath3 } from "node:url";
296
-
297
- // src/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
- }
394
+ import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
302
395
 
303
- // src/build/patches/investigated/copy-package.ts
396
+ // src/cli/build/patches/investigated/copy-package-cli-files.ts
304
397
  import { cpSync } from "node:fs";
305
- function copyPackage(srcDir, config) {
306
- console.log("# copyPackage");
307
- cpSync(srcDir, config.paths.internalPackage, { recursive: true });
398
+ import path3 from "node:path";
399
+ function copyPackageCliFiles(packageDistDir2, config) {
400
+ console.log("# copyPackageTemplateFiles");
401
+ const sourceDir = path3.join(packageDistDir2, "cli");
402
+ const destinationDir = path3.join(config.paths.internalPackage, "cli");
403
+ cpSync(sourceDir, destinationDir, { recursive: true });
308
404
  }
309
405
 
310
- // src/build/patches/to-investigate/patch-read-file.ts
311
- import { readFileSync } from "node:fs";
406
+ // src/cli/build/build-worker.ts
407
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
312
408
 
313
409
  // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/index.js
314
410
  var import_brace_expansion = __toESM(require_brace_expansion(), 1);
@@ -981,11 +1077,11 @@ var qmarksTestNoExtDot = ([$0]) => {
981
1077
  return (f) => f.length === len && f !== "." && f !== "..";
982
1078
  };
983
1079
  var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
984
- var path = {
1080
+ var path4 = {
985
1081
  win32: { sep: "\\" },
986
1082
  posix: { sep: "/" }
987
1083
  };
988
- var sep = defaultPlatform === "win32" ? path.win32.sep : path.posix.sep;
1084
+ var sep = defaultPlatform === "win32" ? path4.win32.sep : path4.posix.sep;
989
1085
  minimatch.sep = sep;
990
1086
  var GLOBSTAR = Symbol("globstar **");
991
1087
  minimatch.GLOBSTAR = GLOBSTAR;
@@ -3015,7 +3111,7 @@ var LRUCache = class _LRUCache {
3015
3111
  // ../../node_modules/.pnpm/path-scurry@2.0.0/node_modules/path-scurry/dist/esm/index.js
3016
3112
  import { posix, win32 } from "node:path";
3017
3113
  import { fileURLToPath } from "node:url";
3018
- import { lstatSync, readdir as readdirCB, readdirSync, readlinkSync, realpathSync as rps } from "fs";
3114
+ import { lstatSync, readdir as readdirCB, readdirSync as readdirSync2, readlinkSync, realpathSync as rps } from "fs";
3019
3115
  import * as actualFS from "node:fs";
3020
3116
  import { lstat, readdir, readlink, realpath } from "node:fs/promises";
3021
3117
 
@@ -3902,7 +3998,7 @@ var realpathSync = rps.native;
3902
3998
  var defaultFS = {
3903
3999
  lstatSync,
3904
4000
  readdir: readdirCB,
3905
- readdirSync,
4001
+ readdirSync: readdirSync2,
3906
4002
  readlinkSync,
3907
4003
  realpathSync,
3908
4004
  promises: {
@@ -4162,12 +4258,12 @@ var PathBase = class {
4162
4258
  /**
4163
4259
  * Get the Path object referenced by the string path, resolved from this Path
4164
4260
  */
4165
- resolve(path12) {
4166
- if (!path12) {
4261
+ resolve(path14) {
4262
+ if (!path14) {
4167
4263
  return this;
4168
4264
  }
4169
- const rootPath = this.getRootString(path12);
4170
- const dir = path12.substring(rootPath.length);
4265
+ const rootPath = this.getRootString(path14);
4266
+ const dir = path14.substring(rootPath.length);
4171
4267
  const dirParts = dir.split(this.splitSep);
4172
4268
  const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
4173
4269
  return result;
@@ -4919,8 +5015,8 @@ var PathWin32 = class _PathWin32 extends PathBase {
4919
5015
  /**
4920
5016
  * @internal
4921
5017
  */
4922
- getRootString(path12) {
4923
- return win32.parse(path12).root;
5018
+ getRootString(path14) {
5019
+ return win32.parse(path14).root;
4924
5020
  }
4925
5021
  /**
4926
5022
  * @internal
@@ -4966,8 +5062,8 @@ var PathPosix = class _PathPosix extends PathBase {
4966
5062
  /**
4967
5063
  * @internal
4968
5064
  */
4969
- getRootString(path12) {
4970
- return path12.startsWith("/") ? "/" : "";
5065
+ getRootString(path14) {
5066
+ return path14.startsWith("/") ? "/" : "";
4971
5067
  }
4972
5068
  /**
4973
5069
  * @internal
@@ -5016,8 +5112,8 @@ var PathScurryBase = class {
5016
5112
  *
5017
5113
  * @internal
5018
5114
  */
5019
- constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs2 = defaultFS } = {}) {
5020
- this.#fs = fsFromOption(fs2);
5115
+ constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs3 = defaultFS } = {}) {
5116
+ this.#fs = fsFromOption(fs3);
5021
5117
  if (cwd instanceof URL || cwd.startsWith("file://")) {
5022
5118
  cwd = fileURLToPath(cwd);
5023
5119
  }
@@ -5056,11 +5152,11 @@ var PathScurryBase = class {
5056
5152
  /**
5057
5153
  * Get the depth of a provided path, string, or the cwd
5058
5154
  */
5059
- depth(path12 = this.cwd) {
5060
- if (typeof path12 === "string") {
5061
- path12 = this.cwd.resolve(path12);
5155
+ depth(path14 = this.cwd) {
5156
+ if (typeof path14 === "string") {
5157
+ path14 = this.cwd.resolve(path14);
5062
5158
  }
5063
- return path12.depth();
5159
+ return path14.depth();
5064
5160
  }
5065
5161
  /**
5066
5162
  * Return the cache of child entries. Exposed so subclasses can create
@@ -5439,7 +5535,7 @@ var PathScurryBase = class {
5439
5535
  const dirs = /* @__PURE__ */ new Set();
5440
5536
  const queue = [entry];
5441
5537
  let processing = 0;
5442
- const process2 = () => {
5538
+ const process3 = () => {
5443
5539
  let paused = false;
5444
5540
  while (!paused) {
5445
5541
  const dir = queue.shift();
@@ -5480,9 +5576,9 @@ var PathScurryBase = class {
5480
5576
  }
5481
5577
  }
5482
5578
  if (paused && !results.flowing) {
5483
- results.once("drain", process2);
5579
+ results.once("drain", process3);
5484
5580
  } else if (!sync2) {
5485
- process2();
5581
+ process3();
5486
5582
  }
5487
5583
  };
5488
5584
  let sync2 = true;
@@ -5490,7 +5586,7 @@ var PathScurryBase = class {
5490
5586
  sync2 = false;
5491
5587
  }
5492
5588
  };
5493
- process2();
5589
+ process3();
5494
5590
  return results;
5495
5591
  }
5496
5592
  streamSync(entry = this.cwd, opts = {}) {
@@ -5508,7 +5604,7 @@ var PathScurryBase = class {
5508
5604
  }
5509
5605
  const queue = [entry];
5510
5606
  let processing = 0;
5511
- const process2 = () => {
5607
+ const process3 = () => {
5512
5608
  let paused = false;
5513
5609
  while (!paused) {
5514
5610
  const dir = queue.shift();
@@ -5542,14 +5638,14 @@ var PathScurryBase = class {
5542
5638
  }
5543
5639
  }
5544
5640
  if (paused && !results.flowing)
5545
- results.once("drain", process2);
5641
+ results.once("drain", process3);
5546
5642
  };
5547
- process2();
5643
+ process3();
5548
5644
  return results;
5549
5645
  }
5550
- chdir(path12 = this.cwd) {
5646
+ chdir(path14 = this.cwd) {
5551
5647
  const oldCwd = this.cwd;
5552
- this.cwd = typeof path12 === "string" ? this.cwd.resolve(path12) : path12;
5648
+ this.cwd = typeof path14 === "string" ? this.cwd.resolve(path14) : path14;
5553
5649
  this.cwd[setAsCwd](oldCwd);
5554
5650
  }
5555
5651
  };
@@ -5575,8 +5671,8 @@ var PathScurryWin32 = class extends PathScurryBase {
5575
5671
  /**
5576
5672
  * @internal
5577
5673
  */
5578
- newRoot(fs2) {
5579
- return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs2 });
5674
+ newRoot(fs3) {
5675
+ return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs3 });
5580
5676
  }
5581
5677
  /**
5582
5678
  * Return true if the provided path string is an absolute path
@@ -5604,8 +5700,8 @@ var PathScurryPosix = class extends PathScurryBase {
5604
5700
  /**
5605
5701
  * @internal
5606
5702
  */
5607
- newRoot(fs2) {
5608
- return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs2 });
5703
+ newRoot(fs3) {
5704
+ return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs3 });
5609
5705
  }
5610
5706
  /**
5611
5707
  * Return true if the provided path string is an absolute path
@@ -5905,8 +6001,8 @@ var MatchRecord = class {
5905
6001
  }
5906
6002
  // match, absolute, ifdir
5907
6003
  entries() {
5908
- return [...this.store.entries()].map(([path12, n]) => [
5909
- path12,
6004
+ return [...this.store.entries()].map(([path14, n]) => [
6005
+ path14,
5910
6006
  !!(n & 2),
5911
6007
  !!(n & 1)
5912
6008
  ]);
@@ -6111,9 +6207,9 @@ var GlobUtil = class {
6111
6207
  signal;
6112
6208
  maxDepth;
6113
6209
  includeChildMatches;
6114
- constructor(patterns, path12, opts) {
6210
+ constructor(patterns, path14, opts) {
6115
6211
  this.patterns = patterns;
6116
- this.path = path12;
6212
+ this.path = path14;
6117
6213
  this.opts = opts;
6118
6214
  this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/";
6119
6215
  this.includeChildMatches = opts.includeChildMatches !== false;
@@ -6132,11 +6228,11 @@ var GlobUtil = class {
6132
6228
  });
6133
6229
  }
6134
6230
  }
6135
- #ignored(path12) {
6136
- return this.seen.has(path12) || !!this.#ignore?.ignored?.(path12);
6231
+ #ignored(path14) {
6232
+ return this.seen.has(path14) || !!this.#ignore?.ignored?.(path14);
6137
6233
  }
6138
- #childrenIgnored(path12) {
6139
- return !!this.#ignore?.childrenIgnored?.(path12);
6234
+ #childrenIgnored(path14) {
6235
+ return !!this.#ignore?.childrenIgnored?.(path14);
6140
6236
  }
6141
6237
  // backpressure mechanism
6142
6238
  pause() {
@@ -6351,8 +6447,8 @@ var GlobUtil = class {
6351
6447
  };
6352
6448
  var GlobWalker = class extends GlobUtil {
6353
6449
  matches = /* @__PURE__ */ new Set();
6354
- constructor(patterns, path12, opts) {
6355
- super(patterns, path12, opts);
6450
+ constructor(patterns, path14, opts) {
6451
+ super(patterns, path14, opts);
6356
6452
  }
6357
6453
  matchEmit(e) {
6358
6454
  this.matches.add(e);
@@ -6389,8 +6485,8 @@ var GlobWalker = class extends GlobUtil {
6389
6485
  };
6390
6486
  var GlobStream = class extends GlobUtil {
6391
6487
  results;
6392
- constructor(patterns, path12, opts) {
6393
- super(patterns, path12, opts);
6488
+ constructor(patterns, path14, opts) {
6489
+ super(patterns, path14, opts);
6394
6490
  this.results = new Minipass({
6395
6491
  signal: this.signal,
6396
6492
  objectMode: true
@@ -6683,67 +6779,44 @@ var glob = Object.assign(glob_, {
6683
6779
  });
6684
6780
  glob.glob = glob;
6685
6781
 
6686
- // src/build/patches/to-investigate/patch-read-file.ts
6687
- import path2 from "node:path";
6688
- function patchReadFile(code, config) {
6689
- console.log("# patchReadFile");
6690
- code = code.replace(
6691
- "getBuildId() {",
6692
- `getBuildId() {
6693
- return ${JSON.stringify(readFileSync(path2.join(config.paths.standaloneAppDotNext, "BUILD_ID"), "utf-8"))};
6694
- `
6695
- );
6696
- const manifestJsons = globSync(path2.join(config.paths.standaloneAppDotNext, "**", "*-manifest.json")).map(
6697
- (file) => file.replace(config.paths.standaloneApp + "/", "")
6698
- );
6699
- code = code.replace(
6700
- /function loadManifest\((.+?), .+?\) {/,
6782
+ // src/cli/build/patches/to-investigate/inline-eval-manifest.ts
6783
+ import path5 from "node:path";
6784
+ function inlineEvalManifest(code, config) {
6785
+ console.log("# inlineEvalManifest");
6786
+ const manifestJss = globSync(
6787
+ path5.join(config.paths.standaloneAppDotNext, "**", "*_client-reference-manifest.js")
6788
+ ).map((file) => file.replace(`${config.paths.standaloneApp}/`, ""));
6789
+ return code.replace(
6790
+ /function evalManifest\((.+?), .+?\) {/,
6701
6791
  `$&
6702
- ${manifestJsons.map(
6703
- (manifestJson) => `
6704
- if ($1.endsWith("${manifestJson}")) {
6705
- return ${readFileSync(path2.join(config.paths.standaloneApp, manifestJson), "utf-8")};
6706
- }
6707
- `
6792
+ ${manifestJss.map(
6793
+ (manifestJs) => `
6794
+ if ($1.endsWith("${manifestJs}")) {
6795
+ require("${path5.join(config.paths.standaloneApp, manifestJs)}");
6796
+ return {
6797
+ __RSC_MANIFEST: {
6798
+ "${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}": globalThis.__RSC_MANIFEST["${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}"],
6799
+ },
6800
+ };
6801
+ }
6802
+ `
6708
6803
  ).join("\n")}
6709
- throw new Error("Unknown loadManifest: " + $1);
6710
- `
6711
- );
6712
- return code;
6713
- }
6714
-
6715
- // src/build/patches/to-investigate/patch-find-dir.ts
6716
- import path3 from "node:path";
6717
- import { existsSync } from "node:fs";
6718
- function patchFindDir(code, config) {
6719
- console.log("# patchFindDir");
6720
- return code.replace(
6721
- "function findDir(dir, name) {",
6722
- `function findDir(dir, name) {
6723
- if (dir.endsWith(".next/server")) {
6724
- if (name === "app") {
6725
- return ${existsSync(`${path3.join(config.paths.standaloneAppServer, "app")}`)};
6726
- }
6727
- if (name === "pages") {
6728
- return ${existsSync(`${path3.join(config.paths.standaloneAppServer, "pages")}`)};
6729
- }
6730
- }
6731
- throw new Error("Unknown findDir call: " + dir + " " + name);
6804
+ throw new Error("Unknown evalManifest: " + $1);
6732
6805
  `
6733
6806
  );
6734
6807
  }
6735
6808
 
6736
- // src/build/patches/to-investigate/inline-next-require.ts
6737
- import { readFileSync as readFileSync2, existsSync as existsSync2 } from "node:fs";
6738
- import path4 from "node:path";
6809
+ // src/cli/build/patches/to-investigate/inline-next-require.ts
6810
+ import { existsSync, readFileSync } from "node:fs";
6811
+ import path6 from "node:path";
6739
6812
  function inlineNextRequire(code, config) {
6740
6813
  console.log("# inlineNextRequire");
6741
- const pagesManifestFile = path4.join(config.paths.standaloneAppServer, "pages-manifest.json");
6742
- const appPathsManifestFile = path4.join(config.paths.standaloneAppServer, "app-paths-manifest.json");
6743
- const pagesManifestFiles = existsSync2(pagesManifestFile) ? Object.values(JSON.parse(readFileSync2(pagesManifestFile, "utf-8"))).map(
6814
+ const pagesManifestFile = path6.join(config.paths.standaloneAppServer, "pages-manifest.json");
6815
+ const appPathsManifestFile = path6.join(config.paths.standaloneAppServer, "app-paths-manifest.json");
6816
+ const pagesManifestFiles = existsSync(pagesManifestFile) ? Object.values(JSON.parse(readFileSync(pagesManifestFile, "utf-8"))).map(
6744
6817
  (file) => ".next/server/" + file
6745
6818
  ) : [];
6746
- const appPathsManifestFiles = existsSync2(appPathsManifestFile) ? Object.values(JSON.parse(readFileSync2(appPathsManifestFile, "utf-8"))).map(
6819
+ const appPathsManifestFiles = existsSync(appPathsManifestFile) ? Object.values(JSON.parse(readFileSync(appPathsManifestFile, "utf-8"))).map(
6747
6820
  (file) => ".next/server/" + file
6748
6821
  ) : [];
6749
6822
  const allManifestFiles = pagesManifestFiles.concat(appPathsManifestFiles);
@@ -6755,14 +6828,14 @@ function inlineNextRequire(code, config) {
6755
6828
  ${htmlPages.map(
6756
6829
  (htmlPage) => `
6757
6830
  if (pagePath.endsWith("${htmlPage}")) {
6758
- return ${JSON.stringify(readFileSync2(path4.join(config.paths.standaloneApp, htmlPage), "utf-8"))};
6831
+ return ${JSON.stringify(readFileSync(path6.join(config.paths.standaloneApp, htmlPage), "utf-8"))};
6759
6832
  }
6760
6833
  `
6761
6834
  ).join("\n")}
6762
6835
  ${pageModules.map(
6763
6836
  (module) => `
6764
6837
  if (pagePath.endsWith("${module}")) {
6765
- return require("${path4.join(config.paths.standaloneApp, module)}");
6838
+ return require("${path6.join(config.paths.standaloneApp, module)}");
6766
6839
  }
6767
6840
  `
6768
6841
  ).join("\n")}
@@ -6771,39 +6844,87 @@ function inlineNextRequire(code, config) {
6771
6844
  );
6772
6845
  }
6773
6846
 
6774
- // src/build/patches/to-investigate/inline-eval-manifest.ts
6775
- import path5 from "node:path";
6776
- function inlineEvalManifest(code, config) {
6777
- console.log("# inlineEvalManifest");
6778
- const manifestJss = globSync(
6779
- path5.join(config.paths.standaloneAppDotNext, "**", "*_client-reference-manifest.js")
6780
- ).map((file) => file.replace(`${config.paths.standaloneApp}/`, ""));
6847
+ // src/cli/build/patches/investigated/patch-cache.ts
6848
+ import path7 from "node:path";
6849
+ function patchCache(code, config) {
6850
+ console.log("# patchCached");
6851
+ const cacheHandler = path7.join(config.paths.internalPackage, "cli", "cache-handler.mjs");
6852
+ const patchedCode = code.replace(
6853
+ "const { cacheHandler } = this.nextConfig;",
6854
+ `const cacheHandler = null;
6855
+ CacheHandler = (await import('${cacheHandler}')).default;
6856
+ CacheHandler.maybeKVNamespace = process.env["${config.cache.kvBindingName}"];
6857
+ `
6858
+ );
6859
+ if (patchedCode === code) {
6860
+ throw new Error("Cache patch not applied");
6861
+ }
6862
+ return patchedCode;
6863
+ }
6864
+
6865
+ // src/cli/build/patches/to-investigate/patch-find-dir.ts
6866
+ import { existsSync as existsSync2 } from "node:fs";
6867
+ import path8 from "node:path";
6868
+ function patchFindDir(code, config) {
6869
+ console.log("# patchFindDir");
6781
6870
  return code.replace(
6782
- /function evalManifest\((.+?), .+?\) {/,
6871
+ "function findDir(dir, name) {",
6872
+ `function findDir(dir, name) {
6873
+ if (dir.endsWith(".next/server")) {
6874
+ if (name === "app") {
6875
+ return ${existsSync2(`${path8.join(config.paths.standaloneAppServer, "app")}`)};
6876
+ }
6877
+ if (name === "pages") {
6878
+ return ${existsSync2(`${path8.join(config.paths.standaloneAppServer, "pages")}`)};
6879
+ }
6880
+ }
6881
+ throw new Error("Unknown findDir call: " + dir + " " + name);
6882
+ `
6883
+ );
6884
+ }
6885
+
6886
+ // src/cli/build/patches/to-investigate/patch-read-file.ts
6887
+ import path9 from "node:path";
6888
+ import { readFileSync as readFileSync2 } from "node:fs";
6889
+ function patchReadFile(code, config) {
6890
+ console.log("# patchReadFile");
6891
+ code = code.replace(
6892
+ "getBuildId() {",
6893
+ `getBuildId() {
6894
+ return ${JSON.stringify(readFileSync2(path9.join(config.paths.standaloneAppDotNext, "BUILD_ID"), "utf-8"))};
6895
+ `
6896
+ );
6897
+ const manifestJsons = globSync(path9.join(config.paths.standaloneAppDotNext, "**", "*-manifest.json")).map(
6898
+ (file) => file.replace(config.paths.standaloneApp + "/", "")
6899
+ );
6900
+ code = code.replace(
6901
+ /function loadManifest\((.+?), .+?\) {/,
6783
6902
  `$&
6784
- ${manifestJss.map(
6785
- (manifestJs) => `
6786
- if ($1.endsWith("${manifestJs}")) {
6787
- require("${path5.join(config.paths.standaloneApp, manifestJs)}");
6788
- return {
6789
- __RSC_MANIFEST: {
6790
- "${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}": globalThis.__RSC_MANIFEST["${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}"],
6791
- },
6792
- };
6793
- }
6794
- `
6903
+ ${manifestJsons.map(
6904
+ (manifestJson) => `
6905
+ if ($1.endsWith("${manifestJson}")) {
6906
+ return ${readFileSync2(path9.join(config.paths.standaloneApp, manifestJson), "utf-8")};
6907
+ }
6908
+ `
6795
6909
  ).join("\n")}
6796
- throw new Error("Unknown evalManifest: " + $1);
6797
- `
6910
+ throw new Error("Unknown loadManifest: " + $1);
6911
+ `
6798
6912
  );
6913
+ return code;
6799
6914
  }
6800
6915
 
6801
- // src/build/patches/to-investigate/wrangler-deps.ts
6802
- import path6 from "node:path";
6803
- import fs, { writeFileSync } from "node:fs";
6916
+ // src/cli/build/patches/investigated/patch-require.ts
6917
+ function patchRequire(code) {
6918
+ console.log("# patchRequire");
6919
+ return code.replace(/__require\d?\(/g, "require(").replace(/__require\d?\./g, "require.");
6920
+ }
6921
+
6922
+ // src/cli/build/patches/to-investigate/wrangler-deps.ts
6923
+ import fs2, { writeFileSync } from "node:fs";
6924
+ import path10 from "node:path";
6804
6925
  function patchWranglerDeps(config) {
6805
6926
  console.log("# patchWranglerDeps");
6806
- const pagesRuntimeFile = path6.join(
6927
+ const pagesRuntimeFile = path10.join(
6807
6928
  config.paths.standaloneApp,
6808
6929
  "node_modules",
6809
6930
  "next",
@@ -6812,9 +6933,9 @@ function patchWranglerDeps(config) {
6812
6933
  "next-server",
6813
6934
  "pages.runtime.prod.js"
6814
6935
  );
6815
- const patchedPagesRuntime = fs.readFileSync(pagesRuntimeFile, "utf-8").replace(`e.exports=require("critters")`, `e.exports={}`);
6816
- fs.writeFileSync(pagesRuntimeFile, patchedPagesRuntime);
6817
- const tracerFile = path6.join(
6936
+ const patchedPagesRuntime = fs2.readFileSync(pagesRuntimeFile, "utf-8").replace(`e.exports=require("critters")`, `e.exports={}`);
6937
+ fs2.writeFileSync(pagesRuntimeFile, patchedPagesRuntime);
6938
+ const tracerFile = path10.join(
6818
6939
  config.paths.standaloneApp,
6819
6940
  "node_modules",
6820
6941
  "next",
@@ -6824,15 +6945,17 @@ function patchWranglerDeps(config) {
6824
6945
  "trace",
6825
6946
  "tracer.js"
6826
6947
  );
6827
- const pacthedTracer = fs.readFileSync(tracerFile, "utf-8").replaceAll(/\w+\s*=\s*require\([^/]*opentelemetry.*\)/g, `throw new Error("@opentelemetry/api")`);
6948
+ const pacthedTracer = fs2.readFileSync(tracerFile, "utf-8").replaceAll(/\w+\s*=\s*require\([^/]*opentelemetry.*\)/g, `throw new Error("@opentelemetry/api")`);
6828
6949
  writeFileSync(tracerFile, pacthedTracer);
6829
6950
  }
6830
6951
 
6831
- // src/build/patches/investigated/update-webpack-chunks-file/index.ts
6832
- import { readdirSync as readdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
6833
- import path7 from "node:path";
6952
+ // src/cli/build/build-worker.ts
6953
+ import path12 from "node:path";
6834
6954
 
6835
- // src/build/patches/investigated/update-webpack-chunks-file/get-chunk-installation-identifiers.ts
6955
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/index.ts
6956
+ import { readFileSync as readFileSync3, readdirSync as readdirSync3, writeFileSync as writeFileSync2 } from "node:fs";
6957
+
6958
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/get-chunk-installation-identifiers.ts
6836
6959
  import * as ts from "ts-morph";
6837
6960
  async function getChunkInstallationIdentifiers(sourceFile) {
6838
6961
  const installChunkDeclaration = getInstallChunkDeclaration(sourceFile);
@@ -6878,7 +7001,7 @@ function getInstalledChunksDeclaration(sourceFile, installChunkDeclaration) {
6878
7001
  return installedChunksDeclaration;
6879
7002
  }
6880
7003
 
6881
- // src/build/patches/investigated/update-webpack-chunks-file/get-file-content-with-updated-webpack-f-require-code.ts
7004
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/get-file-content-with-updated-webpack-f-require-code.ts
6882
7005
  import * as ts2 from "ts-morph";
6883
7006
  async function getFileContentWithUpdatedWebpackFRequireCode(sourceFile, { installedChunks, installChunk }, chunks) {
6884
7007
  const webpackFRequireFunction = sourceFile.getDescendantsOfKind(ts2.SyntaxKind.ArrowFunction).find((arrowFunction) => {
@@ -6922,7 +7045,7 @@ if(${chunkId} === ${chunk}) return ${installChunk}(require("./chunks/${chunk}.js
6922
7045
  return sourceFile.print();
6923
7046
  }
6924
7047
 
6925
- // src/build/utils/ts-parse-file.ts
7048
+ // src/cli/build/utils/ts-parse-file.ts
6926
7049
  import * as ts3 from "ts-morph";
6927
7050
  function tsParseFile(fileContent) {
6928
7051
  const project = new ts3.Project();
@@ -6930,7 +7053,7 @@ function tsParseFile(fileContent) {
6930
7053
  return sourceFile;
6931
7054
  }
6932
7055
 
6933
- // src/build/patches/investigated/update-webpack-chunks-file/get-updated-webpack-chunks-file-content.ts
7056
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/get-updated-webpack-chunks-file-content.ts
6934
7057
  async function getUpdatedWebpackChunksFileContent(fileContent, chunks) {
6935
7058
  const tsSourceFile = tsParseFile(fileContent);
6936
7059
  const chunkInstallationIdentifiers = await getChunkInstallationIdentifiers(tsSourceFile);
@@ -6942,12 +7065,13 @@ async function getUpdatedWebpackChunksFileContent(fileContent, chunks) {
6942
7065
  return updatedFileContent;
6943
7066
  }
6944
7067
 
6945
- // src/build/patches/investigated/update-webpack-chunks-file/index.ts
7068
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/index.ts
7069
+ import path11 from "node:path";
6946
7070
  async function updateWebpackChunksFile(config) {
6947
7071
  console.log("# updateWebpackChunksFile");
6948
- const webpackRuntimeFile = path7.join(config.paths.standaloneAppServer, "webpack-runtime.js");
7072
+ const webpackRuntimeFile = path11.join(config.paths.standaloneAppServer, "webpack-runtime.js");
6949
7073
  const fileContent = readFileSync3(webpackRuntimeFile, "utf-8");
6950
- const chunks = readdirSync2(path7.join(config.paths.standaloneAppServer, "chunks")).filter((chunk) => /^\d+\.js$/.test(chunk)).map((chunk) => {
7074
+ const chunks = readdirSync3(path11.join(config.paths.standaloneAppServer, "chunks")).filter((chunk) => /^\d+\.js$/.test(chunk)).map((chunk) => {
6951
7075
  console.log(` - chunk ${chunk}`);
6952
7076
  return chunk.replace(/\.js$/, "");
6953
7077
  });
@@ -6955,47 +7079,29 @@ async function updateWebpackChunksFile(config) {
6955
7079
  writeFileSync2(webpackRuntimeFile, updatedFileContent);
6956
7080
  }
6957
7081
 
6958
- // src/build/patches/investigated/patch-cache.ts
6959
- import path8 from "node:path";
6960
- function patchCache(code, config) {
6961
- console.log("# patchCached");
6962
- const cacheHandler = path8.join(config.paths.internalPackage, "cache-handler.mjs");
6963
- const patchedCode = code.replace(
6964
- "const { cacheHandler } = this.nextConfig;",
6965
- `const cacheHandler = null;
6966
- CacheHandler = (await import('${cacheHandler}')).default;
6967
- CacheHandler.maybeKVNamespace = process.env["${config.cache.kvBindingName}"];
6968
- `
6969
- );
6970
- if (patchedCode === code) {
6971
- throw new Error("Cache patch not applied");
6972
- }
6973
- return patchedCode;
6974
- }
6975
-
6976
- // src/build/build-worker.ts
6977
- var packageDir = path9.dirname(fileURLToPath3(import.meta.url));
7082
+ // src/cli/build/build-worker.ts
7083
+ var packageDistDir = path12.join(path12.dirname(fileURLToPath3(import.meta.url)), "..");
6978
7084
  async function buildWorker(config) {
6979
7085
  console.log(`\x1B[35m\u2699\uFE0F Copying files...
6980
7086
  \x1B[0m`);
6981
7087
  await cp(
6982
- path9.join(config.paths.dotNext, "static"),
6983
- path9.join(config.paths.builderOutput, "assets", "_next", "static"),
7088
+ path12.join(config.paths.dotNext, "static"),
7089
+ path12.join(config.paths.builderOutput, "assets", "_next", "static"),
6984
7090
  {
6985
7091
  recursive: true
6986
7092
  }
6987
7093
  );
6988
- const publicDir = path9.join(config.paths.nextApp, "public");
7094
+ const publicDir = path12.join(config.paths.nextApp, "public");
6989
7095
  if (existsSync3(publicDir)) {
6990
- await cp(publicDir, path9.join(config.paths.builderOutput, "assets"), {
7096
+ await cp(publicDir, path12.join(config.paths.builderOutput, "assets"), {
6991
7097
  recursive: true
6992
7098
  });
6993
7099
  }
6994
- copyPackage(packageDir, config);
6995
- const templateDir = path9.join(config.paths.internalPackage, "templates");
6996
- const workerEntrypoint = path9.join(templateDir, "worker.ts");
6997
- const workerOutputFile = path9.join(config.paths.builderOutput, "index.mjs");
6998
- const nextConfigStr = readFileSync4(path9.join(config.paths.standaloneApp, "/server.js"), "utf8")?.match(
7100
+ copyPackageCliFiles(packageDistDir, config);
7101
+ const templateDir = path12.join(config.paths.internalPackage, "cli", "templates");
7102
+ const workerEntrypoint = path12.join(templateDir, "worker.ts");
7103
+ const workerOutputFile = path12.join(config.paths.builderOutput, "index.mjs");
7104
+ const nextConfigStr = readFileSync4(path12.join(config.paths.standaloneApp, "/server.js"), "utf8")?.match(
6999
7105
  /const nextConfig = ({.+?})\n/
7000
7106
  )?.[1] ?? {};
7001
7107
  console.log(`\x1B[35m\u2699\uFE0F Bundling the worker file...
@@ -7014,15 +7120,15 @@ async function buildWorker(config) {
7014
7120
  // Note: we apply an empty shim to next/dist/compiled/ws because it generates two `eval`s:
7015
7121
  // eval("require")("bufferutil");
7016
7122
  // eval("require")("utf-8-validate");
7017
- "next/dist/compiled/ws": path9.join(templateDir, "shims", "empty.ts"),
7123
+ "next/dist/compiled/ws": path12.join(templateDir, "shims", "empty.ts"),
7018
7124
  // Note: we apply an empty shim to next/dist/compiled/edge-runtime since (amongst others) it generated the following `eval`:
7019
7125
  // eval(getModuleCode)(module, module.exports, throwingRequire, params.context, ...Object.values(params.scopedContext));
7020
7126
  // which comes from https://github.com/vercel/edge-runtime/blob/6e96b55f/packages/primitives/src/primitives/load.js#L57-L63
7021
7127
  // QUESTION: Why did I encountered this but mhart didn't?
7022
- "next/dist/compiled/edge-runtime": path9.join(templateDir, "shims", "empty.ts"),
7128
+ "next/dist/compiled/edge-runtime": path12.join(templateDir, "shims", "empty.ts"),
7023
7129
  // `@next/env` is a library Next.js uses for loading dotenv files, for obvious reasons we need to stub it here
7024
7130
  // source: https://github.com/vercel/next.js/tree/0ac10d79720/packages/next-env
7025
- "@next/env": path9.join(templateDir, "shims", "env.ts")
7131
+ "@next/env": path12.join(templateDir, "shims", "env.ts")
7026
7132
  },
7027
7133
  define: {
7028
7134
  // config file used by Next.js, see: https://github.com/vercel/next.js/blob/68a7128/packages/next/src/build/utils.ts#L2137-L2139
@@ -7101,103 +7207,88 @@ function createFixRequiresESBuildPlugin(templateDir) {
7101
7207
  return {
7102
7208
  name: "replaceRelative",
7103
7209
  setup(build3) {
7104
- build3.onResolve({ filter: /^\.\/require-hook$/ }, (args) => ({
7105
- path: path9.join(templateDir, "shims", "empty.ts")
7210
+ build3.onResolve({ filter: /^\.\/require-hook$/ }, () => ({
7211
+ path: path12.join(templateDir, "shims", "empty.ts")
7106
7212
  }));
7107
- build3.onResolve({ filter: /\.\/lib\/node-fs-methods$/ }, (args) => ({
7108
- path: path9.join(templateDir, "shims", "empty.ts")
7213
+ build3.onResolve({ filter: /\.\/lib\/node-fs-methods$/ }, () => ({
7214
+ path: path12.join(templateDir, "shims", "empty.ts")
7109
7215
  }));
7110
7216
  }
7111
7217
  };
7112
7218
  }
7113
7219
 
7114
- // src/config.ts
7115
- import { readdirSync as readdirSync3, statSync as statSync2 } from "node:fs";
7116
- import path10, { relative } from "node:path";
7117
- var PACKAGE_NAME = "@opennextjs/cloudflare";
7118
- var UserConfig = {
7119
- cache: {
7120
- bindingName: "NEXT_CACHE_WORKERS_KV"
7121
- }
7122
- };
7123
- function getConfig(appDir, outputDir2) {
7124
- const dotNext = path10.join(outputDir2, ".next");
7125
- const appPath = getNextjsApplicationPath(dotNext).replace(/\/$/, "");
7126
- const standaloneApp = path10.join(dotNext, "standalone", appPath);
7127
- const standaloneAppDotNext = path10.join(standaloneApp, ".next");
7128
- const standaloneAppServer = path10.join(standaloneAppDotNext, "server");
7129
- const nodeModules = path10.join(standaloneApp, "node_modules");
7130
- const internalPackage = path10.join(nodeModules, ...PACKAGE_NAME.split("/"));
7131
- return {
7132
- paths: {
7133
- nextApp: appDir,
7134
- builderOutput: outputDir2,
7135
- dotNext,
7136
- standaloneApp,
7137
- standaloneAppDotNext,
7138
- standaloneAppServer,
7139
- internalPackage
7140
- },
7141
- cache: {
7142
- kvBindingName: UserConfig.cache.bindingName
7143
- },
7144
- internalPackageName: PACKAGE_NAME
7145
- };
7146
- }
7147
- function containsDotNextDir(folder) {
7148
- try {
7149
- return statSync2(path10.join(folder, ".next")).isDirectory();
7150
- } catch (e) {
7151
- return false;
7152
- }
7153
- }
7154
- function getNextjsApplicationPath(dotNextDir) {
7155
- const serverPath = findServerParentPath(dotNextDir);
7156
- if (!serverPath) {
7157
- throw new Error(`Unexpected Error: no \`.next/server\` folder could be found in \`${serverPath}\``);
7158
- }
7159
- return relative(path10.join(dotNextDir, "standalone"), serverPath);
7160
- }
7161
- function findServerParentPath(parentPath) {
7162
- try {
7163
- if (statSync2(path10.join(parentPath, ".next", "server")).isDirectory()) {
7164
- return parentPath;
7165
- }
7166
- } catch {
7167
- }
7168
- const folders = readdirSync3(parentPath);
7169
- for (const folder of folders) {
7170
- const subFolder = path10.join(parentPath, folder);
7171
- if (statSync2(path10.join(parentPath, folder)).isDirectory()) {
7172
- const dirServerPath = findServerParentPath(subFolder);
7173
- if (dirServerPath) {
7174
- return dirServerPath;
7175
- }
7176
- }
7177
- }
7178
- }
7179
-
7180
- // src/build/build.ts
7181
- import { cpSync as cpSync3 } from "node:fs";
7182
- import path11 from "node:path";
7220
+ // src/cli/build/index.ts
7221
+ import { cpSync as cpSync2 } from "node:fs";
7222
+ import path13 from "node:path";
7223
+ import { rm } from "node:fs/promises";
7183
7224
  async function build2(appDir, opts) {
7184
7225
  if (!opts.skipBuild) {
7185
- buildNextjsApp(appDir);
7226
+ await buildNextjsApp(appDir);
7186
7227
  }
7187
7228
  if (!containsDotNextDir(appDir)) {
7188
7229
  throw new Error(`.next folder not found in ${appDir}`);
7189
7230
  }
7190
- const outputDir2 = path11.resolve(opts.outputDir ?? appDir, ".worker-next");
7231
+ const outputDir2 = path13.resolve(opts.outputDir ?? appDir, ".worker-next");
7191
7232
  await cleanDirectory(outputDir2);
7192
- cpSync3(path11.join(appDir, ".next"), path11.join(outputDir2, ".next"), { recursive: true });
7233
+ cpSync2(path13.join(appDir, ".next"), path13.join(outputDir2, ".next"), { recursive: true });
7193
7234
  const config = getConfig(appDir, outputDir2);
7194
7235
  await buildWorker(config);
7195
7236
  }
7196
- async function cleanDirectory(path12) {
7197
- return await rm(path12, { recursive: true, force: true });
7237
+ async function cleanDirectory(path14) {
7238
+ return await rm(path14, { recursive: true, force: true });
7198
7239
  }
7199
7240
 
7200
- // src/index.ts
7241
+ // src/cli/index.ts
7242
+ import { existsSync as existsSync4 } from "node:fs";
7243
+
7244
+ // src/cli/args.ts
7245
+ import { mkdirSync, statSync as statSync2 } from "node:fs";
7246
+ import { parseArgs } from "node:util";
7247
+ import { resolve } from "node:path";
7248
+ function getArgs() {
7249
+ const {
7250
+ values: { skipBuild: skipBuild2, output }
7251
+ } = parseArgs({
7252
+ options: {
7253
+ skipBuild: {
7254
+ type: "boolean",
7255
+ short: "s",
7256
+ default: false
7257
+ },
7258
+ output: {
7259
+ type: "string",
7260
+ short: "o"
7261
+ }
7262
+ },
7263
+ allowPositionals: false
7264
+ });
7265
+ const outputDir2 = output ? resolve(output) : void 0;
7266
+ if (outputDir2) {
7267
+ assertDirArg(outputDir2, "output", true);
7268
+ }
7269
+ return {
7270
+ outputDir: outputDir2,
7271
+ skipBuild: skipBuild2 || ["1", "true", "yes"].includes(String(process.env.SKIP_NEXT_APP_BUILD))
7272
+ };
7273
+ }
7274
+ function assertDirArg(path14, argName, make) {
7275
+ let dirStats;
7276
+ try {
7277
+ dirStats = statSync2(path14);
7278
+ } catch {
7279
+ if (!make) {
7280
+ throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a valid path`);
7281
+ }
7282
+ mkdirSync(path14);
7283
+ return;
7284
+ }
7285
+ if (!dirStats.isDirectory()) {
7286
+ throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a directory`);
7287
+ }
7288
+ }
7289
+
7290
+ // src/cli/index.ts
7291
+ import { resolve as resolve2 } from "node:path";
7201
7292
  var nextAppDir = resolve2(".");
7202
7293
  console.log(`Building the Next.js app in the current folder (${nextAppDir})`);
7203
7294
  if (!["js", "cjs", "mjs", "ts"].some((ext2) => existsSync4(`./next.config.${ext2}`))) {