@opennextjs/cloudflare 0.0.0-9758666 → 0.0.0-af15fd1

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.
@@ -0,0 +1,14 @@
1
+ // src/api/get-cloudflare-context.ts
2
+ import "server-only";
3
+ var cloudflareContextSymbol = Symbol.for("__cloudflare-context__");
4
+ async function getCloudflareContext() {
5
+ const cloudflareContext = globalThis[cloudflareContextSymbol];
6
+ if (!cloudflareContext) {
7
+ throw new Error("Cloudflare context is not defined!");
8
+ }
9
+ return cloudflareContext;
10
+ }
11
+
12
+ export {
13
+ getCloudflareContext
14
+ };
@@ -0,0 +1,28 @@
1
+ declare global {
2
+ interface CloudflareEnv {
3
+ }
4
+ }
5
+ type CloudflareContext<CfProperties extends Record<string, unknown> = IncomingRequestCfProperties, Context = ExecutionContext> = {
6
+ /**
7
+ * the worker's [bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/)
8
+ */
9
+ env: CloudflareEnv;
10
+ /**
11
+ * the request's [cf properties](https://developers.cloudflare.com/workers/runtime-apis/request/#the-cf-property-requestinitcfproperties)
12
+ */
13
+ cf: CfProperties;
14
+ /**
15
+ * the current [execution context](https://developers.cloudflare.com/workers/runtime-apis/context)
16
+ */
17
+ ctx: Context;
18
+ };
19
+ /**
20
+ * Utility to get the current Cloudflare context
21
+ *
22
+ * Throws an error if the context could not be retrieved
23
+ *
24
+ * @returns the cloudflare context
25
+ */
26
+ declare function getCloudflareContext<CfProperties extends Record<string, unknown> = IncomingRequestCfProperties, Context = ExecutionContext>(): Promise<CloudflareContext<CfProperties, Context>>;
27
+
28
+ export { type CloudflareContext, getCloudflareContext };
@@ -0,0 +1,6 @@
1
+ import {
2
+ getCloudflareContext
3
+ } from "./chunk-LA734VUG.mjs";
4
+ export {
5
+ getCloudflareContext
6
+ };
@@ -0,0 +1 @@
1
+ export { CloudflareContext, getCloudflareContext } from './get-cloudflare-context.mjs';
@@ -0,0 +1,6 @@
1
+ import {
2
+ getCloudflareContext
3
+ } from "./chunk-LA734VUG.mjs";
4
+ export {
5
+ getCloudflareContext
6
+ };
@@ -1,6 +1,6 @@
1
1
  import "./chunk-UJCSKKID.mjs";
2
2
 
3
- // src/cache-handler.ts
3
+ // src/cli/cache-handler.ts
4
4
  var CfWorkersKvCacheHandler = class _CfWorkersKvCacheHandler {
5
5
  constructor(ctx) {
6
6
  this.ctx = ctx;
@@ -213,10 +213,10 @@ var require_brace_expansion = __commonJS({
213
213
  }
214
214
  });
215
215
 
216
- // src/index.ts
216
+ // src/cli/index.ts
217
217
  import { resolve as resolve2 } from "node:path";
218
218
 
219
- // src/args.ts
219
+ // src/cli/args.ts
220
220
  import { mkdirSync, statSync } from "node:fs";
221
221
  import { parseArgs } from "node:util";
222
222
  import { resolve } from "node:path";
@@ -246,15 +246,15 @@ function getArgs() {
246
246
  skipBuild: skipBuild2 || ["1", "true", "yes"].includes(String(process.env.SKIP_NEXT_APP_BUILD))
247
247
  };
248
248
  }
