@nodegx/backend 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/nodegx-online.js +4 -3
- package/dist/cloud-bundle.cjs +38 -2
- package/dist/cloudflare-deploy.cjs +720 -159
- package/dist/package.json +1 -1
- package/package.json +1 -3
- package/dist/scripts/build.js +0 -2
- package/src/prebuilt-worker.cjs +0 -24
package/bin/nodegx-online.js
CHANGED
|
@@ -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
|
|
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,9 +74,10 @@ 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 {
|
|
78
|
-
const [cmd, ...pre] =
|
|
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
|
+
if (run.error) process.stderr.write(`@nodegx/backend: wrangler could not be started (${[cmd, ...pre].join(' ')}: ${run.error.code || run.error.message}).\n`);
|
|
80
81
|
return run.status ?? 1;
|
|
81
82
|
}
|
|
82
83
|
|
package/dist/cloud-bundle.cjs
CHANGED
|
@@ -28418,6 +28418,20 @@ var init_node_catalog = __esm({
|
|
|
28418
28418
|
valueType: "signal",
|
|
28419
28419
|
example: "changed-Sa1"
|
|
28420
28420
|
},
|
|
28421
|
+
{
|
|
28422
|
+
pattern: "changed-createdAt",
|
|
28423
|
+
plug: "output",
|
|
28424
|
+
group: "Events",
|
|
28425
|
+
valueType: "signal",
|
|
28426
|
+
example: "changed-createdAt"
|
|
28427
|
+
},
|
|
28428
|
+
{
|
|
28429
|
+
pattern: "changed-updatedAt",
|
|
28430
|
+
plug: "output",
|
|
28431
|
+
group: "Events",
|
|
28432
|
+
valueType: "signal",
|
|
28433
|
+
example: "changed-updatedAt"
|
|
28434
|
+
},
|
|
28421
28435
|
{
|
|
28422
28436
|
pattern: "collectionName",
|
|
28423
28437
|
plug: "input",
|
|
@@ -28434,6 +28448,20 @@ var init_node_catalog = __esm({
|
|
|
28434
28448
|
group: "Properties",
|
|
28435
28449
|
valueType: "string",
|
|
28436
28450
|
example: "prop-Sa1"
|
|
28451
|
+
},
|
|
28452
|
+
{
|
|
28453
|
+
pattern: "prop-createdAt",
|
|
28454
|
+
plug: "output",
|
|
28455
|
+
group: "Properties",
|
|
28456
|
+
valueType: "date",
|
|
28457
|
+
example: "prop-createdAt"
|
|
28458
|
+
},
|
|
28459
|
+
{
|
|
28460
|
+
pattern: "prop-updatedAt",
|
|
28461
|
+
plug: "output",
|
|
28462
|
+
group: "Properties",
|
|
28463
|
+
valueType: "date",
|
|
28464
|
+
example: "prop-updatedAt"
|
|
28437
28465
|
}
|
|
28438
28466
|
]
|
|
28439
28467
|
},
|
|
@@ -144602,7 +144630,7 @@ var init_cloud_node_library = __esm({
|
|
|
144602
144630
|
plug: "output",
|
|
144603
144631
|
group: "Events",
|
|
144604
144632
|
displayName: "Fetched",
|
|
144605
|
-
description: "Fires when the Id binds a record
|
|
144633
|
+
description: "Fires when the Id binds a record already in memory, when a record the Id names is first read from the backend, and when a Fetch finishes reading it; use Done to act on the answer to a Fetch"
|
|
144606
144634
|
},
|
|
144607
144635
|
{
|
|
144608
144636
|
name: "changed",
|
|
@@ -144778,6 +144806,14 @@ var init_cloud_node_library = __esm({
|
|
|
144778
144806
|
displayName: "Only If Unchanged",
|
|
144779
144807
|
description: "Property names, comma-separated (e.g. version). The update is applied only if these still hold the values the record had when it was read; otherwise Failure fires and nothing is written. Fetch the record again before retrying. Needs a NodeGX backend. Leave empty to always write."
|
|
144780
144808
|
},
|
|
144809
|
+
{
|
|
144810
|
+
name: "addTo",
|
|
144811
|
+
type: "string",
|
|
144812
|
+
plug: "input",
|
|
144813
|
+
group: "General",
|
|
144814
|
+
displayName: "Add To",
|
|
144815
|
+
description: "Property names, comma-separated (e.g. points). For these, the value wired in is an amount added to what the backend holds, in one step on the backend, instead of replacing it: two devices adding at once both count. Wire the amount (1, -1, 5). The record then shows the backend's total. Leave empty to write every value as given."
|
|
144816
|
+
},
|
|
144781
144817
|
{
|
|
144782
144818
|
name: "idSource",
|
|
144783
144819
|
type: {
|
|
@@ -151647,7 +151683,7 @@ var init_cloud_node_library = __esm({
|
|
|
151647
151683
|
},
|
|
151648
151684
|
{
|
|
151649
151685
|
name: "userId",
|
|
151650
|
-
type: "
|
|
151686
|
+
type: "string",
|
|
151651
151687
|
plug: "output",
|
|
151652
151688
|
group: "Request",
|
|
151653
151689
|
displayName: "User Id",
|
|
@@ -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
|
|
254
|
+
var path5 = name2.split(".");
|
|
255
255
|
var model = this;
|
|
256
|
-
for (var i = 0; i <
|
|
257
|
-
var v = model.get(
|
|
256
|
+
for (var i = 0; i < path5.length - 1; i++) {
|
|
257
|
+
var v = model.get(path5[i]);
|
|
258
258
|
if (Model2.instanceOf(v)) model = v;
|
|
259
259
|
else return;
|
|
260
260
|
}
|
|
261
|
-
model.set(
|
|
261
|
+
model.set(path5[path5.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
|
|
274
|
+
var path5 = name2.split(".");
|
|
275
275
|
var model = this;
|
|
276
|
-
for (var i = 0; i <
|
|
277
|
-
var v = model.get(
|
|
276
|
+
for (var i = 0; i < path5.length - 1; i++) {
|
|
277
|
+
var v = model.get(path5[i]);
|
|
278
278
|
if (Model2.instanceOf(v)) model = v;
|
|
279
279
|
else return;
|
|
280
280
|
}
|
|
281
|
-
return model.get(
|
|
281
|
+
return model.get(path5[path5.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
|
-
|
|
3754
|
-
|
|
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
|
|
3763
|
-
var
|
|
3764
|
-
var
|
|
3765
|
-
var
|
|
3744
|
+
var crypto4 = __toESM(require("node:crypto"));
|
|
3745
|
+
var fs5 = __toESM(require("node:fs"));
|
|
3746
|
+
var os2 = __toESM(require("node:os"));
|
|
3747
|
+
var path4 = __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,
|
|
4336
|
-
const answer = await call(method,
|
|
4317
|
+
async function must(call, method, path5, body) {
|
|
4318
|
+
const answer = await call(method, path5, body);
|
|
4337
4319
|
if (answer.status >= 300) {
|
|
4338
4320
|
const said = answer.json?.error ?? answer.text.slice(0, 600);
|
|
4339
|
-
throw new ApplyError(`${method} /${
|
|
4321
|
+
throw new ApplyError(`${method} /${path5.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,
|
|
4441
|
-
const answer = await call(method,
|
|
4422
|
+
async function must2(call, method, path5, body) {
|
|
4423
|
+
const answer = await call(method, path5, body);
|
|
4442
4424
|
if (answer.status >= 300) {
|
|
4443
4425
|
const said = answer.json?.error ?? answer.text.slice(0, 600);
|
|
4444
|
-
throw new ApplyError(`${method} /${
|
|
4426
|
+
throw new ApplyError(`${method} /${path5.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).`;
|
|
@@ -4655,16 +5088,59 @@ function wranglerConfig(input2) {
|
|
|
4655
5088
|
return lines.join("\n");
|
|
4656
5089
|
}
|
|
4657
5090
|
|
|
5091
|
+
// ../nodegx-backend/cloudflare/wranglerSpawn.ts
|
|
5092
|
+
var fs4 = __toESM(require("node:fs"));
|
|
5093
|
+
var path3 = __toESM(require("node:path"));
|
|
5094
|
+
var NPX_WRANGLER = ["--yes", "wrangler@4"];
|
|
5095
|
+
function windowsNpxCli(host) {
|
|
5096
|
+
const p = path3.win32;
|
|
5097
|
+
const candidates = [p.join(p.dirname(host.execPath), "node_modules", "npm", "bin", "npx-cli.js")];
|
|
5098
|
+
const npm = host.env.npm_execpath;
|
|
5099
|
+
if (npm && /npm-cli\.js$/i.test(npm)) candidates.push(p.join(p.dirname(npm), "npx-cli.js"));
|
|
5100
|
+
return candidates.find((f) => host.exists(f)) ?? null;
|
|
5101
|
+
}
|
|
5102
|
+
function wranglerCommandFor(host) {
|
|
5103
|
+
if (host.env.NODEGX_WRANGLER) return [host.execPath, host.env.NODEGX_WRANGLER];
|
|
5104
|
+
for (const from of host.from) {
|
|
5105
|
+
try {
|
|
5106
|
+
return [host.execPath, host.resolve("wrangler/bin/wrangler.js", from)];
|
|
5107
|
+
} catch {
|
|
5108
|
+
}
|
|
5109
|
+
}
|
|
5110
|
+
if (host.platform === "win32") {
|
|
5111
|
+
const cli = windowsNpxCli(host);
|
|
5112
|
+
if (cli) return [host.execPath, cli, ...NPX_WRANGLER];
|
|
5113
|
+
}
|
|
5114
|
+
return ["npx", ...NPX_WRANGLER];
|
|
5115
|
+
}
|
|
5116
|
+
function realHost(from) {
|
|
5117
|
+
return {
|
|
5118
|
+
env: process.env,
|
|
5119
|
+
platform: process.platform,
|
|
5120
|
+
execPath: process.execPath,
|
|
5121
|
+
from,
|
|
5122
|
+
resolve: (request, dir) => require.resolve(request, { paths: [dir] }),
|
|
5123
|
+
exists: (f) => fs4.existsSync(f)
|
|
5124
|
+
};
|
|
5125
|
+
}
|
|
5126
|
+
function spawnFailure(command, error) {
|
|
5127
|
+
if (!error) return null;
|
|
5128
|
+
const code = error.code;
|
|
5129
|
+
return `wrangler could not be started (${command.join(" ")}: ${code || error.message}). Install it with \`npm install -g wrangler@4\` and point the deploy at it with NODEGX_WRANGLER set to its bin/wrangler.js.`;
|
|
5130
|
+
}
|
|
5131
|
+
|
|
4658
5132
|
// ../nodegx-backend/cloudflare/deployCloudflare.ts
|
|
4659
5133
|
var HERE = process.env.NODEGX_CLOUDFLARE_SRC || __dirname;
|
|
4660
|
-
var PACKAGES =
|
|
5134
|
+
var PACKAGES = path4.resolve(HERE, "..", "..");
|
|
4661
5135
|
var DeployError = class extends Error {
|
|
4662
5136
|
};
|
|
4663
5137
|
var say = (line = "") => process.stdout.write(line + "\n");
|
|
4664
|
-
var
|
|
5138
|
+
var PROGRAM = process.env.NODEGX_CLOUDFLARE_COMMAND || "deploy.mjs";
|
|
5139
|
+
var USAGE = `usage: ${PROGRAM} <project> [--name <worker>] [--bucket <r2 bucket> | --no-bucket] [--viewer <folder>]
|
|
4665
5140
|
[--allow-development-engine] [--out <folder>] [--local [--port <n>]] [--make-roles]
|
|
4666
5141
|
[--new-admin-credential] [--dry-run] [--domain <hostname> | --no-domain]
|
|
4667
|
-
[--alert-to <address> --alert-from <address on your Cloudflare domain> | --no-alert]
|
|
5142
|
+
[--alert-to <address> --alert-from <address on your Cloudflare domain> | --no-alert]
|
|
5143
|
+
[--wrangler] [--account <id>]`;
|
|
4668
5144
|
function parseArgs(argv) {
|
|
4669
5145
|
const o = { project: "" };
|
|
4670
5146
|
for (let i = 0; i < argv.length; i++) {
|
|
@@ -4678,9 +5154,9 @@ ${USAGE}`);
|
|
|
4678
5154
|
if (a === "--name") o.name = next();
|
|
4679
5155
|
else if (a === "--bucket") o.bucket = next();
|
|
4680
5156
|
else if (a === "--no-bucket") o.bucket = null;
|
|
4681
|
-
else if (a === "--viewer") o.viewer =
|
|
5157
|
+
else if (a === "--viewer") o.viewer = path4.resolve(next());
|
|
4682
5158
|
else if (a === "--allow-development-engine") o.allowDevelopmentEngine = true;
|
|
4683
|
-
else if (a === "--out") o.out =
|
|
5159
|
+
else if (a === "--out") o.out = path4.resolve(next());
|
|
4684
5160
|
else if (a === "--local") o.local = true;
|
|
4685
5161
|
else if (a === "--port") o.port = Number(next());
|
|
4686
5162
|
else if (a === "--make-roles") o.makeRoles = true;
|
|
@@ -4691,9 +5167,11 @@ ${USAGE}`);
|
|
|
4691
5167
|
else if (a === "--alert-to") o.alertTo = next().trim();
|
|
4692
5168
|
else if (a === "--alert-from") o.alertFrom = next().trim();
|
|
4693
5169
|
else if (a === "--no-alert") o.alertTo = o.alertFrom = null;
|
|
5170
|
+
else if (a === "--wrangler") o.wrangler = true;
|
|
5171
|
+
else if (a === "--account") o.account = next().trim();
|
|
4694
5172
|
else if (a.startsWith("--")) throw new DeployError(`${a} is not an option.
|
|
4695
5173
|
${USAGE}`);
|
|
4696
|
-
else if (!o.project) o.project =
|
|
5174
|
+
else if (!o.project) o.project = path4.resolve(a);
|
|
4697
5175
|
else throw new DeployError(`One project at a time.
|
|
4698
5176
|
${USAGE}`);
|
|
4699
5177
|
}
|
|
@@ -4701,20 +5179,20 @@ ${USAGE}`);
|
|
|
4701
5179
|
return o;
|
|
4702
5180
|
}
|
|
4703
5181
|
function readProject(dir) {
|
|
4704
|
-
const file =
|
|
4705
|
-
if (!
|
|
4706
|
-
const json = JSON.parse(
|
|
4707
|
-
const policyFile =
|
|
4708
|
-
const policyText =
|
|
5182
|
+
const file = path4.join(dir, "nodegx.project.json");
|
|
5183
|
+
if (!fs5.existsSync(file)) throw new DeployError(`${dir} is not a NodeGX project: it has no nodegx.project.json.`);
|
|
5184
|
+
const json = JSON.parse(fs5.readFileSync(file, "utf8"));
|
|
5185
|
+
const policyFile = path4.join(dir, "nodegx.security.json");
|
|
5186
|
+
const policyText = fs5.existsSync(policyFile) ? fs5.readFileSync(policyFile, "utf8") : null;
|
|
4709
5187
|
if (policyText) JSON.parse(policyText);
|
|
4710
|
-
const automationsFile =
|
|
4711
|
-
const automationsText =
|
|
5188
|
+
const automationsFile = path4.join(dir, "nodegx.automations.json");
|
|
5189
|
+
const automationsText = fs5.existsSync(automationsFile) ? fs5.readFileSync(automationsFile, "utf8") : null;
|
|
4712
5190
|
if (automationsText) JSON.parse(automationsText);
|
|
4713
|
-
const envFile =
|
|
4714
|
-
const envValues =
|
|
5191
|
+
const envFile = path4.join(dir, ".env");
|
|
5192
|
+
const envValues = fs5.existsSync(envFile) ? fs5.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
5193
|
return {
|
|
4716
5194
|
dir,
|
|
4717
|
-
name: json.name ||
|
|
5195
|
+
name: json.name || path4.basename(dir),
|
|
4718
5196
|
file: json,
|
|
4719
5197
|
policyText,
|
|
4720
5198
|
automationsText,
|
|
@@ -4723,20 +5201,20 @@ function readProject(dir) {
|
|
|
4723
5201
|
};
|
|
4724
5202
|
}
|
|
4725
5203
|
function deploymentsRoot() {
|
|
4726
|
-
return process.env.NODEGX_CLOUDFLARE_HOME ||
|
|
5204
|
+
return process.env.NODEGX_CLOUDFLARE_HOME || path4.join(os2.homedir(), ".nodegx", "cloudflare");
|
|
4727
5205
|
}
|
|
4728
5206
|
function readRecord(dir) {
|
|
4729
|
-
const file =
|
|
4730
|
-
return
|
|
5207
|
+
const file = path4.join(dir, "deployment.json");
|
|
5208
|
+
return fs5.existsSync(file) ? JSON.parse(fs5.readFileSync(file, "utf8")) : null;
|
|
4731
5209
|
}
|
|
4732
5210
|
function writeRecord(dir, record) {
|
|
4733
|
-
const file =
|
|
4734
|
-
|
|
4735
|
-
|
|
5211
|
+
const file = path4.join(dir, "deployment.json");
|
|
5212
|
+
fs5.writeFileSync(file, JSON.stringify(record, null, 2) + "\n", { mode: 384 });
|
|
5213
|
+
fs5.chmodSync(file, 384);
|
|
4736
5214
|
}
|
|
4737
5215
|
function cloudFunctions(projectDir) {
|
|
4738
|
-
const entry = process.env.NODEGX_CLOUD_BUNDLE ||
|
|
4739
|
-
if (!
|
|
5216
|
+
const entry = process.env.NODEGX_CLOUD_BUNDLE || path4.join(PACKAGES, "noodl-mcp", "dist", "cloud-bundle.cjs");
|
|
5217
|
+
if (!fs5.existsSync(entry)) {
|
|
4740
5218
|
throw new DeployError(`The cloud-function bundler is not here (${entry}): run \`npm run build\` in packages/noodl-mcp.`);
|
|
4741
5219
|
}
|
|
4742
5220
|
const run = (0, import_node_child_process.spawnSync)(process.execPath, [entry, projectDir], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, timeout: 12e4 });
|
|
@@ -4745,61 +5223,85 @@ ${(run.stderr || "").trim() || "no output"}`);
|
|
|
4745
5223
|
return JSON.parse(run.stdout);
|
|
4746
5224
|
}
|
|
4747
5225
|
var NOT_FOR_THE_HOST = ["DEPLOY.md", "serve.js", "package.json", ".nodegx-deploy.json", "nodegx-config.json"];
|
|
5226
|
+
var VIEWER_HINT = "\nName a production viewer with --viewer <folder holding noodl.deploy.js>.";
|
|
5227
|
+
function siteThroughCli(copy, out, allowDev) {
|
|
5228
|
+
const cli = process.env.NODEGX_CLI || path4.join(PACKAGES, "nodegx-export", "dist", "cli.mjs");
|
|
5229
|
+
if (!process.env.NODEGX_CLI && process.env.NODEGX_DEPLOY_CLI && !fs5.existsSync(cli)) return null;
|
|
5230
|
+
const args = [cli, "deploy", copy, out];
|
|
5231
|
+
if (allowDev) args.push("--allow-development-engine");
|
|
5232
|
+
const run = (0, import_node_child_process.spawnSync)(process.execPath, args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
|
|
5233
|
+
if (run.status !== 0) {
|
|
5234
|
+
throw new DeployError(`\`nodegx deploy\` refused (${run.status}):
|
|
5235
|
+
${(run.stdout + run.stderr).trim()}` + (run.status === 11 ? VIEWER_HINT : ""));
|
|
5236
|
+
}
|
|
5237
|
+
return run.stdout.split("\n").filter((l) => / deployed to |left out|excluded|engine/i.test(l)).map((l) => l.trim());
|
|
5238
|
+
}
|
|
5239
|
+
function siteThroughEngine(copy, out, allowDev) {
|
|
5240
|
+
const engine = process.env.NODEGX_DEPLOY_CLI;
|
|
5241
|
+
if (!fs5.existsSync(engine)) throw new DeployError(`NODEGX_DEPLOY_CLI is set to ${engine}, and there is nothing there.`);
|
|
5242
|
+
const args = [engine, copy, out];
|
|
5243
|
+
if (allowDev) args.push("--allow-development-engine");
|
|
5244
|
+
const run = (0, import_node_child_process.spawnSync)(process.execPath, args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
|
|
5245
|
+
const last = (run.stdout || "").trim().split("\n").pop() || "";
|
|
5246
|
+
let report;
|
|
5247
|
+
try {
|
|
5248
|
+
report = JSON.parse(last);
|
|
5249
|
+
} catch {
|
|
5250
|
+
throw new DeployError(`The site's deploy engine gave no report (${run.status}):
|
|
5251
|
+
${(run.stderr || "").trim().slice(-2e3) || "no output"}`);
|
|
5252
|
+
}
|
|
5253
|
+
if (report.ok !== true) {
|
|
5254
|
+
throw new DeployError(`The site's deploy engine refused (${report.stage}): ${report.message ?? "no reason given"}` + (report.stage === "engine" ? VIEWER_HINT : ""));
|
|
5255
|
+
}
|
|
5256
|
+
if (report.blank) throw new DeployError(`This deploy would ship a blank site, so it stops here.
|
|
5257
|
+
${report.blank}`);
|
|
5258
|
+
const notes = [`${report.projectName ?? "project"} deployed to ${out} \u2014 ${(report.files ?? []).length} entries`];
|
|
5259
|
+
if (report.engine) notes.push(`engine: ${report.engine.kind} build of the NodeGX viewer, ${(report.engine.bytes / 1e6).toFixed(2)} MB`);
|
|
5260
|
+
for (const w of report.warnings ?? []) notes.push(`! ${w}`);
|
|
5261
|
+
if (report.excluded?.length) notes.push(`${report.excluded.length} project file(s) left out: ${report.excluded.slice(0, 5).map((e) => e.path).join(", ")}`);
|
|
5262
|
+
return notes;
|
|
5263
|
+
}
|
|
4748
5264
|
function buildSite(project, name2, siteDir, o) {
|
|
4749
|
-
const work =
|
|
5265
|
+
const work = fs5.mkdtempSync(path4.join(os2.tmpdir(), "nodegx-cf-site-"));
|
|
4750
5266
|
try {
|
|
4751
|
-
const copy =
|
|
4752
|
-
|
|
4753
|
-
const json = JSON.parse(
|
|
5267
|
+
const copy = path4.join(work, "project");
|
|
5268
|
+
fs5.cpSync(project.dir, copy, { recursive: true, filter: (src) => !/[/\\](\.git|node_modules|\.previews)$/.test(src) });
|
|
5269
|
+
const json = JSON.parse(fs5.readFileSync(path4.join(copy, "nodegx.project.json"), "utf8"));
|
|
4754
5270
|
json.metadata = { ...json.metadata || {}, cloudservices: { endpoint: "", appId: name2, instanceId: name2, type: "nodegx" } };
|
|
4755
|
-
|
|
4756
|
-
const out =
|
|
4757
|
-
const
|
|
4758
|
-
const
|
|
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());
|
|
5271
|
+
fs5.writeFileSync(path4.join(copy, "nodegx.project.json"), JSON.stringify(json, null, 2));
|
|
5272
|
+
const out = path4.join(work, "site");
|
|
5273
|
+
const allowDev = !!(o.viewer || o.allowDevelopmentEngine);
|
|
5274
|
+
const notes = siteThroughCli(copy, out, allowDev) ?? siteThroughEngine(copy, out, allowDev);
|
|
4768
5275
|
if (o.viewer) {
|
|
4769
5276
|
for (const f of ["noodl.deploy.js", "noodl.deploy.js.LICENSE.txt"]) {
|
|
4770
|
-
const from =
|
|
4771
|
-
if (
|
|
5277
|
+
const from = path4.join(o.viewer, f);
|
|
5278
|
+
if (fs5.existsSync(from)) fs5.copyFileSync(from, path4.join(out, f));
|
|
4772
5279
|
else if (f === "noodl.deploy.js") throw new DeployError(`--viewer ${o.viewer} holds no noodl.deploy.js.`);
|
|
4773
5280
|
}
|
|
4774
|
-
const engine = readViewerBuild(
|
|
5281
|
+
const engine = readViewerBuild(path4.join(out, "noodl.deploy.js"));
|
|
4775
5282
|
if (engine.kind !== "production") {
|
|
4776
5283
|
throw new DeployError(`--viewer ${o.viewer} is a DEVELOPMENT build of the viewer: ${engine.reasons.join("; ")}.`);
|
|
4777
5284
|
}
|
|
4778
5285
|
notes.push(`viewer: production, from ${o.viewer} (${(engine.bytes / 1e6).toFixed(2)} MB)`);
|
|
4779
5286
|
}
|
|
4780
|
-
for (const f of NOT_FOR_THE_HOST)
|
|
4781
|
-
const hidden =
|
|
4782
|
-
for (const f of hidden)
|
|
4783
|
-
if (hidden.length) notes.push(`left out (hidden files are never published): ${hidden.map((f) =>
|
|
4784
|
-
|
|
4785
|
-
|
|
5287
|
+
for (const f of NOT_FOR_THE_HOST) fs5.rmSync(path4.join(out, f), { force: true });
|
|
5288
|
+
const hidden = filesUnder2(out).filter((f) => path4.relative(out, f).split(path4.sep).some((part) => part.startsWith(".")));
|
|
5289
|
+
for (const f of hidden) fs5.rmSync(f, { force: true });
|
|
5290
|
+
if (hidden.length) notes.push(`left out (hidden files are never published): ${hidden.map((f) => path4.relative(out, f)).join(", ")}`);
|
|
5291
|
+
fs5.rmSync(siteDir, { recursive: true, force: true });
|
|
5292
|
+
fs5.cpSync(out, siteDir, { recursive: true });
|
|
4786
5293
|
return notes;
|
|
4787
5294
|
} finally {
|
|
4788
|
-
|
|
5295
|
+
fs5.rmSync(work, { recursive: true, force: true });
|
|
4789
5296
|
}
|
|
4790
5297
|
}
|
|
4791
|
-
async function
|
|
4792
|
-
const
|
|
4793
|
-
const
|
|
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");
|
|
5298
|
+
async function bundleWorker(outfile, plugins = [], esbuild = require("esbuild")) {
|
|
5299
|
+
const { shared } = require(path4.join(HERE, "..", "scripts", "build.js"));
|
|
5300
|
+
const nodeSqlite = path4.join(HERE, "nodeSqlite.ts");
|
|
4799
5301
|
await esbuild.build({
|
|
4800
5302
|
...shared,
|
|
4801
|
-
entryPoints: [
|
|
4802
|
-
outfile
|
|
5303
|
+
entryPoints: [path4.join(HERE, "worker.ts")],
|
|
5304
|
+
outfile,
|
|
4803
5305
|
format: "esm",
|
|
4804
5306
|
target: "es2022",
|
|
4805
5307
|
sourcemap: false,
|
|
@@ -4819,46 +5321,56 @@ async function buildWorker(distDir, app, printed) {
|
|
|
4819
5321
|
b.onResolve({ filter: /^\.\/(printed-code|app)\.mjs$/ }, (a) => ({ path: a.path, external: true }));
|
|
4820
5322
|
b.onResolve({ filter: /^node:sqlite$/ }, () => ({ path: nodeSqlite }));
|
|
4821
5323
|
}
|
|
4822
|
-
}
|
|
5324
|
+
},
|
|
5325
|
+
...plugins
|
|
4823
5326
|
]
|
|
4824
5327
|
});
|
|
4825
5328
|
}
|
|
4826
|
-
|
|
5329
|
+
var WORKER_OWN_MODULES = ["./printed-code.mjs", "./app.mjs"];
|
|
5330
|
+
async function buildWorker(distDir, app, printed) {
|
|
5331
|
+
fs5.mkdirSync(distDir, { recursive: true });
|
|
5332
|
+
fs5.writeFileSync(path4.join(distDir, "printed-code.mjs"), printed);
|
|
5333
|
+
fs5.writeFileSync(path4.join(distDir, "app.mjs"), `export default ${JSON.stringify(app)};
|
|
5334
|
+
`);
|
|
5335
|
+
const prebuilt = process.env.NODEGX_CLOUDFLARE_WORKER;
|
|
5336
|
+
if (prebuilt) {
|
|
5337
|
+
if (!fs5.existsSync(prebuilt)) throw new DeployError(`The prebuilt Worker is not here (${prebuilt}): this copy of the deploy is incomplete.`);
|
|
5338
|
+
fs5.copyFileSync(prebuilt, path4.join(distDir, "worker.mjs"));
|
|
5339
|
+
return "prebuilt";
|
|
5340
|
+
}
|
|
5341
|
+
await bundleWorker(path4.join(distDir, "worker.mjs"));
|
|
5342
|
+
return "bundled";
|
|
5343
|
+
}
|
|
5344
|
+
function filesUnder2(dir) {
|
|
4827
5345
|
const out = [];
|
|
4828
5346
|
const walk = (d) => {
|
|
4829
|
-
for (const e of
|
|
4830
|
-
const full =
|
|
5347
|
+
for (const e of fs5.readdirSync(d, { withFileTypes: true })) {
|
|
5348
|
+
const full = path4.join(d, e.name);
|
|
4831
5349
|
if (e.isDirectory()) walk(full);
|
|
4832
5350
|
else out.push(full);
|
|
4833
5351
|
}
|
|
4834
5352
|
};
|
|
4835
|
-
if (
|
|
5353
|
+
if (fs5.existsSync(dir)) walk(dir);
|
|
4836
5354
|
return out;
|
|
4837
5355
|
}
|
|
4838
5356
|
function leaks(files, secrets) {
|
|
4839
5357
|
const found = [];
|
|
4840
5358
|
for (const f of files) {
|
|
4841
|
-
const text =
|
|
5359
|
+
const text = fs5.readFileSync(f, "latin1");
|
|
4842
5360
|
for (const s of secrets) if (s.value && text.includes(s.value)) found.push(`${s.what} is in ${f}`);
|
|
4843
5361
|
}
|
|
4844
5362
|
return found;
|
|
4845
5363
|
}
|
|
4846
5364
|
function wranglerCommand() {
|
|
4847
|
-
|
|
4848
|
-
for (const from of [process.cwd(), HERE]) {
|
|
4849
|
-
try {
|
|
4850
|
-
return [process.execPath, require.resolve("wrangler/bin/wrangler.js", { paths: [from] })];
|
|
4851
|
-
} catch {
|
|
4852
|
-
}
|
|
4853
|
-
}
|
|
4854
|
-
return ["npx", "--yes", "wrangler@4"];
|
|
5365
|
+
return wranglerCommandFor(realHost([process.cwd(), HERE]));
|
|
4855
5366
|
}
|
|
4856
5367
|
function wrangler(args, cwd, opts = {}) {
|
|
4857
5368
|
const [cmd, ...pre] = wranglerCommand();
|
|
4858
5369
|
const run = (0, import_node_child_process.spawnSync)(cmd, [...pre, ...args], { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, env: { ...process.env, WRANGLER_SEND_METRICS: "false" } });
|
|
4859
|
-
const
|
|
5370
|
+
const unstarted = spawnFailure([cmd, ...pre], run.error);
|
|
5371
|
+
const out = unstarted ?? `${run.stdout || ""}${run.stderr || ""}`;
|
|
4860
5372
|
if (!opts.quiet) process.stdout.write(out.split("\n").map((l) => l ? ` \u2502 ${l}` : l).join("\n") + "\n");
|
|
4861
|
-
return { status: run.status ?? 1, out };
|
|
5373
|
+
return { status: run.status ?? 1, out, started: !unstarted };
|
|
4862
5374
|
}
|
|
4863
5375
|
async function waitFor(url, seconds) {
|
|
4864
5376
|
const until = Date.now() + seconds * 1e3;
|
|
@@ -4919,8 +5431,8 @@ async function applyEverything(base, token, project, functions, makeRoles, where
|
|
|
4919
5431
|
const target = where.local ? "local" : "live";
|
|
4920
5432
|
const automations = await applyAutomations(call, project.automationsText, { installedSha256: where.record.automations?.[target] ?? null });
|
|
4921
5433
|
if (automations.before) {
|
|
4922
|
-
const kept =
|
|
4923
|
-
|
|
5434
|
+
const kept = path4.join(where.dir, `automations.before-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
|
|
5435
|
+
fs5.writeFileSync(kept, JSON.stringify(automations.before, null, 2) + "\n");
|
|
4924
5436
|
automations.lines.push(`The backend's previous ones are kept in ${kept}.`);
|
|
4925
5437
|
}
|
|
4926
5438
|
for (const l of automations.lines) say(` ${l}`);
|
|
@@ -4973,10 +5485,10 @@ async function deploy(o) {
|
|
|
4973
5485
|
const name2 = o.name || (o.out ? readRecord(o.out)?.name : void 0) || workerNameFrom(project.name);
|
|
4974
5486
|
const problem = workerNameProblem(name2);
|
|
4975
5487
|
if (problem) throw new DeployError(problem);
|
|
4976
|
-
const dir = o.out ||
|
|
4977
|
-
|
|
5488
|
+
const dir = o.out || path4.join(root, name2);
|
|
5489
|
+
fs5.mkdirSync(dir, { recursive: true });
|
|
4978
5490
|
const before = readRecord(dir);
|
|
4979
|
-
if (before &&
|
|
5491
|
+
if (before && path4.resolve(before.project) !== path4.resolve(project.dir)) {
|
|
4980
5492
|
throw new DeployError(`${name2} was deployed from ${before.project}, not ${project.dir}. Choose another --name.`);
|
|
4981
5493
|
}
|
|
4982
5494
|
const firstDeploy = !before || !before.deploys.some((d) => d.local === !!o.local);
|
|
@@ -4985,7 +5497,7 @@ async function deploy(o) {
|
|
|
4985
5497
|
name: name2,
|
|
4986
5498
|
bucket: o.bucket !== void 0 ? o.bucket : before ? before.bucket : `${name2}-files`,
|
|
4987
5499
|
url: before?.url ?? null,
|
|
4988
|
-
adminToken: mint ?
|
|
5500
|
+
adminToken: mint ? crypto4.randomBytes(32).toString("base64url") : before.adminToken,
|
|
4989
5501
|
project: project.dir,
|
|
4990
5502
|
deploys: before?.deploys ?? [],
|
|
4991
5503
|
// Carried, or every redeploy forgets which file was installed and replaces an edit made on the backend (measured
|
|
@@ -5011,15 +5523,16 @@ ${functions.parts.failures.map((f) => ` ${f.name}: ${f.reason}`).join("\n")}`);
|
|
|
5011
5523
|
if (refusals.length) throw new DeployError(refusals.map(refusalSentence).join("\n"));
|
|
5012
5524
|
say(` ${functions.parts.shipped.length} function(s), ${print.length} code text(s) printed.`);
|
|
5013
5525
|
say("2. The site");
|
|
5014
|
-
const siteDir =
|
|
5526
|
+
const siteDir = path4.join(dir, "site");
|
|
5015
5527
|
for (const n of buildSite(project, name2, siteDir, o)) say(` ${n}`);
|
|
5016
5528
|
say("3. The Worker");
|
|
5017
|
-
const distDir =
|
|
5018
|
-
|
|
5019
|
-
await buildWorker(distDir, { appId: name2, appName: project.name, policy: project.policyText, automations: project.automationsText }, printCodeModule(print));
|
|
5020
|
-
|
|
5021
|
-
|
|
5022
|
-
const
|
|
5529
|
+
const distDir = path4.join(dir, "dist");
|
|
5530
|
+
fs5.rmSync(distDir, { recursive: true, force: true });
|
|
5531
|
+
const how = await buildWorker(distDir, { appId: name2, appName: project.name, policy: project.policyText, automations: project.automationsText }, printCodeModule(print));
|
|
5532
|
+
if (how === "prebuilt") say(" the backend: the prebuilt Worker (nothing bundled on this computer); the app's code beside it");
|
|
5533
|
+
fs5.writeFileSync(path4.join(dir, "wrangler.toml"), wranglerConfig({ name: name2, bucket: record.bucket, domain: o.local ? null : record.domain, alert: record.alert }));
|
|
5534
|
+
const uploaded = [...filesUnder2(siteDir), ...filesUnder2(distDir)];
|
|
5535
|
+
const mb = uploaded.reduce((n, f) => n + fs5.statSync(f).size, 0) / 1e6;
|
|
5023
5536
|
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
5537
|
say("4. Nothing private in what is uploaded");
|
|
5025
5538
|
const found = leaks(uploaded, [{ what: "the admin credential", value: record.adminToken }, ...project.envValues.map((v, i) => ({ what: `.env value ${i + 1}`, value: v }))]);
|
|
@@ -5030,37 +5543,95 @@ ${functions.parts.failures.map((f) => ` ${f.name}: ${f.reason}`).join("\n")}`);
|
|
|
5030
5543
|
say(`Dry run: built in ${dir}, nothing uploaded.`);
|
|
5031
5544
|
return 0;
|
|
5032
5545
|
}
|
|
5033
|
-
say(`5. ${o.local ? "wrangler dev" : "wrangler deploy"}`);
|
|
5034
5546
|
if (o.local) {
|
|
5547
|
+
say("5. wrangler dev");
|
|
5035
5548
|
const port = o.port || 8787;
|
|
5036
|
-
|
|
5549
|
+
fs5.writeFileSync(path4.join(dir, ".dev.vars"), `NODEGX_ADMIN_TOKEN=${record.adminToken}
|
|
5037
5550
|
`, { mode: 384 });
|
|
5038
5551
|
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",
|
|
5552
|
+
const child = (0, import_node_child_process.spawn)(cmd, [...pre, "dev", "--config", "wrangler.toml", "--port", String(port), "--ip", "127.0.0.1", "--persist-to", path4.join(dir, ".state")], {
|
|
5040
5553
|
cwd: dir,
|
|
5041
5554
|
stdio: ["ignore", "pipe", "pipe"],
|
|
5042
5555
|
env: { ...process.env, WRANGLER_SEND_METRICS: "false" }
|
|
5043
5556
|
});
|
|
5044
|
-
const log =
|
|
5557
|
+
const log = fs5.createWriteStream(path4.join(dir, "wrangler-dev.log"));
|
|
5045
5558
|
child.stdout.pipe(log);
|
|
5046
5559
|
child.stderr.pipe(log);
|
|
5560
|
+
const unstarted = new Promise((_, reject) => child.on("error", (e) => reject(new DeployError(spawnFailure([cmd, ...pre], e) ?? String(e)))));
|
|
5561
|
+
unstarted.catch(() => void 0);
|
|
5047
5562
|
const base = `http://127.0.0.1:${port}`;
|
|
5048
|
-
await waitFor(`${base}/health`, 90);
|
|
5563
|
+
await Promise.race([waitFor(`${base}/health`, 90), unstarted]);
|
|
5049
5564
|
say(`6. The project onto the backend at ${base}`);
|
|
5050
5565
|
await applyEverything(base, record.adminToken, project, functions, firstDeploy || !!o.makeRoles, { dir, record, local: true });
|
|
5051
5566
|
record.deploys.push({ at: (/* @__PURE__ */ new Date()).toISOString(), url: base, local: true });
|
|
5052
5567
|
writeRecord(dir, record);
|
|
5053
5568
|
await testAlert(base, record, dir, true);
|
|
5054
5569
|
say(`
|
|
5055
|
-
Running on workerd at ${base} (log: ${
|
|
5570
|
+
Running on workerd at ${base} (log: ${path4.join(dir, "wrangler-dev.log")}). Ctrl-C stops it; its data stays in ${path4.join(dir, ".state")}.`);
|
|
5056
5571
|
await new Promise((resolve2) => child.on("exit", () => resolve2()));
|
|
5057
5572
|
return 0;
|
|
5058
5573
|
}
|
|
5574
|
+
const route = await chooseRoute(o);
|
|
5575
|
+
let url;
|
|
5576
|
+
let domainAnswer = null;
|
|
5577
|
+
if (route.via === "api") {
|
|
5578
|
+
say("5. Up to Cloudflare, through its API, with your NodeGX sign-in");
|
|
5579
|
+
const ours = !!before?.deploys.some((d) => !d.local);
|
|
5580
|
+
const up = await deployThroughApi({
|
|
5581
|
+
token: route.token,
|
|
5582
|
+
account: o.account,
|
|
5583
|
+
name: name2,
|
|
5584
|
+
distDir,
|
|
5585
|
+
siteDir,
|
|
5586
|
+
bucket: record.bucket,
|
|
5587
|
+
firstDeploy,
|
|
5588
|
+
domain: record.domain ?? null,
|
|
5589
|
+
previousDomain: before?.domain ?? null,
|
|
5590
|
+
alert: record.alert ?? null,
|
|
5591
|
+
adminToken: record.adminToken,
|
|
5592
|
+
replaceSecret: mint,
|
|
5593
|
+
ours,
|
|
5594
|
+
log: (l) => say(` ${l}`),
|
|
5595
|
+
onWorkerUp: (at) => {
|
|
5596
|
+
record.url = at;
|
|
5597
|
+
record.deploys.push({ at: (/* @__PURE__ */ new Date()).toISOString(), url: at, local: false, via: "api" });
|
|
5598
|
+
writeRecord(dir, record);
|
|
5599
|
+
}
|
|
5600
|
+
});
|
|
5601
|
+
url = up.url;
|
|
5602
|
+
domainAnswer = up.domain;
|
|
5603
|
+
} else {
|
|
5604
|
+
say(`5. wrangler deploy (${route.why})`);
|
|
5605
|
+
url = wranglerDeploy(dir, record, firstDeploy, mint);
|
|
5606
|
+
record.url = url;
|
|
5607
|
+
record.deploys.push({ at: (/* @__PURE__ */ new Date()).toISOString(), url, local: false, via: "wrangler" });
|
|
5608
|
+
writeRecord(dir, record);
|
|
5609
|
+
}
|
|
5610
|
+
await waitFor(`${url}/health`, 60);
|
|
5611
|
+
say(`6. The project onto the backend at ${url}`);
|
|
5612
|
+
await applyEverything(url, record.adminToken, project, functions, firstDeploy || !!o.makeRoles, { dir, record, local: false });
|
|
5613
|
+
say(`
|
|
5614
|
+
Online: ${url}`);
|
|
5615
|
+
if (record.domain && route.via === "wrangler") {
|
|
5616
|
+
say(`And at https://${record.domain} once Cloudflare has made its certificate (a few minutes the first time).`);
|
|
5617
|
+
} else if (domainAnswer?.inPublicDns) {
|
|
5618
|
+
say(`And at https://${domainAnswer.host} (the first visit can wait a minute for Cloudflare's certificate).`);
|
|
5619
|
+
} else if (domainAnswer) {
|
|
5620
|
+
say(
|
|
5621
|
+
`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.`
|
|
5622
|
+
);
|
|
5623
|
+
}
|
|
5624
|
+
await testAlert(url, record, dir);
|
|
5625
|
+
say(`The backend's dashboard: ${url}/_admin \u2014 its admin credential is in ${path4.join(dir, "deployment.json")} (never uploaded).`);
|
|
5626
|
+
return 0;
|
|
5627
|
+
}
|
|
5628
|
+
function wranglerDeploy(dir, record, firstDeploy, mint) {
|
|
5059
5629
|
if (record.bucket && firstDeploy) {
|
|
5060
5630
|
const made = wrangler(["r2", "bucket", "create", record.bucket], dir, { quiet: true });
|
|
5061
5631
|
if (made.status !== 0 && !/already exists|already own/i.test(made.out)) {
|
|
5632
|
+
if (!made.started) throw new DeployError(made.out);
|
|
5062
5633
|
throw new DeployError(`The bucket ${record.bucket} could not be made:
|
|
5063
|
-
${made.out.trim()}
|
|
5634
|
+
${made.out.trim() || `(wrangler exited ${made.status} and said nothing)`}
|
|
5064
5635
|
(R2 must be enabled on the account; --no-bucket deploys without one.)`);
|
|
5065
5636
|
}
|
|
5066
5637
|
say(` bucket ${record.bucket}: ${made.status === 0 ? "made" : "already there"}`);
|
|
@@ -5068,39 +5639,27 @@ ${made.out.trim()}
|
|
|
5068
5639
|
const deployArgs = ["deploy", "--config", "wrangler.toml"];
|
|
5069
5640
|
let secretsFile = null;
|
|
5070
5641
|
if (mint) {
|
|
5071
|
-
secretsFile =
|
|
5072
|
-
|
|
5642
|
+
secretsFile = path4.join(fs5.mkdtempSync(path4.join(os2.tmpdir(), "nodegx-cf-")), "secrets.json");
|
|
5643
|
+
fs5.writeFileSync(secretsFile, JSON.stringify({ NODEGX_ADMIN_TOKEN: record.adminToken }), { mode: 384 });
|
|
5073
5644
|
deployArgs.push("--secrets-file", secretsFile);
|
|
5074
5645
|
}
|
|
5075
5646
|
let done;
|
|
5076
5647
|
try {
|
|
5077
5648
|
done = wrangler(deployArgs, dir);
|
|
5078
5649
|
} finally {
|
|
5079
|
-
if (secretsFile)
|
|
5650
|
+
if (secretsFile) fs5.rmSync(path4.dirname(secretsFile), { recursive: true, force: true });
|
|
5080
5651
|
}
|
|
5652
|
+
if (!done.started) throw new DeployError(`${done.out} Nothing on the backend was changed.`);
|
|
5081
5653
|
if (done.status !== 0) throw new DeployError("wrangler deploy failed (above). Nothing on the backend was changed.");
|
|
5082
5654
|
const url = /https:\/\/[a-z0-9.-]+\.workers\.dev/.exec(done.out)?.[0] ?? record.url;
|
|
5083
5655
|
if (!url) throw new DeployError("wrangler deployed, but did not say the address: deploy again to finish.");
|
|
5084
|
-
|
|
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;
|
|
5656
|
+
return url;
|
|
5098
5657
|
}
|
|
5099
5658
|
async function main(argv) {
|
|
5100
5659
|
try {
|
|
5101
5660
|
return await deploy(parseArgs(argv));
|
|
5102
5661
|
} catch (e) {
|
|
5103
|
-
if (e instanceof DeployError || e?.name === "ApplyError") {
|
|
5662
|
+
if (e instanceof DeployError || e instanceof ApiDeployError || e?.name === "ApplyError") {
|
|
5104
5663
|
process.stderr.write(`
|
|
5105
5664
|
${e.message}
|
|
5106
5665
|
`);
|
|
@@ -5111,10 +5670,12 @@ ${e.message}
|
|
|
5111
5670
|
}
|
|
5112
5671
|
// Annotate the CommonJS export names for ESM import in node:
|
|
5113
5672
|
0 && (module.exports = {
|
|
5114
|
-
|
|
5115
|
-
|
|
5673
|
+
WORKER_OWN_MODULES,
|
|
5674
|
+
buildWorker,
|
|
5675
|
+
bundleWorker,
|
|
5116
5676
|
deploy,
|
|
5117
5677
|
leaks,
|
|
5118
5678
|
main,
|
|
5119
|
-
parseArgs
|
|
5679
|
+
parseArgs,
|
|
5680
|
+
wranglerCommand
|
|
5120
5681
|
});
|
package/dist/package.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nodegx/backend",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
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
|
],
|
package/dist/scripts/build.js
DELETED
package/src/prebuilt-worker.cjs
DELETED
|
@@ -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
|
-
};
|