@nodegx/backend 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -54,7 +54,7 @@ function deployEnvironment() {
54
54
  const set = (k, v) => {
55
55
  if (!process.env[k]) process.env[k] = v;
56
56
  };
57
- // The deploy's own folder, as it sees it: `../scripts/build.js` from here is the pack's stub (build.mjs).
57
+ // The deploy's own folder, as it sees it (where it looks for a wrangler installed beside it).
58
58
  set('NODEGX_CLOUDFLARE_SRC', path.join(DIST, 'cloudflare'));
59
59
  set('NODEGX_CLOUDFLARE_WORKER', need(path.join(DIST, 'worker', 'worker.mjs'), 'The Worker (dist/worker/worker.mjs)'));
60
60
  set('NODEGX_CLOUD_BUNDLE', need(path.join(DIST, 'cloud-bundle.cjs'), 'The cloud-function bundler (dist/cloud-bundle.cjs)'));
@@ -74,8 +74,8 @@ function provider(word, verb) {
74
74
  /** wrangler, as the deploy itself runs it (one installed nearby, else `npx wrangler@4`), with the terminal attached. */
75
75
  function wrangler(args) {
76
76
  deployEnvironment();
77
- const { __nodegxWranglerCommand } = require(need(path.join(DIST, 'cloudflare-deploy.cjs'), 'The deploy (dist/cloudflare-deploy.cjs)'));
78
- const [cmd, ...pre] = __nodegxWranglerCommand();
77
+ const { wranglerCommand } = require(need(path.join(DIST, 'cloudflare-deploy.cjs'), 'The deploy (dist/cloudflare-deploy.cjs)'));
78
+ const [cmd, ...pre] = wranglerCommand();
79
79
  const run = spawnSync(cmd, [...pre, ...args], { stdio: 'inherit', env: { ...process.env, WRANGLER_SEND_METRICS: 'false' } });
80
80
  return run.status ?? 1;
81
81
  }
@@ -251,14 +251,14 @@ var require_model = __commonJS({
251
251
  };
252
252
  Model2.prototype.set = function(name2, value2, args) {
253
253
  if (args && args.resolve && name2.indexOf(".") !== -1) {
254
- var path2 = name2.split(".");
254
+ var path4 = name2.split(".");
255
255
  var model = this;
256
- for (var i = 0; i < path2.length - 1; i++) {
257
- var v = model.get(path2[i]);
256
+ for (var i = 0; i < path4.length - 1; i++) {
257
+ var v = model.get(path4[i]);
258
258
  if (Model2.instanceOf(v)) model = v;
259
259
  else return;
260
260
  }
261
- model.set(path2[path2.length - 1], value2);
261
+ model.set(path4[path4.length - 1], value2);
262
262
  return;
263
263
  }
264
264
  const forceChange = args && args.forceChange;
@@ -271,14 +271,14 @@ var require_model = __commonJS({
271
271
  };
272
272
  Model2.prototype.get = function(name2, args) {
273
273
  if (args && args.resolve && name2.indexOf(".") !== -1) {
274
- var path2 = name2.split(".");
274
+ var path4 = name2.split(".");
275
275
  var model = this;
276
- for (var i = 0; i < path2.length - 1; i++) {
277
- var v = model.get(path2[i]);
276
+ for (var i = 0; i < path4.length - 1; i++) {
277
+ var v = model.get(path4[i]);
278
278
  if (Model2.instanceOf(v)) model = v;
279
279
  else return;
280
280
  }
281
- return model.get(path2[path2.length - 1]);
281
+ return model.get(path4[path4.length - 1]);
282
282
  }
283
283
  return this.data[name2];
284
284
  };
@@ -3727,42 +3727,24 @@ var require_mapcollectionnode = __commonJS({
3727
3727
  }
3728
3728
  });
3729
3729
 
3730
- // src/prebuilt-worker.cjs
3731
- var require_prebuilt_worker = __commonJS({
3732
- "src/prebuilt-worker.cjs"(exports2) {
3733
- "use strict";
3734
- var fs3 = require("fs");
3735
- var path2 = require("path");
3736
- exports2.build = async function build(options) {
3737
- const entry = String(options && options.entryPoints && options.entryPoints[0] || "");
3738
- const prebuilt = process.env.NODEGX_CLOUDFLARE_WORKER;
3739
- if (path2.basename(entry) !== "worker.ts" || !prebuilt) {
3740
- throw new Error(`@nodegx/backend bundles nothing at deploy time (asked for ${entry || "no entry"}); see src/prebuilt-worker.cjs.`);
3741
- }
3742
- if (!fs3.existsSync(prebuilt)) throw new Error(`The prebuilt Worker is not here (${prebuilt}): this install is incomplete.`);
3743
- fs3.mkdirSync(path2.dirname(options.outfile), { recursive: true });
3744
- fs3.copyFileSync(prebuilt, options.outfile);
3745
- return { errors: [], warnings: [] };
3746
- };
3747
- }
3748
- });
3749
-
3750
3730
  // ../nodegx-backend/cloudflare/deployCloudflare.ts
3751
3731
  var deployCloudflare_exports = {};
3752
3732
  __export(deployCloudflare_exports, {
3753
- __nodegxBuildWorker: () => buildWorker,
3754
- __nodegxWranglerCommand: () => wranglerCommand,
3733
+ WORKER_OWN_MODULES: () => WORKER_OWN_MODULES,
3734
+ buildWorker: () => buildWorker,
3735
+ bundleWorker: () => bundleWorker,
3755
3736
  deploy: () => deploy,
3756
3737
  leaks: () => leaks,
3757
3738
  main: () => main,
3758
- parseArgs: () => parseArgs
3739
+ parseArgs: () => parseArgs,
3740
+ wranglerCommand: () => wranglerCommand
3759
3741
  });
3760
3742
  module.exports = __toCommonJS(deployCloudflare_exports);
3761
3743
  var import_node_child_process = require("node:child_process");
3762
- var crypto2 = __toESM(require("node:crypto"));
3763
- var fs2 = __toESM(require("node:fs"));
3764
- var os = __toESM(require("node:os"));
3765
- var path = __toESM(require("node:path"));
3744
+ var crypto4 = __toESM(require("node:crypto"));
3745
+ var fs4 = __toESM(require("node:fs"));
3746
+ var os2 = __toESM(require("node:os"));
3747
+ var path3 = __toESM(require("node:path"));
3766
3748
 
3767
3749
  // ../noodl-runtime/src/nodes/std-library/expression-ports.ts
3768
3750
  var EXPRESSION_MATH_ALIASES = [
@@ -4332,11 +4314,11 @@ function namedRoles(config) {
4332
4314
  // ../nodegx-backend/cloudflare/applyProject.ts
4333
4315
  var ApplyError = class extends Error {
4334
4316
  };
4335
- async function must(call, method, path2, body) {
4336
- const answer = await call(method, path2, body);
4317
+ async function must(call, method, path4, body) {
4318
+ const answer = await call(method, path4, body);
4337
4319
  if (answer.status >= 300) {
4338
4320
  const said = answer.json?.error ?? answer.text.slice(0, 600);
4339
- throw new ApplyError(`${method} /${path2.replace(/^\//, "")} answered ${answer.status}: ${said}`);
4321
+ throw new ApplyError(`${method} /${path4.replace(/^\//, "")} answered ${answer.status}: ${said}`);
4340
4322
  }
4341
4323
  return answer;
4342
4324
  }
@@ -4437,11 +4419,11 @@ async function applyProject(call, project, options) {
4437
4419
  function automationsSha256(text) {
4438
4420
  return crypto.createHash("sha256").update(text).digest("hex");
4439
4421
  }
4440
- async function must2(call, method, path2, body) {
4441
- const answer = await call(method, path2, body);
4422
+ async function must2(call, method, path4, body) {
4423
+ const answer = await call(method, path4, body);
4442
4424
  if (answer.status >= 300) {
4443
4425
  const said = answer.json?.error ?? answer.text.slice(0, 600);
4444
- throw new ApplyError(`${method} /${path2.replace(/^\//, "")} answered ${answer.status}: ${said}`);
4426
+ throw new ApplyError(`${method} /${path4.replace(/^\//, "")} answered ${answer.status}: ${said}`);
4445
4427
  }
4446
4428
  return answer;
4447
4429
  }
@@ -4571,6 +4553,457 @@ ${differences.map((d) => ` - ${d}`).join("\n")}
4571
4553
  return report;
4572
4554
  }
4573
4555
 
4556
+ // ../nodegx-backend/cloudflare/deployApi.ts
4557
+ var crypto3 = __toESM(require("node:crypto"));
4558
+ var fs3 = __toESM(require("node:fs"));
4559
+ var path2 = __toESM(require("node:path"));
4560
+
4561
+ // ../nodegx-backend/cloudflare/signIn.ts
4562
+ var crypto2 = __toESM(require("crypto"));
4563
+ var fs2 = __toESM(require("fs"));
4564
+ var os = __toESM(require("os"));
4565
+ var path = __toESM(require("path"));
4566
+ var CLOUDFLARE_TOKEN_URL = "https://dash.cloudflare.com/oauth2/token";
4567
+ var CLOUDFLARE_SCOPES = [
4568
+ "offline_access",
4569
+ "user-details.read",
4570
+ "account-settings.read",
4571
+ "workers-scripts.admin",
4572
+ "workers-kv-storage.write",
4573
+ "workers-r2.write",
4574
+ "workers-routes.write",
4575
+ "zone.read",
4576
+ "dns.write",
4577
+ "email-sending.write",
4578
+ "registrar-domains.admin"
4579
+ ];
4580
+ var LOCK_WAIT_MS = 15e3;
4581
+ var LOCK_STALE_MS = 3e4;
4582
+ var EXPIRY_MARGIN_MS = 6e4;
4583
+ var DEFAULT_TIMEOUT_MS = 10 * 6e4;
4584
+ var SignInError = class extends Error {
4585
+ constructor(message, code) {
4586
+ super(message);
4587
+ this.code = code;
4588
+ this.name = "SignInError";
4589
+ }
4590
+ };
4591
+ function cloudflareHome() {
4592
+ return process.env.NODEGX_CLOUDFLARE_HOME || path.join(os.homedir(), ".nodegx", "cloudflare");
4593
+ }
4594
+ function signInFile() {
4595
+ return path.join(cloudflareHome(), "sign-in.json");
4596
+ }
4597
+ function readSignIn(file = signInFile()) {
4598
+ let raw;
4599
+ try {
4600
+ raw = fs2.readFileSync(file, "utf8");
4601
+ } catch {
4602
+ return null;
4603
+ }
4604
+ try {
4605
+ const s = JSON.parse(raw);
4606
+ return typeof s.accessToken === "string" && s.accessToken ? s : null;
4607
+ } catch {
4608
+ return null;
4609
+ }
4610
+ }
4611
+ function writeSignIn(s, file = signInFile()) {
4612
+ const dir = path.dirname(file);
4613
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
4614
+ const tmp = `${file}.${process.pid}.${crypto2.randomBytes(4).toString("hex")}.tmp`;
4615
+ fs2.writeFileSync(tmp, JSON.stringify(s, null, 2) + "\n", { mode: 384 });
4616
+ fs2.chmodSync(tmp, 384);
4617
+ fs2.renameSync(tmp, file);
4618
+ }
4619
+ var defaultFetch = (url, init) => fetch(url, init);
4620
+ async function tokenRequest(form, o) {
4621
+ const res = await (o.fetchImpl ?? defaultFetch)(o.tokenUrl ?? CLOUDFLARE_TOKEN_URL, {
4622
+ method: "POST",
4623
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
4624
+ body: new URLSearchParams(form).toString()
4625
+ });
4626
+ let body = null;
4627
+ try {
4628
+ body = await res.json();
4629
+ } catch {
4630
+ }
4631
+ if (!res.ok || !body?.access_token) {
4632
+ const why = String(body?.error_description || body?.error || `HTTP ${res.status}`).slice(0, 300);
4633
+ const err = new SignInError(`Cloudflare did not hand over the sign-in: ${why}`, "failed");
4634
+ err.oauthError = body?.error;
4635
+ throw err;
4636
+ }
4637
+ return body;
4638
+ }
4639
+ function fromAnswer(a, clientId, asked, now, previous) {
4640
+ return {
4641
+ clientId,
4642
+ accessToken: a.access_token,
4643
+ refreshToken: a.refresh_token ?? previous?.refreshToken,
4644
+ // No `expires_in` is read as one hour (Hydra's default) rather than as "forever".
4645
+ expiresAt: new Date(now + (typeof a.expires_in === "number" ? a.expires_in : 3600) * 1e3).toISOString(),
4646
+ scopes: a.scope ? a.scope.split(/\s+/).filter(Boolean) : previous?.scopes ?? [...asked],
4647
+ signedInAt: previous?.signedInAt ?? new Date(now).toISOString(),
4648
+ ...previous ? { refreshedAt: new Date(now).toISOString() } : {}
4649
+ };
4650
+ }
4651
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
4652
+ async function withLock(file, fn) {
4653
+ const lock = `${file}.lock`;
4654
+ const started = Date.now();
4655
+ for (; ; ) {
4656
+ try {
4657
+ const fd = fs2.openSync(lock, "wx", 384);
4658
+ fs2.closeSync(fd);
4659
+ break;
4660
+ } catch (e) {
4661
+ if (e.code !== "EEXIST") throw e;
4662
+ try {
4663
+ if (Date.now() - fs2.statSync(lock).mtimeMs > LOCK_STALE_MS) fs2.rmSync(lock, { force: true });
4664
+ } catch {
4665
+ }
4666
+ if (Date.now() - started > LOCK_WAIT_MS) {
4667
+ throw new SignInError("Another part of NodeGX is renewing the Cloudflare sign-in and has not finished. Try again in a moment.", "failed");
4668
+ }
4669
+ await sleep(100);
4670
+ }
4671
+ }
4672
+ try {
4673
+ return await fn();
4674
+ } finally {
4675
+ fs2.rmSync(lock, { force: true });
4676
+ }
4677
+ }
4678
+ var expiredSentence = () => new SignInError("Your Cloudflare sign-in has run out. Ask Claude to sign in to Cloudflare again (one page, one click).", "expired");
4679
+ async function cloudflareAccessToken(o = {}) {
4680
+ const file = o.file ?? signInFile();
4681
+ const now = o.now ?? Date.now;
4682
+ const first = readSignIn(file);
4683
+ const began = now();
4684
+ const fresh = (s) => o.force ? !!s.refreshedAt && Date.parse(s.refreshedAt) >= began && s !== first : Date.parse(s.expiresAt) - EXPIRY_MARGIN_MS > now();
4685
+ if (!first) return null;
4686
+ if (fresh(first)) return first.accessToken;
4687
+ if (!first.refreshToken) throw expiredSentence();
4688
+ return withLock(file, async () => {
4689
+ const s = readSignIn(file);
4690
+ if (!s) return null;
4691
+ if (fresh(s)) return s.accessToken;
4692
+ if (!s.refreshToken) throw expiredSentence();
4693
+ let a;
4694
+ try {
4695
+ a = await tokenRequest({ grant_type: "refresh_token", refresh_token: s.refreshToken, client_id: s.clientId }, o);
4696
+ } catch (e) {
4697
+ if (e.oauthError === "invalid_grant") {
4698
+ fs2.rmSync(file, { force: true });
4699
+ throw expiredSentence();
4700
+ }
4701
+ throw e;
4702
+ }
4703
+ const next = fromAnswer(a, s.clientId, s.scopes, now(), s);
4704
+ writeSignIn(next, file);
4705
+ return next.accessToken;
4706
+ });
4707
+ }
4708
+ function missingScopes(s, wanted = CLOUDFLARE_SCOPES) {
4709
+ const have = new Set(s.scopes);
4710
+ return wanted.filter((w) => w !== "offline_access" && !have.has(w));
4711
+ }
4712
+
4713
+ // ../nodegx-backend/cloudflare/deployApi.ts
4714
+ var ApiDeployError = class extends Error {
4715
+ constructor(message) {
4716
+ super(message);
4717
+ this.name = "ApiDeployError";
4718
+ }
4719
+ };
4720
+ var CLOUDFLARE_API = "https://api.cloudflare.com/client/v4";
4721
+ var PUBLIC_DNS = "https://cloudflare-dns.com/dns-query";
4722
+ var DO_CLASS = "NodegxBackend";
4723
+ var MIGRATION_TAG = "v1";
4724
+ var MAX_ASSET_BYTES = 25 * 1024 * 1024;
4725
+ var MIME = {
4726
+ html: "text/html",
4727
+ htm: "text/html",
4728
+ css: "text/css",
4729
+ js: "application/javascript",
4730
+ mjs: "application/javascript",
4731
+ json: "application/json",
4732
+ map: "application/json",
4733
+ txt: "text/plain",
4734
+ xml: "application/xml",
4735
+ svg: "image/svg+xml",
4736
+ png: "image/png",
4737
+ jpg: "image/jpeg",
4738
+ jpeg: "image/jpeg",
4739
+ gif: "image/gif",
4740
+ webp: "image/webp",
4741
+ avif: "image/avif",
4742
+ ico: "image/x-icon",
4743
+ woff: "font/woff",
4744
+ woff2: "font/woff2",
4745
+ ttf: "font/ttf",
4746
+ otf: "font/otf",
4747
+ wasm: "application/wasm",
4748
+ mp3: "audio/mpeg",
4749
+ wav: "audio/wav",
4750
+ ogg: "audio/ogg",
4751
+ mp4: "video/mp4",
4752
+ webm: "video/webm",
4753
+ pdf: "application/pdf",
4754
+ glb: "model/gltf-binary",
4755
+ gltf: "model/gltf+json"
4756
+ };
4757
+ var mimeOf = (file) => MIME[path2.extname(file).slice(1).toLowerCase()] ?? "application/octet-stream";
4758
+ function assetHash(content, ext) {
4759
+ return crypto3.createHash("sha256").update(content.toString("base64") + ext).digest("hex").slice(0, 32);
4760
+ }
4761
+ function filesUnder(dir) {
4762
+ const out = [];
4763
+ const walk = (d) => {
4764
+ for (const e of fs3.readdirSync(d, { withFileTypes: true }).sort((x, y) => x.name.localeCompare(y.name))) {
4765
+ const full = path2.join(d, e.name);
4766
+ if (e.isDirectory()) walk(full);
4767
+ else if (e.isFile()) out.push(full);
4768
+ }
4769
+ };
4770
+ if (fs3.existsSync(dir)) walk(dir);
4771
+ return out;
4772
+ }
4773
+ function siteManifest(siteDir) {
4774
+ const m = /* @__PURE__ */ new Map();
4775
+ for (const file of filesUnder(siteDir)) {
4776
+ const content = fs3.readFileSync(file);
4777
+ if (content.length > MAX_ASSET_BYTES) {
4778
+ throw new ApiDeployError(`${path2.relative(siteDir, file)} is ${(content.length / 1e6).toFixed(1)} MB: Cloudflare takes site files up to 25 MB each.`);
4779
+ }
4780
+ const key = "/" + path2.relative(siteDir, file).split(path2.sep).join("/");
4781
+ m.set(key, { file, hash: assetHash(content, path2.extname(file).slice(1)), size: content.length });
4782
+ }
4783
+ return m;
4784
+ }
4785
+ function moduleType(file) {
4786
+ const ext = path2.extname(file).toLowerCase();
4787
+ if (ext === ".mjs" || ext === ".js") return "application/javascript+module";
4788
+ if (ext === ".wasm") return "application/wasm";
4789
+ if (ext === ".txt" || ext === ".html") return "text/plain";
4790
+ if (ext === ".bin") return "application/octet-stream";
4791
+ throw new ApiDeployError(`The Worker's build holds ${path2.basename(file)}, a kind of file the upload does not know how to send.`);
4792
+ }
4793
+ async function chooseRoute(o, tokenFor = () => cloudflareAccessToken()) {
4794
+ if (o.local) return { via: "wrangler", why: "--local runs the Worker on this computer, on wrangler's workerd" };
4795
+ if (o.wrangler) return { via: "wrangler", why: "--wrangler" };
4796
+ const s = readSignIn();
4797
+ if (!s) return { via: "wrangler", why: "this computer has no NodeGX sign-in to Cloudflare" };
4798
+ if (missingScopes(s, ["workers-scripts.admin"]).length) {
4799
+ throw new ApiDeployError(
4800
+ "Your NodeGX sign-in to Cloudflare cannot put an app online: it was made before NodeGX asked for Workers Admin, and Cloudflare refuses a Worker to anything less. Sign in to Cloudflare again (one page, one click), or deploy with --wrangler."
4801
+ );
4802
+ }
4803
+ try {
4804
+ const token = await tokenFor();
4805
+ if (!token) return { via: "wrangler", why: "this computer has no NodeGX sign-in to Cloudflare" };
4806
+ return { via: "api", token };
4807
+ } catch (e) {
4808
+ if (e instanceof SignInError) throw new ApiDeployError(e.message);
4809
+ throw e;
4810
+ }
4811
+ }
4812
+ var errText = (j) => (j?.errors ?? []).map((e) => e.code !== void 0 ? `${e.code}: ${e.message}` : String(e.message)).join("; ") || "";
4813
+ var hasCode = (j, code) => (j?.errors ?? []).some((e) => e.code === code);
4814
+ async function deployThroughApi(o) {
4815
+ const f = o.fetchImpl ?? ((u, i) => fetch(u, i));
4816
+ const api = o.api ?? process.env.NODEGX_CF_API ?? CLOUDFLARE_API;
4817
+ const log = o.log ?? (() => {
4818
+ });
4819
+ const lines = [];
4820
+ const say2 = (l) => {
4821
+ lines.push(l);
4822
+ log(l);
4823
+ };
4824
+ const auth = { authorization: `Bearer ${o.token}` };
4825
+ const call = async (method, p, body, headers = auth) => {
4826
+ const isJson = body !== void 0 && !(body instanceof FormData);
4827
+ let res;
4828
+ try {
4829
+ res = await f(p.startsWith("http") ? p : api + p, {
4830
+ method,
4831
+ headers: isJson ? { ...headers, "content-type": "application/json" } : headers,
4832
+ body: isJson ? JSON.stringify(body) : body
4833
+ });
4834
+ } catch (e) {
4835
+ const c = e?.cause;
4836
+ throw new ApiDeployError(`Cloudflare could not be reached (${e.message}${c?.code ? `: ${c.code}` : ""}). Nothing was changed by this step.`);
4837
+ }
4838
+ let j = null;
4839
+ try {
4840
+ j = await res.json();
4841
+ } catch {
4842
+ }
4843
+ return { status: res.status, j, ok: res.status >= 200 && res.status < 300 && j?.success !== false };
4844
+ };
4845
+ let account = o.account ?? process.env.CLOUDFLARE_ACCOUNT_ID;
4846
+ if (!account) {
4847
+ const r = await call("GET", "/accounts?per_page=50");
4848
+ const accounts = r.j?.result ?? [];
4849
+ if (!r.ok || !accounts.length) throw new ApiDeployError(`Your Cloudflare sign-in sees no account (${r.status} ${errText(r.j)}).`);
4850
+ if (accounts.length > 1) throw new ApiDeployError(`Your Cloudflare sign-in sees ${accounts.length} accounts; choose one with --account:
4851
+ ${accounts.map((a) => ` ${a.id} ${a.name}`).join("\n")}`);
4852
+ account = accounts[0].id;
4853
+ }
4854
+ const A = `/accounts/${account}`;
4855
+ const sub = await call("GET", `${A}/workers/subdomain`);
4856
+ const subdomain = sub.j?.result?.subdomain;
4857
+ if (!subdomain) {
4858
+ throw new ApiDeployError(
4859
+ "This Cloudflare account has no workers.dev address yet, which every app needs. Open Workers & Pages in the Cloudflare dashboard once: it asks for one (the name you choose is part of every app's address). Nothing was changed."
4860
+ );
4861
+ }
4862
+ const list = await call("GET", `${A}/workers/scripts`);
4863
+ if (!list.ok) throw new ApiDeployError(`Cloudflare would not list the Workers on the account (${list.status} ${errText(list.j)}). Nothing was changed.`);
4864
+ const existing = (list.j?.result ?? []).find((s) => s.id === o.name);
4865
+ if (existing && !o.ours) {
4866
+ throw new ApiDeployError(
4867
+ `A Worker called ${o.name} is already on your Cloudflare account, and this computer did not put it there: deploying would replace it. Choose another name with --name. Nothing was changed.`
4868
+ );
4869
+ }
4870
+ const tag = existing?.migration_tag || null;
4871
+ if (tag && tag !== MIGRATION_TAG) {
4872
+ throw new ApiDeployError(`The Worker ${o.name} has the Durable Object migration "${tag}", which this deploy does not know (it writes "${MIGRATION_TAG}"). Nothing was changed.`);
4873
+ }
4874
+ if (o.bucket && (!existing || o.firstDeploy)) {
4875
+ const r = await call("POST", `${A}/r2/buckets`, { name: o.bucket });
4876
+ if (r.ok) say2(`bucket ${o.bucket}: made`);
4877
+ else if (r.status === 409 || hasCode(r.j, 10004) || /already exists|already own/i.test(errText(r.j))) say2(`bucket ${o.bucket}: already there`);
4878
+ else {
4879
+ throw new ApiDeployError(
4880
+ `The bucket ${o.bucket} could not be made (${r.status} ${errText(r.j)}). R2 must be switched on in the Cloudflare dashboard once; --no-bucket deploys without file storage. Nothing else was changed.`
4881
+ );
4882
+ }
4883
+ }
4884
+ const manifest = siteManifest(o.siteDir);
4885
+ const byHash = new Map([...manifest.values()].map((v) => [v.hash, v]));
4886
+ const session = await call("POST", `${A}/workers/scripts/${o.name}/assets-upload-session`, {
4887
+ manifest: Object.fromEntries([...manifest].map(([k, v]) => [k, { hash: v.hash, size: v.size }]))
4888
+ });
4889
+ if (!session.ok) throw new ApiDeployError(refusedSentence("the site's file list", session));
4890
+ const uploadJwt = session.j?.result?.jwt;
4891
+ let assetsJwt = uploadJwt;
4892
+ const buckets = session.j?.result?.buckets ?? [];
4893
+ let sent = 0;
4894
+ for (const b of buckets) {
4895
+ const form2 = new FormData();
4896
+ for (const h of b) {
4897
+ const v = byHash.get(h);
4898
+ if (!v) throw new ApiDeployError(`Cloudflare asked for a site file this deploy never listed (${h}). Nothing on the app was changed.`);
4899
+ form2.append(h, new Blob([fs3.readFileSync(v.file).toString("base64")], { type: mimeOf(v.file) }), h);
4900
+ }
4901
+ const up2 = await call("POST", `${A}/workers/assets/upload?base64=true`, form2, { authorization: `Bearer ${uploadJwt}` });
4902
+ if (!up2.ok) throw new ApiDeployError(refusedSentence("the site's files", up2));
4903
+ sent += b.length;
4904
+ if (up2.j?.result?.jwt) assetsJwt = up2.j.result.jwt;
4905
+ }
4906
+ if (!assetsJwt) throw new ApiDeployError("Cloudflare took the site's files but gave no receipt for them (no jwt). Nothing on the app was changed.");
4907
+ say2(`site: ${manifest.size} file(s), ${sent} sent (Cloudflare has the rest already)`);
4908
+ const bindings = [
4909
+ { type: "durable_object_namespace", name: "BACKEND", class_name: DO_CLASS },
4910
+ { type: "assets", name: "ASSETS" }
4911
+ ];
4912
+ if (o.bucket) bindings.push({ type: "r2_bucket", name: "FILES", bucket_name: o.bucket });
4913
+ if (o.alert) {
4914
+ bindings.push(
4915
+ { type: "send_email", name: "ALERT_EMAIL" },
4916
+ { type: "plain_text", name: "NODEGX_ALERT_FROM", text: o.alert.from },
4917
+ { type: "plain_text", name: "NODEGX_ALERT_TO", text: o.alert.to }
4918
+ );
4919
+ }
4920
+ const metadata = {
4921
+ main_module: "worker.mjs",
4922
+ compatibility_date: o.compatibilityDate ?? "2026-10-01",
4923
+ compatibility_flags: ["nodejs_compat"],
4924
+ bindings,
4925
+ assets: { jwt: assetsJwt, config: { run_worker_first: true } },
4926
+ observability: { enabled: true }
4927
+ };
4928
+ if (!existing) {
4929
+ metadata.migrations = { new_tag: MIGRATION_TAG, new_sqlite_classes: [DO_CLASS] };
4930
+ bindings.push({ type: "secret_text", name: "NODEGX_ADMIN_TOKEN", text: o.adminToken });
4931
+ } else {
4932
+ metadata.keep_bindings = ["secret_text"];
4933
+ }
4934
+ const modules = filesUnder(o.distDir).filter((p) => path2.dirname(p) === o.distDir);
4935
+ if (!modules.some((p) => path2.basename(p) === "worker.mjs")) throw new ApiDeployError(`The Worker's build has no worker.mjs in ${o.distDir}.`);
4936
+ const form = new FormData();
4937
+ form.append("metadata", new Blob([JSON.stringify(metadata)], { type: "application/json" }));
4938
+ for (const p of modules.sort((a, b) => path2.basename(a) === "worker.mjs" ? -1 : path2.basename(b) === "worker.mjs" ? 1 : a.localeCompare(b))) {
4939
+ form.append(path2.basename(p), new Blob([fs3.readFileSync(p)], { type: moduleType(p) }), path2.basename(p));
4940
+ }
4941
+ const up = await call("PUT", `${A}/workers/scripts/${o.name}`, form);
4942
+ if (!up.ok) throw new ApiDeployError(refusedSentence("the Worker", up) + (existing ? " The app online is the one from before, unchanged." : ""));
4943
+ say2(`Worker ${o.name}: ${existing ? "updated (its data and its credential kept)" : "made"}`);
4944
+ const url = `https://${o.name}.${subdomain}.workers.dev`;
4945
+ o.onWorkerUp?.(url);
4946
+ if (existing && o.replaceSecret) {
4947
+ const s = await call("PUT", `${A}/workers/scripts/${o.name}/secrets`, { name: "NODEGX_ADMIN_TOKEN", text: o.adminToken, type: "secret_text" });
4948
+ if (!s.ok) throw new ApiDeployError(`The new admin credential was not set (${s.status} ${errText(s.j)}): the Worker still has the old one. Deploy again with --new-admin-credential.`);
4949
+ say2("admin credential: replaced (the old one no longer works)");
4950
+ }
4951
+ const on = await call("POST", `${A}/workers/scripts/${o.name}/subdomain`, { enabled: true, previews_enabled: false });
4952
+ if (!on.ok) throw new ApiDeployError(`The Worker is up, but its workers.dev address could not be turned on (${on.status} ${errText(on.j)}). Deploy again to finish.`);
4953
+ if (o.previousDomain && o.previousDomain !== o.domain) {
4954
+ const found = await call("GET", `${A}/workers/domains?hostname=${encodeURIComponent(o.previousDomain)}`);
4955
+ const mine = (found.j?.result ?? []).filter((d) => d.hostname === o.previousDomain && d.service === o.name);
4956
+ for (const d of mine) {
4957
+ const del = await call("DELETE", `${A}/workers/domains/${d.id}`);
4958
+ say2(del.ok ? `domain ${o.previousDomain}: detached` : `domain ${o.previousDomain}: NOT detached (${del.status} ${errText(del.j)}); remove it in the dashboard`);
4959
+ }
4960
+ }
4961
+ let domain = null;
4962
+ if (o.domain) {
4963
+ const zoneId = await zoneOf(call, o.domain);
4964
+ if (!zoneId) {
4965
+ throw new ApiDeployError(`The app is online at ${url}, but ${o.domain} is not in a zone on this Cloudflare account, so it cannot answer there. Add the domain to the account, then deploy again.`);
4966
+ }
4967
+ const dom = await call("PUT", `${A}/workers/domains`, { hostname: o.domain, service: o.name, zone_id: zoneId, environment: "production" });
4968
+ if (!dom.ok) throw new ApiDeployError(`The app is online at ${url}, but ${o.domain} could not be attached (${dom.status} ${errText(dom.j)}).`);
4969
+ const t0 = Date.now();
4970
+ const wait = o.waitDnsMs ?? 18e4;
4971
+ let there = await inPublicDns(f, o.domain);
4972
+ while (!there && Date.now() - t0 < wait) {
4973
+ await new Promise((r) => setTimeout(r, o.pollMs ?? 3e3));
4974
+ there = await inPublicDns(f, o.domain);
4975
+ }
4976
+ domain = { host: o.domain, inPublicDns: there, waitedMs: Date.now() - t0 };
4977
+ say2(`domain ${o.domain}: attached; ${there ? `in public DNS after ${Math.round(domain.waitedMs / 1e3)} s` : `not in public DNS after ${Math.round(wait / 1e3)} s`}`);
4978
+ }
4979
+ return { url, domain, lines };
4980
+ }
4981
+ function refusedSentence(what, r) {
4982
+ const words = errText(r.j);
4983
+ if (r.status === 403 && !(r.j?.errors ?? []).some((e) => e.code !== void 0)) {
4984
+ return `Cloudflare refused ${what} (403 "${words || "no access"}"): the sign-in is not allowed to put a Worker up. It needs Workers Admin: sign in to Cloudflare again.`;
4985
+ }
4986
+ return `Cloudflare refused ${what} (${r.status}${words ? ` ${words}` : ""}).`;
4987
+ }
4988
+ async function zoneOf(call, host) {
4989
+ const labels = host.split(".");
4990
+ for (let i = 0; i < labels.length - 1; i++) {
4991
+ const r = await call("GET", `/zones?name=${encodeURIComponent(labels.slice(i).join("."))}`);
4992
+ const id = r.j?.result?.[0]?.id;
4993
+ if (r.ok && id) return id;
4994
+ }
4995
+ return null;
4996
+ }
4997
+ async function inPublicDns(f, host) {
4998
+ try {
4999
+ const res = await f(`${PUBLIC_DNS}?name=${encodeURIComponent(host)}&type=A`, { method: "GET", headers: { accept: "application/dns-json" } });
5000
+ const j = await res.json();
5001
+ return (j?.Answer ?? []).some((a) => a.type === void 0 || a.type === 1 || a.type === 5);
5002
+ } catch {
5003
+ return false;
5004
+ }
5005
+ }
5006
+
4574
5007
  // ../nodegx-backend/cloudflare/wranglerConfig.ts
4575
5008
  function emailProblem(what, address) {
4576
5009
  return /^[^\s@<>"]+@[a-z0-9-]+(\.[a-z0-9-]+)+$/i.test(address) ? null : `${what} "${address}" is not an email address (write it bare, like alerts@example.com).`;
@@ -4657,14 +5090,16 @@ function wranglerConfig(input2) {
4657
5090
 
4658
5091
  // ../nodegx-backend/cloudflare/deployCloudflare.ts
4659
5092
  var HERE = process.env.NODEGX_CLOUDFLARE_SRC || __dirname;
4660
- var PACKAGES = path.resolve(HERE, "..", "..");
5093
+ var PACKAGES = path3.resolve(HERE, "..", "..");
4661
5094
  var DeployError = class extends Error {
4662
5095
  };
4663
5096
  var say = (line = "") => process.stdout.write(line + "\n");
4664
- var USAGE = `usage: ${process.env.NODEGX_CLOUDFLARE_COMMAND || "deploy.mjs"} <project> [--name <worker>] [--bucket <r2 bucket> | --no-bucket] [--viewer <folder>]
5097
+ var PROGRAM = process.env.NODEGX_CLOUDFLARE_COMMAND || "deploy.mjs";
5098
+ var USAGE = `usage: ${PROGRAM} <project> [--name <worker>] [--bucket <r2 bucket> | --no-bucket] [--viewer <folder>]
4665
5099
  [--allow-development-engine] [--out <folder>] [--local [--port <n>]] [--make-roles]
4666
5100
  [--new-admin-credential] [--dry-run] [--domain <hostname> | --no-domain]
4667
- [--alert-to <address> --alert-from <address on your Cloudflare domain> | --no-alert]`;
5101
+ [--alert-to <address> --alert-from <address on your Cloudflare domain> | --no-alert]
5102
+ [--wrangler] [--account <id>]`;
4668
5103
  function parseArgs(argv) {
4669
5104
  const o = { project: "" };
4670
5105
  for (let i = 0; i < argv.length; i++) {
@@ -4678,9 +5113,9 @@ ${USAGE}`);
4678
5113
  if (a === "--name") o.name = next();
4679
5114
  else if (a === "--bucket") o.bucket = next();
4680
5115
  else if (a === "--no-bucket") o.bucket = null;
4681
- else if (a === "--viewer") o.viewer = path.resolve(next());
5116
+ else if (a === "--viewer") o.viewer = path3.resolve(next());
4682
5117
  else if (a === "--allow-development-engine") o.allowDevelopmentEngine = true;
4683
- else if (a === "--out") o.out = path.resolve(next());
5118
+ else if (a === "--out") o.out = path3.resolve(next());
4684
5119
  else if (a === "--local") o.local = true;
4685
5120
  else if (a === "--port") o.port = Number(next());
4686
5121
  else if (a === "--make-roles") o.makeRoles = true;
@@ -4691,9 +5126,11 @@ ${USAGE}`);
4691
5126
  else if (a === "--alert-to") o.alertTo = next().trim();
4692
5127
  else if (a === "--alert-from") o.alertFrom = next().trim();
4693
5128
  else if (a === "--no-alert") o.alertTo = o.alertFrom = null;
5129
+ else if (a === "--wrangler") o.wrangler = true;
5130
+ else if (a === "--account") o.account = next().trim();
4694
5131
  else if (a.startsWith("--")) throw new DeployError(`${a} is not an option.
4695
5132
  ${USAGE}`);
4696
- else if (!o.project) o.project = path.resolve(a);
5133
+ else if (!o.project) o.project = path3.resolve(a);
4697
5134
  else throw new DeployError(`One project at a time.
4698
5135
  ${USAGE}`);
4699
5136
  }
@@ -4701,20 +5138,20 @@ ${USAGE}`);
4701
5138
  return o;
4702
5139
  }
4703
5140
  function readProject(dir) {
4704
- const file = path.join(dir, "nodegx.project.json");
4705
- if (!fs2.existsSync(file)) throw new DeployError(`${dir} is not a NodeGX project: it has no nodegx.project.json.`);
4706
- const json = JSON.parse(fs2.readFileSync(file, "utf8"));
4707
- const policyFile = path.join(dir, "nodegx.security.json");
4708
- const policyText = fs2.existsSync(policyFile) ? fs2.readFileSync(policyFile, "utf8") : null;
5141
+ const file = path3.join(dir, "nodegx.project.json");
5142
+ if (!fs4.existsSync(file)) throw new DeployError(`${dir} is not a NodeGX project: it has no nodegx.project.json.`);
5143
+ const json = JSON.parse(fs4.readFileSync(file, "utf8"));
5144
+ const policyFile = path3.join(dir, "nodegx.security.json");
5145
+ const policyText = fs4.existsSync(policyFile) ? fs4.readFileSync(policyFile, "utf8") : null;
4709
5146
  if (policyText) JSON.parse(policyText);
4710
- const automationsFile = path.join(dir, "nodegx.automations.json");
4711
- const automationsText = fs2.existsSync(automationsFile) ? fs2.readFileSync(automationsFile, "utf8") : null;
5147
+ const automationsFile = path3.join(dir, "nodegx.automations.json");
5148
+ const automationsText = fs4.existsSync(automationsFile) ? fs4.readFileSync(automationsFile, "utf8") : null;
4712
5149
  if (automationsText) JSON.parse(automationsText);
4713
- const envFile = path.join(dir, ".env");
4714
- const envValues = fs2.existsSync(envFile) ? fs2.readFileSync(envFile, "utf8").split("\n").map((l) => l.replace(/^\s*(export\s+)?[A-Za-z_][A-Za-z0-9_]*\s*=\s*/, "").replace(/^['"]|['"]\s*$/g, "").trim()).filter((v) => v.length >= 8) : [];
5150
+ const envFile = path3.join(dir, ".env");
5151
+ const envValues = fs4.existsSync(envFile) ? fs4.readFileSync(envFile, "utf8").split("\n").map((l) => l.replace(/^\s*(export\s+)?[A-Za-z_][A-Za-z0-9_]*\s*=\s*/, "").replace(/^['"]|['"]\s*$/g, "").trim()).filter((v) => v.length >= 8) : [];
4715
5152
  return {
4716
5153
  dir,
4717
- name: json.name || path.basename(dir),
5154
+ name: json.name || path3.basename(dir),
4718
5155
  file: json,
4719
5156
  policyText,
4720
5157
  automationsText,
@@ -4723,20 +5160,20 @@ function readProject(dir) {
4723
5160
  };
4724
5161
  }
4725
5162
  function deploymentsRoot() {
4726
- return process.env.NODEGX_CLOUDFLARE_HOME || path.join(os.homedir(), ".nodegx", "cloudflare");
5163
+ return process.env.NODEGX_CLOUDFLARE_HOME || path3.join(os2.homedir(), ".nodegx", "cloudflare");
4727
5164
  }
4728
5165
  function readRecord(dir) {
4729
- const file = path.join(dir, "deployment.json");
4730
- return fs2.existsSync(file) ? JSON.parse(fs2.readFileSync(file, "utf8")) : null;
5166
+ const file = path3.join(dir, "deployment.json");
5167
+ return fs4.existsSync(file) ? JSON.parse(fs4.readFileSync(file, "utf8")) : null;
4731
5168
  }
4732
5169
  function writeRecord(dir, record) {
4733
- const file = path.join(dir, "deployment.json");
4734
- fs2.writeFileSync(file, JSON.stringify(record, null, 2) + "\n", { mode: 384 });
4735
- fs2.chmodSync(file, 384);
5170
+ const file = path3.join(dir, "deployment.json");
5171
+ fs4.writeFileSync(file, JSON.stringify(record, null, 2) + "\n", { mode: 384 });
5172
+ fs4.chmodSync(file, 384);
4736
5173
  }
4737
5174
  function cloudFunctions(projectDir) {
4738
- const entry = process.env.NODEGX_CLOUD_BUNDLE || path.join(PACKAGES, "noodl-mcp", "dist", "cloud-bundle.cjs");
4739
- if (!fs2.existsSync(entry)) {
5175
+ const entry = process.env.NODEGX_CLOUD_BUNDLE || path3.join(PACKAGES, "noodl-mcp", "dist", "cloud-bundle.cjs");
5176
+ if (!fs4.existsSync(entry)) {
4740
5177
  throw new DeployError(`The cloud-function bundler is not here (${entry}): run \`npm run build\` in packages/noodl-mcp.`);
4741
5178
  }
4742
5179
  const run = (0, import_node_child_process.spawnSync)(process.execPath, [entry, projectDir], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, timeout: 12e4 });
@@ -4745,61 +5182,85 @@ ${(run.stderr || "").trim() || "no output"}`);
4745
5182
  return JSON.parse(run.stdout);
4746
5183
  }
4747
5184
  var NOT_FOR_THE_HOST = ["DEPLOY.md", "serve.js", "package.json", ".nodegx-deploy.json", "nodegx-config.json"];
5185
+ var VIEWER_HINT = "\nName a production viewer with --viewer <folder holding noodl.deploy.js>.";
5186
+ function siteThroughCli(copy, out, allowDev) {
5187
+ const cli = process.env.NODEGX_CLI || path3.join(PACKAGES, "nodegx-export", "dist", "cli.mjs");
5188
+ if (!process.env.NODEGX_CLI && process.env.NODEGX_DEPLOY_CLI && !fs4.existsSync(cli)) return null;
5189
+ const args = [cli, "deploy", copy, out];
5190
+ if (allowDev) args.push("--allow-development-engine");
5191
+ const run = (0, import_node_child_process.spawnSync)(process.execPath, args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
5192
+ if (run.status !== 0) {
5193
+ throw new DeployError(`\`nodegx deploy\` refused (${run.status}):
5194
+ ${(run.stdout + run.stderr).trim()}` + (run.status === 11 ? VIEWER_HINT : ""));
5195
+ }
5196
+ return run.stdout.split("\n").filter((l) => / deployed to |left out|excluded|engine/i.test(l)).map((l) => l.trim());
5197
+ }
5198
+ function siteThroughEngine(copy, out, allowDev) {
5199
+ const engine = process.env.NODEGX_DEPLOY_CLI;
5200
+ if (!fs4.existsSync(engine)) throw new DeployError(`NODEGX_DEPLOY_CLI is set to ${engine}, and there is nothing there.`);
5201
+ const args = [engine, copy, out];
5202
+ if (allowDev) args.push("--allow-development-engine");
5203
+ const run = (0, import_node_child_process.spawnSync)(process.execPath, args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
5204
+ const last = (run.stdout || "").trim().split("\n").pop() || "";
5205
+ let report;
5206
+ try {
5207
+ report = JSON.parse(last);
5208
+ } catch {
5209
+ throw new DeployError(`The site's deploy engine gave no report (${run.status}):
5210
+ ${(run.stderr || "").trim().slice(-2e3) || "no output"}`);
5211
+ }
5212
+ if (report.ok !== true) {
5213
+ throw new DeployError(`The site's deploy engine refused (${report.stage}): ${report.message ?? "no reason given"}` + (report.stage === "engine" ? VIEWER_HINT : ""));
5214
+ }
5215
+ if (report.blank) throw new DeployError(`This deploy would ship a blank site, so it stops here.
5216
+ ${report.blank}`);
5217
+ const notes = [`${report.projectName ?? "project"} deployed to ${out} \u2014 ${(report.files ?? []).length} entries`];
5218
+ if (report.engine) notes.push(`engine: ${report.engine.kind} build of the NodeGX viewer, ${(report.engine.bytes / 1e6).toFixed(2)} MB`);
5219
+ for (const w of report.warnings ?? []) notes.push(`! ${w}`);
5220
+ if (report.excluded?.length) notes.push(`${report.excluded.length} project file(s) left out: ${report.excluded.slice(0, 5).map((e) => e.path).join(", ")}`);
5221
+ return notes;
5222
+ }
4748
5223
  function buildSite(project, name2, siteDir, o) {
4749
- const work = fs2.mkdtempSync(path.join(os.tmpdir(), "nodegx-cf-site-"));
5224
+ const work = fs4.mkdtempSync(path3.join(os2.tmpdir(), "nodegx-cf-site-"));
4750
5225
  try {
4751
- const copy = path.join(work, "project");
4752
- fs2.cpSync(project.dir, copy, { recursive: true, filter: (src) => !/[/\\](\.git|node_modules|\.previews)$/.test(src) });
4753
- const json = JSON.parse(fs2.readFileSync(path.join(copy, "nodegx.project.json"), "utf8"));
5226
+ const copy = path3.join(work, "project");
5227
+ fs4.cpSync(project.dir, copy, { recursive: true, filter: (src) => !/[/\\](\.git|node_modules|\.previews)$/.test(src) });
5228
+ const json = JSON.parse(fs4.readFileSync(path3.join(copy, "nodegx.project.json"), "utf8"));
4754
5229
  json.metadata = { ...json.metadata || {}, cloudservices: { endpoint: "", appId: name2, instanceId: name2, type: "nodegx" } };
4755
- fs2.writeFileSync(path.join(copy, "nodegx.project.json"), JSON.stringify(json, null, 2));
4756
- const out = path.join(work, "site");
4757
- const cli = process.env.NODEGX_CLI || path.join(PACKAGES, "nodegx-export", "dist", "cli.mjs");
4758
- const args = [cli, "deploy", copy, out];
4759
- if (o.viewer || o.allowDevelopmentEngine) args.push("--allow-development-engine");
4760
- const run = (0, import_node_child_process.spawnSync)(process.execPath, args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
4761
- if (run.status !== 0) {
4762
- throw new DeployError(
4763
- `\`nodegx deploy\` refused (${run.status}):
4764
- ${(run.stdout + run.stderr).trim()}` + (run.status === 11 ? "\nName a production viewer with --viewer <folder holding noodl.deploy.js>." : "")
4765
- );
4766
- }
4767
- const notes = run.stdout.split("\n").filter((l) => / deployed to |left out|excluded|engine/i.test(l)).map((l) => l.trim());
5230
+ fs4.writeFileSync(path3.join(copy, "nodegx.project.json"), JSON.stringify(json, null, 2));
5231
+ const out = path3.join(work, "site");
5232
+ const allowDev = !!(o.viewer || o.allowDevelopmentEngine);
5233
+ const notes = siteThroughCli(copy, out, allowDev) ?? siteThroughEngine(copy, out, allowDev);
4768
5234
  if (o.viewer) {
4769
5235
  for (const f of ["noodl.deploy.js", "noodl.deploy.js.LICENSE.txt"]) {
4770
- const from = path.join(o.viewer, f);
4771
- if (fs2.existsSync(from)) fs2.copyFileSync(from, path.join(out, f));
5236
+ const from = path3.join(o.viewer, f);
5237
+ if (fs4.existsSync(from)) fs4.copyFileSync(from, path3.join(out, f));
4772
5238
  else if (f === "noodl.deploy.js") throw new DeployError(`--viewer ${o.viewer} holds no noodl.deploy.js.`);
4773
5239
  }
4774
- const engine = readViewerBuild(path.join(out, "noodl.deploy.js"));
5240
+ const engine = readViewerBuild(path3.join(out, "noodl.deploy.js"));
4775
5241
  if (engine.kind !== "production") {
4776
5242
  throw new DeployError(`--viewer ${o.viewer} is a DEVELOPMENT build of the viewer: ${engine.reasons.join("; ")}.`);
4777
5243
  }
4778
5244
  notes.push(`viewer: production, from ${o.viewer} (${(engine.bytes / 1e6).toFixed(2)} MB)`);
4779
5245
  }
4780
- for (const f of NOT_FOR_THE_HOST) fs2.rmSync(path.join(out, f), { force: true });
4781
- const hidden = filesUnder(out).filter((f) => path.relative(out, f).split(path.sep).some((part) => part.startsWith(".")));
4782
- for (const f of hidden) fs2.rmSync(f, { force: true });
4783
- if (hidden.length) notes.push(`left out (hidden files are never published): ${hidden.map((f) => path.relative(out, f)).join(", ")}`);
4784
- fs2.rmSync(siteDir, { recursive: true, force: true });
4785
- fs2.cpSync(out, siteDir, { recursive: true });
5246
+ for (const f of NOT_FOR_THE_HOST) fs4.rmSync(path3.join(out, f), { force: true });
5247
+ const hidden = filesUnder2(out).filter((f) => path3.relative(out, f).split(path3.sep).some((part) => part.startsWith(".")));
5248
+ for (const f of hidden) fs4.rmSync(f, { force: true });
5249
+ if (hidden.length) notes.push(`left out (hidden files are never published): ${hidden.map((f) => path3.relative(out, f)).join(", ")}`);
5250
+ fs4.rmSync(siteDir, { recursive: true, force: true });
5251
+ fs4.cpSync(out, siteDir, { recursive: true });
4786
5252
  return notes;
4787
5253
  } finally {
4788
- fs2.rmSync(work, { recursive: true, force: true });
5254
+ fs4.rmSync(work, { recursive: true, force: true });
4789
5255
  }
4790
5256
  }
4791
- async function buildWorker(distDir, app, printed) {
4792
- const esbuild = require_prebuilt_worker();
4793
- const { shared } = require(path.join(HERE, "..", "scripts", "build.js"));
4794
- fs2.mkdirSync(distDir, { recursive: true });
4795
- fs2.writeFileSync(path.join(distDir, "printed-code.mjs"), printed);
4796
- fs2.writeFileSync(path.join(distDir, "app.mjs"), `export default ${JSON.stringify(app)};
4797
- `);
4798
- const nodeSqlite = path.join(HERE, "nodeSqlite.ts");
5257
+ async function bundleWorker(outfile, plugins = [], esbuild = require("esbuild")) {
5258
+ const { shared } = require(path3.join(HERE, "..", "scripts", "build.js"));
5259
+ const nodeSqlite = path3.join(HERE, "nodeSqlite.ts");
4799
5260
  await esbuild.build({
4800
5261
  ...shared,
4801
- entryPoints: [path.join(HERE, "worker.ts")],
4802
- outfile: path.join(distDir, "worker.mjs"),
5262
+ entryPoints: [path3.join(HERE, "worker.ts")],
5263
+ outfile,
4803
5264
  format: "esm",
4804
5265
  target: "es2022",
4805
5266
  sourcemap: false,
@@ -4819,26 +5280,42 @@ async function buildWorker(distDir, app, printed) {
4819
5280
  b.onResolve({ filter: /^\.\/(printed-code|app)\.mjs$/ }, (a) => ({ path: a.path, external: true }));
4820
5281
  b.onResolve({ filter: /^node:sqlite$/ }, () => ({ path: nodeSqlite }));
4821
5282
  }
4822
- }
5283
+ },
5284
+ ...plugins
4823
5285
  ]
4824
5286
  });
4825
5287
  }
4826
- function filesUnder(dir) {
5288
+ var WORKER_OWN_MODULES = ["./printed-code.mjs", "./app.mjs"];
5289
+ async function buildWorker(distDir, app, printed) {
5290
+ fs4.mkdirSync(distDir, { recursive: true });
5291
+ fs4.writeFileSync(path3.join(distDir, "printed-code.mjs"), printed);
5292
+ fs4.writeFileSync(path3.join(distDir, "app.mjs"), `export default ${JSON.stringify(app)};
5293
+ `);
5294
+ const prebuilt = process.env.NODEGX_CLOUDFLARE_WORKER;
5295
+ if (prebuilt) {
5296
+ if (!fs4.existsSync(prebuilt)) throw new DeployError(`The prebuilt Worker is not here (${prebuilt}): this copy of the deploy is incomplete.`);
5297
+ fs4.copyFileSync(prebuilt, path3.join(distDir, "worker.mjs"));
5298
+ return "prebuilt";
5299
+ }
5300
+ await bundleWorker(path3.join(distDir, "worker.mjs"));
5301
+ return "bundled";
5302
+ }
5303
+ function filesUnder2(dir) {
4827
5304
  const out = [];
4828
5305
  const walk = (d) => {
4829
- for (const e of fs2.readdirSync(d, { withFileTypes: true })) {
4830
- const full = path.join(d, e.name);
5306
+ for (const e of fs4.readdirSync(d, { withFileTypes: true })) {
5307
+ const full = path3.join(d, e.name);
4831
5308
  if (e.isDirectory()) walk(full);
4832
5309
  else out.push(full);
4833
5310
  }
4834
5311
  };
4835
- if (fs2.existsSync(dir)) walk(dir);
5312
+ if (fs4.existsSync(dir)) walk(dir);
4836
5313
  return out;
4837
5314
  }
4838
5315
  function leaks(files, secrets) {
4839
5316
  const found = [];
4840
5317
  for (const f of files) {
4841
- const text = fs2.readFileSync(f, "latin1");
5318
+ const text = fs4.readFileSync(f, "latin1");
4842
5319
  for (const s of secrets) if (s.value && text.includes(s.value)) found.push(`${s.what} is in ${f}`);
4843
5320
  }
4844
5321
  return found;
@@ -4919,8 +5396,8 @@ async function applyEverything(base, token, project, functions, makeRoles, where
4919
5396
  const target = where.local ? "local" : "live";
4920
5397
  const automations = await applyAutomations(call, project.automationsText, { installedSha256: where.record.automations?.[target] ?? null });
4921
5398
  if (automations.before) {
4922
- const kept = path.join(where.dir, `automations.before-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
4923
- fs2.writeFileSync(kept, JSON.stringify(automations.before, null, 2) + "\n");
5399
+ const kept = path3.join(where.dir, `automations.before-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
5400
+ fs4.writeFileSync(kept, JSON.stringify(automations.before, null, 2) + "\n");
4924
5401
  automations.lines.push(`The backend's previous ones are kept in ${kept}.`);
4925
5402
  }
4926
5403
  for (const l of automations.lines) say(` ${l}`);
@@ -4973,10 +5450,10 @@ async function deploy(o) {
4973
5450
  const name2 = o.name || (o.out ? readRecord(o.out)?.name : void 0) || workerNameFrom(project.name);
4974
5451
  const problem = workerNameProblem(name2);
4975
5452
  if (problem) throw new DeployError(problem);
4976
- const dir = o.out || path.join(root, name2);
4977
- fs2.mkdirSync(dir, { recursive: true });
5453
+ const dir = o.out || path3.join(root, name2);
5454
+ fs4.mkdirSync(dir, { recursive: true });
4978
5455
  const before = readRecord(dir);
4979
- if (before && path.resolve(before.project) !== path.resolve(project.dir)) {
5456
+ if (before && path3.resolve(before.project) !== path3.resolve(project.dir)) {
4980
5457
  throw new DeployError(`${name2} was deployed from ${before.project}, not ${project.dir}. Choose another --name.`);
4981
5458
  }
4982
5459
  const firstDeploy = !before || !before.deploys.some((d) => d.local === !!o.local);
@@ -4985,7 +5462,7 @@ async function deploy(o) {
4985
5462
  name: name2,
4986
5463
  bucket: o.bucket !== void 0 ? o.bucket : before ? before.bucket : `${name2}-files`,
4987
5464
  url: before?.url ?? null,
4988
- adminToken: mint ? crypto2.randomBytes(32).toString("base64url") : before.adminToken,
5465
+ adminToken: mint ? crypto4.randomBytes(32).toString("base64url") : before.adminToken,
4989
5466
  project: project.dir,
4990
5467
  deploys: before?.deploys ?? [],
4991
5468
  // Carried, or every redeploy forgets which file was installed and replaces an edit made on the backend (measured
@@ -5011,15 +5488,16 @@ ${functions.parts.failures.map((f) => ` ${f.name}: ${f.reason}`).join("\n")}`);
5011
5488
  if (refusals.length) throw new DeployError(refusals.map(refusalSentence).join("\n"));
5012
5489
  say(` ${functions.parts.shipped.length} function(s), ${print.length} code text(s) printed.`);
5013
5490
  say("2. The site");
5014
- const siteDir = path.join(dir, "site");
5491
+ const siteDir = path3.join(dir, "site");
5015
5492
  for (const n of buildSite(project, name2, siteDir, o)) say(` ${n}`);
5016
5493
  say("3. The Worker");
5017
- const distDir = path.join(dir, "dist");
5018
- fs2.rmSync(distDir, { recursive: true, force: true });
5019
- await buildWorker(distDir, { appId: name2, appName: project.name, policy: project.policyText, automations: project.automationsText }, printCodeModule(print));
5020
- fs2.writeFileSync(path.join(dir, "wrangler.toml"), wranglerConfig({ name: name2, bucket: record.bucket, domain: o.local ? null : record.domain, alert: record.alert }));
5021
- const uploaded = [...filesUnder(siteDir), ...filesUnder(distDir)];
5022
- const mb = uploaded.reduce((n, f) => n + fs2.statSync(f).size, 0) / 1e6;
5494
+ const distDir = path3.join(dir, "dist");
5495
+ fs4.rmSync(distDir, { recursive: true, force: true });
5496
+ const how = await buildWorker(distDir, { appId: name2, appName: project.name, policy: project.policyText, automations: project.automationsText }, printCodeModule(print));
5497
+ if (how === "prebuilt") say(" the backend: the prebuilt Worker (nothing bundled on this computer); the app's code beside it");
5498
+ fs4.writeFileSync(path3.join(dir, "wrangler.toml"), wranglerConfig({ name: name2, bucket: record.bucket, domain: o.local ? null : record.domain, alert: record.alert }));
5499
+ const uploaded = [...filesUnder2(siteDir), ...filesUnder2(distDir)];
5500
+ const mb = uploaded.reduce((n, f) => n + fs4.statSync(f).size, 0) / 1e6;
5023
5501
  say(` ${uploaded.length} files to upload, ${mb.toFixed(2)} MB; files in ${record.bucket ? `the bucket ${record.bucket}` : "NO bucket (uploads are lost on a restart)"}.`);
5024
5502
  say("4. Nothing private in what is uploaded");
5025
5503
  const found = leaks(uploaded, [{ what: "the admin credential", value: record.adminToken }, ...project.envValues.map((v, i) => ({ what: `.env value ${i + 1}`, value: v }))]);
@@ -5030,18 +5508,18 @@ ${functions.parts.failures.map((f) => ` ${f.name}: ${f.reason}`).join("\n")}`);
5030
5508
  say(`Dry run: built in ${dir}, nothing uploaded.`);
5031
5509
  return 0;
5032
5510
  }
5033
- say(`5. ${o.local ? "wrangler dev" : "wrangler deploy"}`);
5034
5511
  if (o.local) {
5512
+ say("5. wrangler dev");
5035
5513
  const port = o.port || 8787;
5036
- fs2.writeFileSync(path.join(dir, ".dev.vars"), `NODEGX_ADMIN_TOKEN=${record.adminToken}
5514
+ fs4.writeFileSync(path3.join(dir, ".dev.vars"), `NODEGX_ADMIN_TOKEN=${record.adminToken}
5037
5515
  `, { mode: 384 });
5038
5516
  const [cmd, ...pre] = wranglerCommand();
5039
- const child = (0, import_node_child_process.spawn)(cmd, [...pre, "dev", "--config", "wrangler.toml", "--port", String(port), "--ip", "127.0.0.1", "--persist-to", path.join(dir, ".state")], {
5517
+ const child = (0, import_node_child_process.spawn)(cmd, [...pre, "dev", "--config", "wrangler.toml", "--port", String(port), "--ip", "127.0.0.1", "--persist-to", path3.join(dir, ".state")], {
5040
5518
  cwd: dir,
5041
5519
  stdio: ["ignore", "pipe", "pipe"],
5042
5520
  env: { ...process.env, WRANGLER_SEND_METRICS: "false" }
5043
5521
  });
5044
- const log = fs2.createWriteStream(path.join(dir, "wrangler-dev.log"));
5522
+ const log = fs4.createWriteStream(path3.join(dir, "wrangler-dev.log"));
5045
5523
  child.stdout.pipe(log);
5046
5524
  child.stderr.pipe(log);
5047
5525
  const base = `http://127.0.0.1:${port}`;
@@ -5052,10 +5530,65 @@ ${functions.parts.failures.map((f) => ` ${f.name}: ${f.reason}`).join("\n")}`);
5052
5530
  writeRecord(dir, record);
5053
5531
  await testAlert(base, record, dir, true);
5054
5532
  say(`
5055
- Running on workerd at ${base} (log: ${path.join(dir, "wrangler-dev.log")}). Ctrl-C stops it; its data stays in ${path.join(dir, ".state")}.`);
5533
+ Running on workerd at ${base} (log: ${path3.join(dir, "wrangler-dev.log")}). Ctrl-C stops it; its data stays in ${path3.join(dir, ".state")}.`);
5056
5534
  await new Promise((resolve2) => child.on("exit", () => resolve2()));
5057
5535
  return 0;
5058
5536
  }
5537
+ const route = await chooseRoute(o);
5538
+ let url;
5539
+ let domainAnswer = null;
5540
+ if (route.via === "api") {
5541
+ say("5. Up to Cloudflare, through its API, with your NodeGX sign-in");
5542
+ const ours = !!before?.deploys.some((d) => !d.local);
5543
+ const up = await deployThroughApi({
5544
+ token: route.token,
5545
+ account: o.account,
5546
+ name: name2,
5547
+ distDir,
5548
+ siteDir,
5549
+ bucket: record.bucket,
5550
+ firstDeploy,
5551
+ domain: record.domain ?? null,
5552
+ previousDomain: before?.domain ?? null,
5553
+ alert: record.alert ?? null,
5554
+ adminToken: record.adminToken,
5555
+ replaceSecret: mint,
5556
+ ours,
5557
+ log: (l) => say(` ${l}`),
5558
+ onWorkerUp: (at) => {
5559
+ record.url = at;
5560
+ record.deploys.push({ at: (/* @__PURE__ */ new Date()).toISOString(), url: at, local: false, via: "api" });
5561
+ writeRecord(dir, record);
5562
+ }
5563
+ });
5564
+ url = up.url;
5565
+ domainAnswer = up.domain;
5566
+ } else {
5567
+ say(`5. wrangler deploy (${route.why})`);
5568
+ url = wranglerDeploy(dir, record, firstDeploy, mint);
5569
+ record.url = url;
5570
+ record.deploys.push({ at: (/* @__PURE__ */ new Date()).toISOString(), url, local: false, via: "wrangler" });
5571
+ writeRecord(dir, record);
5572
+ }
5573
+ await waitFor(`${url}/health`, 60);
5574
+ say(`6. The project onto the backend at ${url}`);
5575
+ await applyEverything(url, record.adminToken, project, functions, firstDeploy || !!o.makeRoles, { dir, record, local: false });
5576
+ say(`
5577
+ Online: ${url}`);
5578
+ if (record.domain && route.via === "wrangler") {
5579
+ say(`And at https://${record.domain} once Cloudflare has made its certificate (a few minutes the first time).`);
5580
+ } else if (domainAnswer?.inPublicDns) {
5581
+ say(`And at https://${domainAnswer.host} (the first visit can wait a minute for Cloudflare's certificate).`);
5582
+ } else if (domainAnswer) {
5583
+ say(
5584
+ `https://${domainAnswer.host} is attached, but the world's DNS does not have it yet. Open it in a few minutes, not before: a browser that looks a name up too early remembers it as missing for up to half an hour.`
5585
+ );
5586
+ }
5587
+ await testAlert(url, record, dir);
5588
+ say(`The backend's dashboard: ${url}/_admin \u2014 its admin credential is in ${path3.join(dir, "deployment.json")} (never uploaded).`);
5589
+ return 0;
5590
+ }
5591
+ function wranglerDeploy(dir, record, firstDeploy, mint) {
5059
5592
  if (record.bucket && firstDeploy) {
5060
5593
  const made = wrangler(["r2", "bucket", "create", record.bucket], dir, { quiet: true });
5061
5594
  if (made.status !== 0 && !/already exists|already own/i.test(made.out)) {
@@ -5068,39 +5601,26 @@ ${made.out.trim()}
5068
5601
  const deployArgs = ["deploy", "--config", "wrangler.toml"];
5069
5602
  let secretsFile = null;
5070
5603
  if (mint) {
5071
- secretsFile = path.join(fs2.mkdtempSync(path.join(os.tmpdir(), "nodegx-cf-")), "secrets.json");
5072
- fs2.writeFileSync(secretsFile, JSON.stringify({ NODEGX_ADMIN_TOKEN: record.adminToken }), { mode: 384 });
5604
+ secretsFile = path3.join(fs4.mkdtempSync(path3.join(os2.tmpdir(), "nodegx-cf-")), "secrets.json");
5605
+ fs4.writeFileSync(secretsFile, JSON.stringify({ NODEGX_ADMIN_TOKEN: record.adminToken }), { mode: 384 });
5073
5606
  deployArgs.push("--secrets-file", secretsFile);
5074
5607
  }
5075
5608
  let done;
5076
5609
  try {
5077
5610
  done = wrangler(deployArgs, dir);
5078
5611
  } finally {
5079
- if (secretsFile) fs2.rmSync(path.dirname(secretsFile), { recursive: true, force: true });
5612
+ if (secretsFile) fs4.rmSync(path3.dirname(secretsFile), { recursive: true, force: true });
5080
5613
  }
5081
5614
  if (done.status !== 0) throw new DeployError("wrangler deploy failed (above). Nothing on the backend was changed.");
5082
5615
  const url = /https:\/\/[a-z0-9.-]+\.workers\.dev/.exec(done.out)?.[0] ?? record.url;
5083
5616
  if (!url) throw new DeployError("wrangler deployed, but did not say the address: deploy again to finish.");
5084
- record.url = url;
5085
- record.deploys.push({ at: (/* @__PURE__ */ new Date()).toISOString(), url, local: false });
5086
- writeRecord(dir, record);
5087
- await waitFor(`${url}/health`, 60);
5088
- say(`6. The project onto the backend at ${url}`);
5089
- await applyEverything(url, record.adminToken, project, functions, firstDeploy || !!o.makeRoles, { dir, record, local: false });
5090
- say(`
5091
- Online: ${url}`);
5092
- if (record.domain) {
5093
- say(`And at https://${record.domain} once Cloudflare has made its certificate (a few minutes the first time).`);
5094
- }
5095
- await testAlert(url, record, dir);
5096
- say(`The backend's dashboard: ${url}/_admin \u2014 its admin credential is in ${path.join(dir, "deployment.json")} (never uploaded).`);
5097
- return 0;
5617
+ return url;
5098
5618
  }
5099
5619
  async function main(argv) {
5100
5620
  try {
5101
5621
  return await deploy(parseArgs(argv));
5102
5622
  } catch (e) {
5103
- if (e instanceof DeployError || e?.name === "ApplyError") {
5623
+ if (e instanceof DeployError || e instanceof ApiDeployError || e?.name === "ApplyError") {
5104
5624
  process.stderr.write(`
5105
5625
  ${e.message}
5106
5626
  `);
@@ -5111,10 +5631,12 @@ ${e.message}
5111
5631
  }
5112
5632
  // Annotate the CommonJS export names for ESM import in node:
5113
5633
  0 && (module.exports = {
5114
- __nodegxBuildWorker,
5115
- __nodegxWranglerCommand,
5634
+ WORKER_OWN_MODULES,
5635
+ buildWorker,
5636
+ bundleWorker,
5116
5637
  deploy,
5117
5638
  leaks,
5118
5639
  main,
5119
- parseArgs
5640
+ parseArgs,
5641
+ wranglerCommand
5120
5642
  });
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nodegx-mcp-bundles",
3
- "version": "0.2.10",
3
+ "version": "0.2.11",
4
4
  "private": true,
5
5
  "description": "Build metadata for the bundled CLIs beside it. See build-cloud-bundle.mjs: @noodl/platform reads it."
6
6
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodegx/backend",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Put a NodeGX app online on your own Cloudflare account: its pages, its backend, its rules and its functions, on one Worker, the same address every time.",
5
5
  "license": "GPL-3.0-only",
6
6
  "homepage": "https://nodegx.io",
@@ -18,9 +18,7 @@
18
18
  "dist/cloudflare-domain.cjs",
19
19
  "dist/cloud-bundle.cjs",
20
20
  "dist/package.json",
21
- "dist/scripts",
22
21
  "dist/worker",
23
- "src/prebuilt-worker.cjs",
24
22
  "README.md",
25
23
  "LICENSE"
26
24
  ],
@@ -1,2 +0,0 @@
1
- // The backend build settings the installed deploy reads (see build.mjs): only the banner, empty; the prebuilt Worker has the real one.
2
- module.exports = { shared: { banner: { js: '' } } };
@@ -1,24 +0,0 @@
1
- /**
2
- * What `require('esbuild')` is inside the INSTALLED deploy (`dist/cloudflare-deploy.cjs`; `build.mjs` aliases it).
3
- *
4
- * The deploy calls esbuild once, to bundle the Worker (`worker.ts` and the whole backend). Nothing in that bundle is
5
- * the app's own (the app's two modules stay imports), so the pack built it already (`dist/worker/worker.mjs`), and
6
- * this "build" copies it to where the deploy asked. Any other build is a refusal that names this file: an install
7
- * has no esbuild and no backend source.
8
- */
9
- 'use strict';
10
-
11
- const fs = require('fs');
12
- const path = require('path');
13
-
14
- exports.build = async function build(options) {
15
- const entry = String((options && options.entryPoints && options.entryPoints[0]) || '');
16
- const prebuilt = process.env.NODEGX_CLOUDFLARE_WORKER;
17
- if (path.basename(entry) !== 'worker.ts' || !prebuilt) {
18
- throw new Error(`@nodegx/backend bundles nothing at deploy time (asked for ${entry || 'no entry'}); see src/prebuilt-worker.cjs.`);
19
- }
20
- if (!fs.existsSync(prebuilt)) throw new Error(`The prebuilt Worker is not here (${prebuilt}): this install is incomplete.`);
21
- fs.mkdirSync(path.dirname(options.outfile), { recursive: true });
22
- fs.copyFileSync(prebuilt, options.outfile);
23
- return { errors: [], warnings: [] };
24
- };