249
- function assertDirArg(path12, argName, make) {
249
+ function assertDirArg(path13, argName, make) {
250
250
  let dirStats;
251
251
  try {
252
- dirStats = statSync(path12);
252
+ dirStats = statSync(path13);
253
253
  } catch {
254
254
  if (!make) {
255
255
  throw new Error(`Error: the provided${argName ? ` "${argName}"` : ""} input is not a valid path`);
256
256
  }
257
- mkdirSync(path12);
257
+ mkdirSync(path13);
258
258
  return;
259
259
  }
260
260
  if (!dirStats.isDirectory()) {
@@ -262,13 +262,13 @@ function assertDirArg(path12, argName, make) {
262
262
  }
263
263
  }
264
264
 
265
- // src/index.ts
265
+ // src/cli/index.ts
266
266
  import { existsSync as existsSync4 } from "node:fs";
267
267
 
268
- // src/build/build.ts
268
+ // src/cli/build/index.ts
269
269
  import { rm } from "node:fs/promises";
270
270
 
271
- // src/build/build-next-app.ts
271
+ // src/cli/build/build-next-app.ts
272
272
  import { execSync } from "node:child_process";
273
273
  function buildNextjsApp(nextAppDir2) {
274
274
  runNextBuildCommand("pnpm", nextAppDir2);
@@ -287,27 +287,30 @@ function runNextBuildCommand(packager, nextAppDir2) {
287
287
  });
288
288
  }
289
289
 
290
- // src/build/build-worker.ts
290
+ // src/cli/build/build-worker.ts
291
291
  import { build } from "esbuild";
292
292
  import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
293
293
  import { cp, readFile, writeFile } from "node:fs/promises";
294
- import path9 from "node:path";
294
+ import path10 from "node:path";
295
295
  import { fileURLToPath as fileURLToPath3 } from "node:url";
296
296
 
297
- // src/build/patches/investigated/patch-require.ts
297
+ // src/cli/build/patches/investigated/patch-require.ts
298
298
  function patchRequire(code) {
299
299
  console.log("# patchRequire");
300
300
  return code.replace(/__require\d?\(/g, "require(").replace(/__require\d?\./g, "require.");
301
301
  }
302
302
 
303
- // src/build/patches/investigated/copy-package.ts
303
+ // src/cli/build/patches/investigated/copy-package-cli-files.ts
304
304
  import { cpSync } from "node:fs";
305
- function copyPackage(srcDir, config) {
306
- console.log("# copyPackage");
307
- cpSync(srcDir, config.paths.internalPackage, { recursive: true });
305
+ import path from "node:path";
306
+ function copyPackageCliFiles(packageDistDir2, config) {
307
+ console.log("# copyPackageTemplateFiles");
308
+ const sourceDir = path.join(packageDistDir2, "cli");
309
+ const destinationDir = path.join(config.paths.internalPackage, "cli");
310
+ cpSync(sourceDir, destinationDir, { recursive: true });
308
311
  }
309
312
 
310
- // src/build/patches/to-investigate/patch-read-file.ts
313
+ // src/cli/build/patches/to-investigate/patch-read-file.ts
311
314
  import { readFileSync } from "node:fs";
312
315
 
313
316
  // ../../node_modules/.pnpm/minimatch@10.0.1/node_modules/minimatch/dist/esm/index.js
@@ -981,11 +984,11 @@ var qmarksTestNoExtDot = ([$0]) => {
981
984
  return (f) => f.length === len && f !== "." && f !== "..";
982
985
  };
983
986
  var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
984
- var path = {
987
+ var path2 = {
985
988
  win32: { sep: "\\" },
986
989
  posix: { sep: "/" }
987
990
  };
988
- var sep = defaultPlatform === "win32" ? path.win32.sep : path.posix.sep;
991
+ var sep = defaultPlatform === "win32" ? path2.win32.sep : path2.posix.sep;
989
992
  minimatch.sep = sep;
990
993
  var GLOBSTAR = Symbol("globstar **");
991
994
  minimatch.GLOBSTAR = GLOBSTAR;
@@ -4162,12 +4165,12 @@ var PathBase = class {
4162
4165
  /**
4163
4166
  * Get the Path object referenced by the string path, resolved from this Path
4164
4167
  */
4165
- resolve(path12) {
4166
- if (!path12) {
4168
+ resolve(path13) {
4169
+ if (!path13) {
4167
4170
  return this;
4168
4171
  }
4169
- const rootPath = this.getRootString(path12);
4170
- const dir = path12.substring(rootPath.length);
4172
+ const rootPath = this.getRootString(path13);
4173
+ const dir = path13.substring(rootPath.length);
4171
4174
  const dirParts = dir.split(this.splitSep);
4172
4175
  const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
4173
4176
  return result;
@@ -4919,8 +4922,8 @@ var PathWin32 = class _PathWin32 extends PathBase {
4919
4922
  /**
4920
4923
  * @internal
4921
4924
  */
4922
- getRootString(path12) {
4923
- return win32.parse(path12).root;
4925
+ getRootString(path13) {
4926
+ return win32.parse(path13).root;
4924
4927
  }
4925
4928
  /**
4926
4929
  * @internal
@@ -4966,8 +4969,8 @@ var PathPosix = class _PathPosix extends PathBase {
4966
4969
  /**
4967
4970
  * @internal
4968
4971
  */
4969
- getRootString(path12) {
4970
- return path12.startsWith("/") ? "/" : "";
4972
+ getRootString(path13) {
4973
+ return path13.startsWith("/") ? "/" : "";
4971
4974
  }
4972
4975
  /**
4973
4976
  * @internal
@@ -5056,11 +5059,11 @@ var PathScurryBase = class {
5056
5059
  /**
5057
5060
  * Get the depth of a provided path, string, or the cwd
5058
5061
  */
5059
- depth(path12 = this.cwd) {
5060
- if (typeof path12 === "string") {
5061
- path12 = this.cwd.resolve(path12);
5062
+ depth(path13 = this.cwd) {
5063
+ if (typeof path13 === "string") {
5064
+ path13 = this.cwd.resolve(path13);
5062
5065
  }
5063
- return path12.depth();
5066
+ return path13.depth();
5064
5067
  }
5065
5068
  /**
5066
5069
  * Return the cache of child entries. Exposed so subclasses can create
@@ -5547,9 +5550,9 @@ var PathScurryBase = class {
5547
5550
  process2();
5548
5551
  return results;
5549
5552
  }
5550
- chdir(path12 = this.cwd) {
5553
+ chdir(path13 = this.cwd) {
5551
5554
  const oldCwd = this.cwd;
5552
- this.cwd = typeof path12 === "string" ? this.cwd.resolve(path12) : path12;
5555
+ this.cwd = typeof path13 === "string" ? this.cwd.resolve(path13) : path13;
5553
5556
  this.cwd[setAsCwd](oldCwd);
5554
5557
  }
5555
5558
  };
@@ -5905,8 +5908,8 @@ var MatchRecord = class {
5905
5908
  }
5906
5909
  // match, absolute, ifdir
5907
5910
  entries() {
5908
- return [...this.store.entries()].map(([path12, n]) => [
5909
- path12,
5911
+ return [...this.store.entries()].map(([path13, n]) => [
5912
+ path13,
5910
5913
  !!(n & 2),
5911
5914
  !!(n & 1)
5912
5915
  ]);
@@ -6111,9 +6114,9 @@ var GlobUtil = class {
6111
6114
  signal;
6112
6115
  maxDepth;
6113
6116
  includeChildMatches;
6114
- constructor(patterns, path12, opts) {
6117
+ constructor(patterns, path13, opts) {
6115
6118
  this.patterns = patterns;
6116
- this.path = path12;
6119
+ this.path = path13;
6117
6120
  this.opts = opts;
6118
6121
  this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/";
6119
6122
  this.includeChildMatches = opts.includeChildMatches !== false;
@@ -6132,11 +6135,11 @@ var GlobUtil = class {
6132
6135
  });
6133
6136
  }
6134
6137
  }
6135
- #ignored(path12) {
6136
- return this.seen.has(path12) || !!this.#ignore?.ignored?.(path12);
6138
+ #ignored(path13) {
6139
+ return this.seen.has(path13) || !!this.#ignore?.ignored?.(path13);
6137
6140
  }
6138
- #childrenIgnored(path12) {
6139
- return !!this.#ignore?.childrenIgnored?.(path12);
6141
+ #childrenIgnored(path13) {
6142
+ return !!this.#ignore?.childrenIgnored?.(path13);
6140
6143
  }
6141
6144
  // backpressure mechanism
6142
6145
  pause() {
@@ -6351,8 +6354,8 @@ var GlobUtil = class {
6351
6354
  };
6352
6355
  var GlobWalker = class extends GlobUtil {
6353
6356
  matches = /* @__PURE__ */ new Set();
6354
- constructor(patterns, path12, opts) {
6355
- super(patterns, path12, opts);
6357
+ constructor(patterns, path13, opts) {
6358
+ super(patterns, path13, opts);
6356
6359
  }
6357
6360
  matchEmit(e) {
6358
6361
  this.matches.add(e);
@@ -6389,8 +6392,8 @@ var GlobWalker = class extends GlobUtil {
6389
6392
  };
6390
6393
  var GlobStream = class extends GlobUtil {
6391
6394
  results;
6392
- constructor(patterns, path12, opts) {
6393
- super(patterns, path12, opts);
6395
+ constructor(patterns, path13, opts) {
6396
+ super(patterns, path13, opts);
6394
6397
  this.results = new Minipass({
6395
6398
  signal: this.signal,
6396
6399
  objectMode: true
@@ -6683,17 +6686,17 @@ var glob = Object.assign(glob_, {
6683
6686
  });
6684
6687
  glob.glob = glob;
6685
6688
 
6686
- // src/build/patches/to-investigate/patch-read-file.ts
6687
- import path2 from "node:path";
6689
+ // src/cli/build/patches/to-investigate/patch-read-file.ts
6690
+ import path3 from "node:path";
6688
6691
  function patchReadFile(code, config) {
6689
6692
  console.log("# patchReadFile");
6690
6693
  code = code.replace(
6691
6694
  "getBuildId() {",
6692
6695
  `getBuildId() {
6693
- return ${JSON.stringify(readFileSync(path2.join(config.paths.standaloneAppDotNext, "BUILD_ID"), "utf-8"))};
6696
+ return ${JSON.stringify(readFileSync(path3.join(config.paths.standaloneAppDotNext, "BUILD_ID"), "utf-8"))};
6694
6697
  `
6695
6698
  );
6696
- const manifestJsons = globSync(path2.join(config.paths.standaloneAppDotNext, "**", "*-manifest.json")).map(
6699
+ const manifestJsons = globSync(path3.join(config.paths.standaloneAppDotNext, "**", "*-manifest.json")).map(
6697
6700
  (file) => file.replace(config.paths.standaloneApp + "/", "")
6698
6701
  );
6699
6702
  code = code.replace(
@@ -6702,7 +6705,7 @@ function patchReadFile(code, config) {
6702
6705
  ${manifestJsons.map(
6703
6706
  (manifestJson) => `
6704
6707
  if ($1.endsWith("${manifestJson}")) {
6705
- return ${readFileSync(path2.join(config.paths.standaloneApp, manifestJson), "utf-8")};
6708
+ return ${readFileSync(path3.join(config.paths.standaloneApp, manifestJson), "utf-8")};
6706
6709
  }
6707
6710
  `
6708
6711
  ).join("\n")}
@@ -6712,8 +6715,8 @@ function patchReadFile(code, config) {
6712
6715
  return code;
6713
6716
  }
6714
6717
 
6715
- // src/build/patches/to-investigate/patch-find-dir.ts
6716
- import path3 from "node:path";
6718
+ // src/cli/build/patches/to-investigate/patch-find-dir.ts
6719
+ import path4 from "node:path";
6717
6720
  import { existsSync } from "node:fs";
6718
6721
  function patchFindDir(code, config) {
6719
6722
  console.log("# patchFindDir");
@@ -6722,10 +6725,10 @@ function patchFindDir(code, config) {
6722
6725
  `function findDir(dir, name) {
6723
6726
  if (dir.endsWith(".next/server")) {
6724
6727
  if (name === "app") {
6725
- return ${existsSync(`${path3.join(config.paths.standaloneAppServer, "app")}`)};
6728
+ return ${existsSync(`${path4.join(config.paths.standaloneAppServer, "app")}`)};
6726
6729
  }
6727
6730
  if (name === "pages") {
6728
- return ${existsSync(`${path3.join(config.paths.standaloneAppServer, "pages")}`)};
6731
+ return ${existsSync(`${path4.join(config.paths.standaloneAppServer, "pages")}`)};
6729
6732
  }
6730
6733
  }
6731
6734
  throw new Error("Unknown findDir call: " + dir + " " + name);
@@ -6733,13 +6736,13 @@ function patchFindDir(code, config) {
6733
6736
  );
6734
6737
  }
6735
6738
 
6736
- // src/build/patches/to-investigate/inline-next-require.ts
6739
+ // src/cli/build/patches/to-investigate/inline-next-require.ts
6737
6740
  import { readFileSync as readFileSync2, existsSync as existsSync2 } from "node:fs";
6738
- import path4 from "node:path";
6741
+ import path5 from "node:path";
6739
6742
  function inlineNextRequire(code, config) {
6740
6743
  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");
6744
+ const pagesManifestFile = path5.join(config.paths.standaloneAppServer, "pages-manifest.json");
6745
+ const appPathsManifestFile = path5.join(config.paths.standaloneAppServer, "app-paths-manifest.json");
6743
6746
  const pagesManifestFiles = existsSync2(pagesManifestFile) ? Object.values(JSON.parse(readFileSync2(pagesManifestFile, "utf-8"))).map(
6744
6747
  (file) => ".next/server/" + file
6745
6748
  ) : [];
@@ -6755,14 +6758,14 @@ function inlineNextRequire(code, config) {
6755
6758
  ${htmlPages.map(
6756
6759
  (htmlPage) => `
6757
6760
  if (pagePath.endsWith("${htmlPage}")) {
6758
- return ${JSON.stringify(readFileSync2(path4.join(config.paths.standaloneApp, htmlPage), "utf-8"))};
6761
+ return ${JSON.stringify(readFileSync2(path5.join(config.paths.standaloneApp, htmlPage), "utf-8"))};
6759
6762
  }
6760
6763
  `
6761
6764
  ).join("\n")}
6762
6765
  ${pageModules.map(
6763
6766
  (module) => `
6764
6767
  if (pagePath.endsWith("${module}")) {
6765
- return require("${path4.join(config.paths.standaloneApp, module)}");
6768
+ return require("${path5.join(config.paths.standaloneApp, module)}");
6766
6769
  }
6767
6770
  `
6768
6771
  ).join("\n")}
@@ -6771,12 +6774,12 @@ function inlineNextRequire(code, config) {
6771
6774
  );
6772
6775
  }
6773
6776
 
6774
- // src/build/patches/to-investigate/inline-eval-manifest.ts
6775
- import path5 from "node:path";
6777
+ // src/cli/build/patches/to-investigate/inline-eval-manifest.ts
6778
+ import path6 from "node:path";
6776
6779
  function inlineEvalManifest(code, config) {
6777
6780
  console.log("# inlineEvalManifest");
6778
6781
  const manifestJss = globSync(
6779
- path5.join(config.paths.standaloneAppDotNext, "**", "*_client-reference-manifest.js")
6782
+ path6.join(config.paths.standaloneAppDotNext, "**", "*_client-reference-manifest.js")
6780
6783
  ).map((file) => file.replace(`${config.paths.standaloneApp}/`, ""));
6781
6784
  return code.replace(
6782
6785
  /function evalManifest\((.+?), .+?\) {/,
@@ -6784,7 +6787,7 @@ function inlineEvalManifest(code, config) {
6784
6787
  ${manifestJss.map(
6785
6788
  (manifestJs) => `
6786
6789
  if ($1.endsWith("${manifestJs}")) {
6787
- require("${path5.join(config.paths.standaloneApp, manifestJs)}");
6790
+ require("${path6.join(config.paths.standaloneApp, manifestJs)}");
6788
6791
  return {
6789
6792
  __RSC_MANIFEST: {
6790
6793
  "${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}": globalThis.__RSC_MANIFEST["${manifestJs.replace(".next/server/app", "").replace("_client-reference-manifest.js", "")}"],
@@ -6798,12 +6801,12 @@ function inlineEvalManifest(code, config) {
6798
6801
  );
6799
6802
  }
6800
6803
 
6801
- // src/build/patches/to-investigate/wrangler-deps.ts
6802
- import path6 from "node:path";
6804
+ // src/cli/build/patches/to-investigate/wrangler-deps.ts
6805
+ import path7 from "node:path";
6803
6806
  import fs, { writeFileSync } from "node:fs";
6804
6807
  function patchWranglerDeps(config) {
6805
6808
  console.log("# patchWranglerDeps");
6806
- const pagesRuntimeFile = path6.join(
6809
+ const pagesRuntimeFile = path7.join(
6807
6810
  config.paths.standaloneApp,
6808
6811
  "node_modules",
6809
6812
  "next",
@@ -6814,7 +6817,7 @@ function patchWranglerDeps(config) {
6814
6817
  );
6815
6818
  const patchedPagesRuntime = fs.readFileSync(pagesRuntimeFile, "utf-8").replace(`e.exports=require("critters")`, `e.exports={}`);
6816
6819
  fs.writeFileSync(pagesRuntimeFile, patchedPagesRuntime);
6817
- const tracerFile = path6.join(
6820
+ const tracerFile = path7.join(
6818
6821
  config.paths.standaloneApp,
6819
6822
  "node_modules",
6820
6823
  "next",
@@ -6828,11 +6831,11 @@ function patchWranglerDeps(config) {
6828
6831
  writeFileSync(tracerFile, pacthedTracer);
6829
6832
  }
6830
6833
 
6831
- // src/build/patches/investigated/update-webpack-chunks-file/index.ts
6834
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/index.ts
6832
6835
  import { readdirSync as readdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
6833
- import path7 from "node:path";
6836
+ import path8 from "node:path";
6834
6837
 
6835
- // src/build/patches/investigated/update-webpack-chunks-file/get-chunk-installation-identifiers.ts
6838
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/get-chunk-installation-identifiers.ts
6836
6839
  import * as ts from "ts-morph";
6837
6840
  async function getChunkInstallationIdentifiers(sourceFile) {
6838
6841
  const installChunkDeclaration = getInstallChunkDeclaration(sourceFile);
@@ -6878,7 +6881,7 @@ function getInstalledChunksDeclaration(sourceFile, installChunkDeclaration) {
6878
6881
  return installedChunksDeclaration;
6879
6882
  }
6880
6883
 
6881
- // src/build/patches/investigated/update-webpack-chunks-file/get-file-content-with-updated-webpack-f-require-code.ts
6884
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/get-file-content-with-updated-webpack-f-require-code.ts
6882
6885
  import * as ts2 from "ts-morph";
6883
6886
  async function getFileContentWithUpdatedWebpackFRequireCode(sourceFile, { installedChunks, installChunk }, chunks) {
6884
6887
  const webpackFRequireFunction = sourceFile.getDescendantsOfKind(ts2.SyntaxKind.ArrowFunction).find((arrowFunction) => {
@@ -6922,7 +6925,7 @@ if(${chunkId} === ${chunk}) return ${installChunk}(require("./chunks/${chunk}.js
6922
6925
  return sourceFile.print();
6923
6926
  }
6924
6927
 
6925
- // src/build/utils/ts-parse-file.ts
6928
+ // src/cli/build/utils/ts-parse-file.ts
6926
6929
  import * as ts3 from "ts-morph";
6927
6930
  function tsParseFile(fileContent) {
6928
6931
  const project = new ts3.Project();
@@ -6930,7 +6933,7 @@ function tsParseFile(fileContent) {
6930
6933
  return sourceFile;
6931
6934
  }
6932
6935
 
6933
- // src/build/patches/investigated/update-webpack-chunks-file/get-updated-webpack-chunks-file-content.ts
6936
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/get-updated-webpack-chunks-file-content.ts
6934
6937
  async function getUpdatedWebpackChunksFileContent(fileContent, chunks) {
6935
6938
  const tsSourceFile = tsParseFile(fileContent);
6936
6939
  const chunkInstallationIdentifiers = await getChunkInstallationIdentifiers(tsSourceFile);
@@ -6942,12 +6945,12 @@ async function getUpdatedWebpackChunksFileContent(fileContent, chunks) {
6942
6945
  return updatedFileContent;
6943
6946
  }
6944
6947
 
6945
- // src/build/patches/investigated/update-webpack-chunks-file/index.ts
6948
+ // src/cli/build/patches/investigated/update-webpack-chunks-file/index.ts
6946
6949
  async function updateWebpackChunksFile(config) {
6947
6950
  console.log("# updateWebpackChunksFile");
6948
- const webpackRuntimeFile = path7.join(config.paths.standaloneAppServer, "webpack-runtime.js");
6951
+ const webpackRuntimeFile = path8.join(config.paths.standaloneAppServer, "webpack-runtime.js");
6949
6952
  const fileContent = readFileSync3(webpackRuntimeFile, "utf-8");
6950
- const chunks = readdirSync2(path7.join(config.paths.standaloneAppServer, "chunks")).filter((chunk) => /^\d+\.js$/.test(chunk)).map((chunk) => {
6953
+ const chunks = readdirSync2(path8.join(config.paths.standaloneAppServer, "chunks")).filter((chunk) => /^\d+\.js$/.test(chunk)).map((chunk) => {
6951
6954
  console.log(` - chunk ${chunk}`);
6952
6955
  return chunk.replace(/\.js$/, "");
6953
6956
  });
@@ -6955,11 +6958,11 @@ async function updateWebpackChunksFile(config) {
6955
6958
  writeFileSync2(webpackRuntimeFile, updatedFileContent);
6956
6959
  }
6957
6960
 
6958
- // src/build/patches/investigated/patch-cache.ts
6959
- import path8 from "node:path";
6961
+ // src/cli/build/patches/investigated/patch-cache.ts
6962
+ import path9 from "node:path";
6960
6963
  function patchCache(code, config) {
6961
6964
  console.log("# patchCached");
6962
- const cacheHandler = path8.join(config.paths.internalPackage, "cache-handler.mjs");
6965
+ const cacheHandler = path9.join(config.paths.internalPackage, "cli", "cache-handler.mjs");
6963
6966
  const patchedCode = code.replace(
6964
6967
  "const { cacheHandler } = this.nextConfig;",
6965
6968
  `const cacheHandler = null;
@@ -6973,29 +6976,29 @@ CacheHandler.maybeKVNamespace = process.env["${config.cache.kvBindingName}"];
6973
6976
  return patchedCode;
6974
6977
  }
6975
6978
 
6976
- // src/build/build-worker.ts
6977
- var packageDir = path9.dirname(fileURLToPath3(import.meta.url));
6979
+ // src/cli/build/build-worker.ts
6980
+ var packageDistDir = path10.join(path10.dirname(fileURLToPath3(import.meta.url)), "..");
6978
6981
  async function buildWorker(config) {
6979
6982
  console.log(`\x1B[35m\u2699\uFE0F Copying files...
6980
6983
  \x1B[0m`);
6981
6984
  await cp(
6982
- path9.join(config.paths.dotNext, "static"),
6983
- path9.join(config.paths.builderOutput, "assets", "_next", "static"),
6985
+ path10.join(config.paths.dotNext, "static"),
6986
+ path10.join(config.paths.builderOutput, "assets", "_next", "static"),
6984
6987
  {
6985
6988
  recursive: true
6986
6989
  }
6987
6990
  );
6988
- const publicDir = path9.join(config.paths.nextApp, "public");
6991
+ const publicDir = path10.join(config.paths.nextApp, "public");
6989
6992
  if (existsSync3(publicDir)) {
6990
- await cp(publicDir, path9.join(config.paths.builderOutput, "assets"), {
6993
+ await cp(publicDir, path10.join(config.paths.builderOutput, "assets"), {
6991
6994
  recursive: true
6992
6995
  });
6993
6996
  }
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(
6997
+ copyPackageCliFiles(packageDistDir, config);
6998
+ const templateDir = path10.join(config.paths.internalPackage, "cli", "templates");
6999
+ const workerEntrypoint = path10.join(templateDir, "worker.ts");
7000
+ const workerOutputFile = path10.join(config.paths.builderOutput, "index.mjs");
7001
+ const nextConfigStr = readFileSync4(path10.join(config.paths.standaloneApp, "/server.js"), "utf8")?.match(
6999
7002
  /const nextConfig = ({.+?})\n/
7000
7003
  )?.[1] ?? {};
7001
7004
  console.log(`\x1B[35m\u2699\uFE0F Bundling the worker file...
@@ -7014,15 +7017,15 @@ async function buildWorker(config) {
7014
7017
  // Note: we apply an empty shim to next/dist/compiled/ws because it generates two `eval`s:
7015
7018
  // eval("require")("bufferutil");
7016
7019
  // eval("require")("utf-8-validate");
7017
- "next/dist/compiled/ws": path9.join(templateDir, "shims", "empty.ts"),
7020
+ "next/dist/compiled/ws": path10.join(templateDir, "shims", "empty.ts"),
7018
7021
  // Note: we apply an empty shim to next/dist/compiled/edge-runtime since (amongst others) it generated the following `eval`:
7019
7022
  // eval(getModuleCode)(module, module.exports, throwingRequire, params.context, ...Object.values(params.scopedContext));
7020
7023
  // which comes from https://github.com/vercel/edge-runtime/blob/6e96b55f/packages/primitives/src/primitives/load.js#L57-L63
7021
7024
  // QUESTION: Why did I encountered this but mhart didn't?
7022
- "next/dist/compiled/edge-runtime": path9.join(templateDir, "shims", "empty.ts"),
7025
+ "next/dist/compiled/edge-runtime": path10.join(templateDir, "shims", "empty.ts"),
7023
7026
  // `@next/env` is a library Next.js uses for loading dotenv files, for obvious reasons we need to stub it here
7024
7027
  // source: https://github.com/vercel/next.js/tree/0ac10d79720/packages/next-env
7025
- "@next/env": path9.join(templateDir, "shims", "env.ts")
7028
+ "@next/env": path10.join(templateDir, "shims", "env.ts")
7026
7029
  },
7027
7030
  define: {
7028
7031
  // config file used by Next.js, see: https://github.com/vercel/next.js/blob/68a7128/packages/next/src/build/utils.ts#L2137-L2139
@@ -7102,18 +7105,18 @@ function createFixRequiresESBuildPlugin(templateDir) {
7102
7105
  name: "replaceRelative",
7103
7106
  setup(build3) {
7104
7107
  build3.onResolve({ filter: /^\.\/require-hook$/ }, (args) => ({
7105
- path: path9.join(templateDir, "shims", "empty.ts")
7108
+ path: path10.join(templateDir, "shims", "empty.ts")
7106
7109
  }));
7107
7110
  build3.onResolve({ filter: /\.\/lib\/node-fs-methods$/ }, (args) => ({
7108
- path: path9.join(templateDir, "shims", "empty.ts")
7111
+ path: path10.join(templateDir, "shims", "empty.ts")
7109
7112
  }));
7110
7113
  }
7111
7114
  };
7112
7115
  }
7113
7116
 
7114
- // src/config.ts
7117
+ // src/cli/config.ts
7115
7118
  import { readdirSync as readdirSync3, statSync as statSync2 } from "node:fs";
7116
- import path10, { relative } from "node:path";
7119
+ import path11, { relative } from "node:path";
7117
7120
  var PACKAGE_NAME = "@opennextjs/cloudflare";
7118
7121
  var UserConfig = {
7119
7122
  cache: {
@@ -7121,13 +7124,13 @@ var UserConfig = {
7121
7124
  }
7122
7125
  };
7123
7126
  function getConfig(appDir, outputDir2) {
7124
- const dotNext = path10.join(outputDir2, ".next");
7127
+ const dotNext = path11.join(outputDir2, ".next");
7125
7128
  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("/"));
7129
+ const standaloneApp = path11.join(dotNext, "standalone", appPath);
7130
+ const standaloneAppDotNext = path11.join(standaloneApp, ".next");
7131
+ const standaloneAppServer = path11.join(standaloneAppDotNext, "server");
7132
+ const nodeModules = path11.join(standaloneApp, "node_modules");
7133
+ const internalPackage = path11.join(nodeModules, ...PACKAGE_NAME.split("/"));
7131
7134
  return {
7132
7135
  paths: {
7133
7136
  nextApp: appDir,
@@ -7146,7 +7149,7 @@ function getConfig(appDir, outputDir2) {
7146
7149
  }
7147
7150
  function containsDotNextDir(folder) {
7148
7151
  try {
7149
- return statSync2(path10.join(folder, ".next")).isDirectory();
7152
+ return statSync2(path11.join(folder, ".next")).isDirectory();
7150
7153
  } catch (e) {
7151
7154
  return false;
7152
7155
  }
@@ -7156,19 +7159,19 @@ function getNextjsApplicationPath(dotNextDir) {
7156
7159
  if (!serverPath) {
7157
7160
  throw new Error(`Unexpected Error: no \`.next/server\` folder could be found in \`${serverPath}\``);
7158
7161
  }
7159
- return relative(path10.join(dotNextDir, "standalone"), serverPath);
7162
+ return relative(path11.join(dotNextDir, "standalone"), serverPath);
7160
7163
  }
7161
7164
  function findServerParentPath(parentPath) {
7162
7165
  try {
7163
- if (statSync2(path10.join(parentPath, ".next", "server")).isDirectory()) {
7166
+ if (statSync2(path11.join(parentPath, ".next", "server")).isDirectory()) {
7164
7167
  return parentPath;
7165
7168
  }
7166
7169
  } catch {
7167
7170
  }
7168
7171
  const folders = readdirSync3(parentPath);
7169
7172
  for (const folder of folders) {
7170
- const subFolder = path10.join(parentPath, folder);
7171
- if (statSync2(path10.join(parentPath, folder)).isDirectory()) {
7173
+ const subFolder = path11.join(parentPath, folder);
7174
+ if (statSync2(path11.join(parentPath, folder)).isDirectory()) {
7172
7175
  const dirServerPath = findServerParentPath(subFolder);
7173
7176
  if (dirServerPath) {
7174
7177
  return dirServerPath;
@@ -7177,9 +7180,9 @@ function findServerParentPath(parentPath) {
7177
7180
  }
7178
7181
  }
7179
7182
 
7180
- // src/build/build.ts
7181
- import { cpSync as cpSync3 } from "node:fs";
7182
- import path11 from "node:path";
7183
+ // src/cli/build/index.ts
7184
+ import { cpSync as cpSync2 } from "node:fs";
7185
+ import path12 from "node:path";
7183
7186
  async function build2(appDir, opts) {
7184
7187
  if (!opts.skipBuild) {
7185
7188
  buildNextjsApp(appDir);
@@ -7187,17 +7190,17 @@ async function build2(appDir, opts) {
7187
7190
  if (!containsDotNextDir(appDir)) {
7188
7191
  throw new Error(`.next folder not found in ${appDir}`);
7189
7192
  }
7190
- const outputDir2 = path11.resolve(opts.outputDir ?? appDir, ".worker-next");
7193
+ const outputDir2 = path12.resolve(opts.outputDir ?? appDir, ".worker-next");
7191
7194
  await cleanDirectory(outputDir2);
7192
- cpSync3(path11.join(appDir, ".next"), path11.join(outputDir2, ".next"), { recursive: true });
7195
+ cpSync2(path12.join(appDir, ".next"), path12.join(outputDir2, ".next"), { recursive: true });
7193
7196
  const config = getConfig(appDir, outputDir2);
7194
7197
  await buildWorker(config);
7195
7198
  }
7196
- async function cleanDirectory(path12) {
7197
- return await rm(path12, { recursive: true, force: true });
7199
+ async function cleanDirectory(path13) {
7200
+ return await rm(path13, { recursive: true, force: true });
7198
7201
  }
7199
7202
 
7200
- // src/index.ts
7203
+ // src/cli/index.ts
7201
7204
  var nextAppDir = resolve2(".");
7202
7205
  console.log(`Building the Next.js app in the current folder (${nextAppDir})`);
7203
7206
  if (!["js", "cjs", "mjs", "ts"].some((ext2) => existsSync4(`./next.config.${ext2}`))) {
@@ -1,46 +1,64 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
1
2
  import Stream from "node:stream";
2
3
  import type { NextConfig } from "next";
3
4
  import { NodeNextRequest, NodeNextResponse } from "next/dist/server/base-http/node";
4
5
  import { MockedResponse } from "next/dist/server/lib/mock-request";
5
6
  import NextNodeServer, { NodeRequestHandler } from "next/dist/server/next-server";
6
7
  import type { IncomingMessage } from "node:http";
8
+ import { type CloudflareContext } from "../../api";
7
9
 
8
10
  const NON_BODY_RESPONSES = new Set([101, 204, 205, 304]);
9
11
 
12
+ const cloudflareContextALS = new AsyncLocalStorage<CloudflareContext>();
13
+
14
+ // Note: this symbol needs to be kept in sync with the one defined in `src/api/get-cloudflare-context.ts`
15
+ (globalThis as any)[Symbol.for("__cloudflare-context__")] = new Proxy(
16
+ {},
17
+ {
18
+ ownKeys: () => Reflect.ownKeys(cloudflareContextALS.getStore()!),
19
+ getOwnPropertyDescriptor: (_, ...args) =>
20
+ Reflect.getOwnPropertyDescriptor(cloudflareContextALS.getStore()!, ...args),
21
+ get: (_, property) => Reflect.get(cloudflareContextALS.getStore()!, property),
22
+ set: (_, property, value) => Reflect.set(cloudflareContextALS.getStore()!, property, value),
23
+ }
24
+ );
25
+
10
26
  // Injected at build time
11
27
  const nextConfig: NextConfig = JSON.parse(process.env.__NEXT_PRIVATE_STANDALONE_CONFIG ?? "{}");
12
28
 
13
29
  let requestHandler: NodeRequestHandler | null = null;
14
30
 
15
31
  export default {
16
- async fetch(request: Request, env: any, ctx: any) {
17
- if (requestHandler == null) {
18
- globalThis.process.env = { ...globalThis.process.env, ...env };
19
- requestHandler = new NextNodeServer({
20
- conf: { ...nextConfig, env },
21
- customServer: false,
22
- dev: false,
23
- dir: "",
24
- minimalMode: false,
25
- }).getRequestHandler();
26
- }
27
-
28
- const url = new URL(request.url);
29
-
30
- if (url.pathname === "/_next/image") {
31
- let imageUrl =
32
- url.searchParams.get("url") ?? "https://developers.cloudflare.com/_astro/logo.BU9hiExz.svg";
33
- if (imageUrl.startsWith("/")) {
34
- return env.ASSETS.fetch(new URL(imageUrl, request.url));
32
+ async fetch(request: Request & { cf: IncomingRequestCfProperties }, env: any, ctx: any) {
33
+ return cloudflareContextALS.run({ env, ctx, cf: request.cf }, async () => {
34
+ if (requestHandler == null) {
35
+ globalThis.process.env = { ...globalThis.process.env, ...env };
36
+ requestHandler = new NextNodeServer({
37
+ conf: { ...nextConfig, env },
38
+ customServer: false,
39
+ dev: false,
40
+ dir: "",
41
+ minimalMode: false,
42
+ }).getRequestHandler();
43
+ }
44
+
45
+ const url = new URL(request.url);
46
+
47
+ if (url.pathname === "/_next/image") {
48
+ let imageUrl =
49
+ url.searchParams.get("url") ?? "https://developers.cloudflare.com/_astro/logo.BU9hiExz.svg";
50
+ if (imageUrl.startsWith("/")) {
51
+ return env.ASSETS.fetch(new URL(imageUrl, request.url));
52
+ }
53
+ return fetch(imageUrl, { cf: { cacheEverything: true } } as any);
35
54
  }
36
- return fetch(imageUrl, { cf: { cacheEverything: true } } as any);
37
- }
38
55
 
39
- const { req, res, webResponse } = getWrappedStreams(request, ctx);
56
+ const { req, res, webResponse } = getWrappedStreams(request, ctx);
40
57
 
41
- ctx.waitUntil(requestHandler(new NodeNextRequest(req), new NodeNextResponse(res)));
58
+ ctx.waitUntil(requestHandler(new NodeNextRequest(req), new NodeNextResponse(res)));
42
59
 
43
- return await webResponse();
60
+ return await webResponse();
61
+ });
44
62
  },
45
63
  };
46
64
 
package/package.json CHANGED
@@ -1,8 +1,16 @@
1
1
  {
2
2
  "name": "@opennextjs/cloudflare",
3
3
  "description": "Cloudflare builder for next apps",
4
- "version": "0.0.0-9758666",
5
- "bin": "dist/index.mjs",
4
+ "version": "0.0.0-af15fd1",
5
+ "bin": "dist/cli/index.mjs",
6
+ "main": "./dist/api/index.mjs",
7
+ "types": "./dist/api/index.d.mts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/api/index.mjs",
11
+ "types": "./dist/api/index.d.mts"
12
+ }
13
+ },
6
14
  "files": [
7
15
  "README.md",
8
16
  "dist"
File without changes