@ubercode/channelvault 0.2.0 → 0.3.0-rc.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.
- package/CHANGELOG.md +41 -0
- package/README.md +31 -11
- package/dist/cli.js +753 -171
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +130 -19
- package/dist/index.js.map +1 -1
- package/docs/roadmap.md +7 -0
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -2,18 +2,18 @@
|
|
|
2
2
|
|
|
3
3
|
// src/cli.ts
|
|
4
4
|
import { spawnSync } from "child_process";
|
|
5
|
-
import { mkdir as
|
|
6
|
-
import { existsSync as
|
|
5
|
+
import { cp, lstat as lstat3, mkdir as mkdir5, mkdtemp, readdir as readdir5, readFile as readFile5, realpath as realpath4, rm as rm4, writeFile as writeFile6 } from "fs/promises";
|
|
6
|
+
import { existsSync as existsSync6 } from "fs";
|
|
7
7
|
import { tmpdir } from "os";
|
|
8
8
|
import { createRequire } from "module";
|
|
9
|
-
import * as
|
|
9
|
+
import * as path6 from "path";
|
|
10
10
|
import { createInterface } from "readline/promises";
|
|
11
11
|
import { Command, CommanderError } from "commander";
|
|
12
12
|
|
|
13
13
|
// src/explode/index.ts
|
|
14
14
|
import { AsyncLocalStorage } from "async_hooks";
|
|
15
15
|
import { existsSync } from "fs";
|
|
16
|
-
import { lstat, mkdir, readFile as readFile2, realpath, writeFile } from "fs/promises";
|
|
16
|
+
import { lstat, mkdir, readFile as readFile2, readdir, realpath, writeFile } from "fs/promises";
|
|
17
17
|
import * as path from "path";
|
|
18
18
|
|
|
19
19
|
// src/types.ts
|
|
@@ -398,12 +398,17 @@ async function splitCollection(parent, containerKey, elementKey, root, serverDir
|
|
|
398
398
|
const wasArray = Array.isArray(raw);
|
|
399
399
|
const elements = asArray(raw);
|
|
400
400
|
const refs = [];
|
|
401
|
+
const byName = (el) => `${slug(el["name"]).toLowerCase()}\0${String(el["id"] ?? "")}`;
|
|
402
|
+
const slugs = /* @__PURE__ */ new Map();
|
|
403
|
+
for (const el of elements.filter(isPlainObject).sort((a, b) => byName(a) < byName(b) ? -1 : byName(a) > byName(b) ? 1 : 0)) {
|
|
404
|
+
slugs.set(el, uniqueSlug(slug(el["name"]), usedSlugs));
|
|
405
|
+
}
|
|
401
406
|
for (const el of elements) {
|
|
402
407
|
if (!isPlainObject(el)) {
|
|
403
408
|
refs.push(el);
|
|
404
409
|
continue;
|
|
405
410
|
}
|
|
406
|
-
const slugName =
|
|
411
|
+
const slugName = slugs.get(el);
|
|
407
412
|
const { jsonFile, resourceDir } = targetFor(el["name"], slugName);
|
|
408
413
|
const transformed = await explodeResource(el, resourceDir);
|
|
409
414
|
await writeJson(jsonFile, transformed);
|
|
@@ -595,12 +600,13 @@ async function readWithinRoot(root, target, rel) {
|
|
|
595
600
|
}
|
|
596
601
|
return readFile2(realTarget, "utf8");
|
|
597
602
|
}
|
|
598
|
-
|
|
603
|
+
var pathKey = (file) => process.platform === "win32" ? file.toLowerCase() : file;
|
|
604
|
+
async function resolveMarkers(value, jsonDir, root, referenced) {
|
|
599
605
|
if (Array.isArray(value)) {
|
|
600
606
|
const out = [];
|
|
601
607
|
for (const item of value) {
|
|
602
608
|
if (isRefMarker(item) && !existsSync(resolveWithinRoot(root, jsonDir, item["@ref"]))) continue;
|
|
603
|
-
out.push(await resolveMarkers(item, jsonDir, root));
|
|
609
|
+
out.push(await resolveMarkers(item, jsonDir, root, referenced));
|
|
604
610
|
}
|
|
605
611
|
return out;
|
|
606
612
|
}
|
|
@@ -611,25 +617,81 @@ async function resolveMarkers(value, jsonDir, root) {
|
|
|
611
617
|
if (isRefMarker(value)) {
|
|
612
618
|
const target = resolveWithinRoot(root, jsonDir, value["@ref"]);
|
|
613
619
|
const text = await readWithinRoot(root, target, value["@ref"]);
|
|
620
|
+
referenced.add(pathKey(await realpath(target)));
|
|
614
621
|
const parsed = parseJson(text, target);
|
|
615
|
-
return resolveMarkers(parsed, path.dirname(target), root);
|
|
622
|
+
return resolveMarkers(parsed, path.dirname(target), root, referenced);
|
|
616
623
|
}
|
|
617
624
|
if (isPlainObject(value)) {
|
|
618
625
|
const out = {};
|
|
619
626
|
for (const [k, v] of Object.entries(value)) {
|
|
620
627
|
if (isRefMarker(v) && !existsSync(resolveWithinRoot(root, jsonDir, v["@ref"]))) continue;
|
|
621
|
-
out[k] = await resolveMarkers(v, jsonDir, root);
|
|
628
|
+
out[k] = await resolveMarkers(v, jsonDir, root, referenced);
|
|
622
629
|
}
|
|
623
630
|
return out;
|
|
624
631
|
}
|
|
625
632
|
return value;
|
|
626
633
|
}
|
|
634
|
+
async function discoverResources(config, root, referenced) {
|
|
635
|
+
const realRoot = await realpath(root);
|
|
636
|
+
const contained = async (file) => {
|
|
637
|
+
const real = await realpath(file);
|
|
638
|
+
if (real !== realRoot && !real.startsWith(realRoot + path.sep)) throw new Error(`resource path escapes the working tree through a link: ${file}`);
|
|
639
|
+
return real;
|
|
640
|
+
};
|
|
641
|
+
const layouts = [
|
|
642
|
+
{ folder: "channels", filename: "channel.json", container: "channels", member: "channel" },
|
|
643
|
+
{ folder: "codeTemplates", filename: "library.json", container: "codeTemplateLibraries", member: "codeTemplateLibrary" },
|
|
644
|
+
{ folder: "channelGroups", filename: null, container: "channelGroups", member: "channelGroup" }
|
|
645
|
+
];
|
|
646
|
+
for (const layout of layouts) {
|
|
647
|
+
const dir = path.join(root, layout.folder);
|
|
648
|
+
if (!existsSync(dir)) continue;
|
|
649
|
+
await contained(dir);
|
|
650
|
+
const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
651
|
+
const additions = [];
|
|
652
|
+
for (const entry of entries) {
|
|
653
|
+
let file = path.join(dir, entry.name);
|
|
654
|
+
if (layout.filename) {
|
|
655
|
+
if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
|
|
656
|
+
await contained(file);
|
|
657
|
+
file = path.join(file, layout.filename);
|
|
658
|
+
if (!existsSync(file)) continue;
|
|
659
|
+
} else if (!entry.name.endsWith(".json")) continue;
|
|
660
|
+
const real = await contained(file);
|
|
661
|
+
if (referenced.has(pathKey(real))) continue;
|
|
662
|
+
const parsed = parseJson(await readWithinRoot(root, file, file), file);
|
|
663
|
+
const resource = await resolveMarkers(parsed, path.dirname(file), root, referenced);
|
|
664
|
+
if (!isPlainObject(resource) || typeof resource["id"] !== "string" || !resource["id"].trim() || typeof resource["name"] !== "string" || !resource["name"].trim()) {
|
|
665
|
+
throw new Error(`new resource ${file} needs a nonempty id and name`);
|
|
666
|
+
}
|
|
667
|
+
additions.push(resource);
|
|
668
|
+
referenced.add(pathKey(real));
|
|
669
|
+
}
|
|
670
|
+
if (!additions.length) continue;
|
|
671
|
+
const container = isPlainObject(config[layout.container]) ? config[layout.container] : {};
|
|
672
|
+
const old = container[layout.member];
|
|
673
|
+
const members = [...old == null || old === "" ? [] : asArray(old), ...additions];
|
|
674
|
+
const ids = /* @__PURE__ */ new Set();
|
|
675
|
+
for (const member of members.filter(isPlainObject)) {
|
|
676
|
+
const id = String(member["id"]);
|
|
677
|
+
if (ids.has(id)) throw new Error(`duplicate ${layout.member} id ${id}: a copied resource keeps its source's id; give each copy a new UUID`);
|
|
678
|
+
ids.add(id);
|
|
679
|
+
}
|
|
680
|
+
config[layout.container] = { ...container, [layout.member]: members.length === 1 ? members[0] : members };
|
|
681
|
+
}
|
|
682
|
+
}
|
|
627
683
|
async function implode(opts) {
|
|
628
684
|
const root = path.resolve(opts.root);
|
|
685
|
+
if (existsSync(path.join(root, ".channelvault-transaction.json"))) {
|
|
686
|
+
throw new Error("working tree has a pending replacement; run a channelvault CLI command with the original --dotenv selection to recover it before reading");
|
|
687
|
+
}
|
|
629
688
|
const serverDir = path.join(root, "server");
|
|
630
689
|
const configPath = path.join(serverDir, "configuration.json");
|
|
631
|
-
const parsed = await
|
|
632
|
-
const
|
|
690
|
+
const parsed = parseJson(await readWithinRoot(root, configPath, configPath), configPath);
|
|
691
|
+
const referenced = /* @__PURE__ */ new Set();
|
|
692
|
+
const resolved = await resolveMarkers(parsed, serverDir, root, referenced);
|
|
693
|
+
if (!isPlainObject(resolved)) throw new Error("server/configuration.json must hold a configuration object");
|
|
694
|
+
await discoverResources(resolved, root, referenced);
|
|
633
695
|
return resolved;
|
|
634
696
|
}
|
|
635
697
|
function createExplodeEngine() {
|
|
@@ -927,25 +989,31 @@ function elementSegment(el, index) {
|
|
|
927
989
|
if (el && typeof el === "object" && !Array.isArray(el)) {
|
|
928
990
|
const id = el["id"] ?? el["metaDataId"];
|
|
929
991
|
if (typeof id === "string" || typeof id === "number") return `[${String(id)}]`;
|
|
992
|
+
const mapKey = CONFIG_PROPERTY in el ? configMapKeyOf(el) : void 0;
|
|
993
|
+
if (mapKey !== void 0) return `[${mapKey}]`;
|
|
930
994
|
}
|
|
931
995
|
return `[${index}]`;
|
|
932
996
|
}
|
|
997
|
+
function configMapKeyOf(entry) {
|
|
998
|
+
const key = entry["string"];
|
|
999
|
+
if (typeof key === "string") return key;
|
|
1000
|
+
return Array.isArray(key) && typeof key[0] === "string" ? key[0] : void 0;
|
|
1001
|
+
}
|
|
933
1002
|
function mapLeaves(config, visit) {
|
|
934
|
-
const walk = (node, key,
|
|
1003
|
+
const walk = (node, key, path7, labels, section, cmKey) => {
|
|
935
1004
|
if (typeof node === "string") {
|
|
936
|
-
return visit(node, { location:
|
|
1005
|
+
return visit(node, { location: path7.join("/"), key, labels, section, configMapKey: cmKey });
|
|
937
1006
|
}
|
|
938
1007
|
if (Array.isArray(node)) {
|
|
939
|
-
return node.map((el, i) => walk(el, key, [...
|
|
1008
|
+
return node.map((el, i) => walk(el, key, [...path7.slice(0, -1), `${path7[path7.length - 1]}${elementSegment(el, i)}`], labels, section, cmKey));
|
|
940
1009
|
}
|
|
941
1010
|
if (node && typeof node === "object") {
|
|
942
1011
|
const name = node["name"];
|
|
943
1012
|
const inner = typeof name === "string" && name.trim() !== "" ? [...labels, name] : labels;
|
|
944
|
-
const
|
|
945
|
-
const mapKey = section === "configurationMap" && CONFIG_PROPERTY in node ? typeof entryKey === "string" ? entryKey : Array.isArray(entryKey) && typeof entryKey[0] === "string" ? entryKey[0] : void 0 : cmKey;
|
|
1013
|
+
const mapKey = section === "configurationMap" && CONFIG_PROPERTY in node ? configMapKeyOf(node) : cmKey;
|
|
946
1014
|
const out = {};
|
|
947
1015
|
for (const [k, v] of Object.entries(node)) {
|
|
948
|
-
out[k] = walk(v, k, [...
|
|
1016
|
+
out[k] = walk(v, k, [...path7, k], inner, section || k, mapKey);
|
|
949
1017
|
}
|
|
950
1018
|
return out;
|
|
951
1019
|
}
|
|
@@ -1287,6 +1355,41 @@ function formatFindings(findings) {
|
|
|
1287
1355
|
${"".padEnd(20)} at ${f.location} context ${f.context}`).join("\n");
|
|
1288
1356
|
}
|
|
1289
1357
|
|
|
1358
|
+
// src/client/validate.ts
|
|
1359
|
+
var object = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
1360
|
+
function liveConfiguration(payload) {
|
|
1361
|
+
const bad = (detail) => {
|
|
1362
|
+
throw new Error(`invalid server configuration response: ${detail}; nothing should be written from this snapshot`);
|
|
1363
|
+
};
|
|
1364
|
+
if (!object(payload) || Object.keys(payload).length !== 1 || !("serverConfiguration" in payload)) bad("expected the serverConfiguration wrapper");
|
|
1365
|
+
const config = payload["serverConfiguration"];
|
|
1366
|
+
if (!object(config)) bad("expected a configuration object");
|
|
1367
|
+
const c = config;
|
|
1368
|
+
if (typeof c["@version"] !== "string" || !/^\d+\.\d+(?:\.\d+)*(?:[-+][A-Za-z0-9.-]+)?$/.test(c["@version"])) bad("missing or invalid engine version");
|
|
1369
|
+
if (!("channels" in c)) bad("missing channels collection");
|
|
1370
|
+
const collection = (container, key, where) => {
|
|
1371
|
+
if (container == null || container === "") return [];
|
|
1372
|
+
if (!object(container)) bad(`invalid ${where} collection`);
|
|
1373
|
+
if (!(key in container) && Object.keys(container).some((k) => !k.startsWith("@"))) bad(`missing resource list in ${where}`);
|
|
1374
|
+
const raw = container[key];
|
|
1375
|
+
if (raw == null || raw === "") return [];
|
|
1376
|
+
const items = Array.isArray(raw) ? raw : [raw];
|
|
1377
|
+
for (const item of items) {
|
|
1378
|
+
if (!object(item) || typeof item.id !== "string" || !item.id.trim() || typeof item.name !== "string" || !item.name.trim()) bad(`invalid resource in ${where}`);
|
|
1379
|
+
if ("revision" in item && (!Number.isSafeInteger(item.revision) || Number(item.revision) < 0)) bad(`invalid revision in ${where}`);
|
|
1380
|
+
}
|
|
1381
|
+
return items;
|
|
1382
|
+
};
|
|
1383
|
+
collection(c.channels, "channel", "channels");
|
|
1384
|
+
if ("codeTemplateLibraries" in c) {
|
|
1385
|
+
for (const library of collection(c.codeTemplateLibraries, "codeTemplateLibrary", "code template libraries")) {
|
|
1386
|
+
if ("codeTemplates" in library) collection(library.codeTemplates, "codeTemplate", "code templates");
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
if ("channelGroups" in c) collection(c.channelGroups, "channelGroup", "channel groups");
|
|
1390
|
+
return c;
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1290
1393
|
// src/client/index.ts
|
|
1291
1394
|
var UNTRUSTED_CERT_CODES = /* @__PURE__ */ new Set([
|
|
1292
1395
|
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
@@ -1400,16 +1503,20 @@ var MirthClientImpl = class {
|
|
|
1400
1503
|
/**
|
|
1401
1504
|
* GET /server/configuration -> canonical config.
|
|
1402
1505
|
*
|
|
1403
|
-
* Requests JSON
|
|
1404
|
-
*
|
|
1405
|
-
* a multi-key object is returned as-is).
|
|
1506
|
+
* Requests JSON and validates the envelope and core resource collections
|
|
1507
|
+
* before this snapshot can be used to replace a tree or plan server writes.
|
|
1406
1508
|
*/
|
|
1407
1509
|
async getServerConfiguration() {
|
|
1408
1510
|
const response = await this.request("GET", "/server/configuration", {
|
|
1409
1511
|
headers: { Accept: "application/json" }
|
|
1410
1512
|
});
|
|
1411
|
-
|
|
1412
|
-
|
|
1513
|
+
let json;
|
|
1514
|
+
try {
|
|
1515
|
+
json = await response.json();
|
|
1516
|
+
} catch {
|
|
1517
|
+
throw new Error("invalid server configuration response: expected JSON");
|
|
1518
|
+
}
|
|
1519
|
+
return liveConfiguration(json);
|
|
1413
1520
|
}
|
|
1414
1521
|
/**
|
|
1415
1522
|
* PUT /server/configuration <- canonical config.
|
|
@@ -1437,7 +1544,9 @@ var MirthClientImpl = class {
|
|
|
1437
1544
|
}
|
|
1438
1545
|
async getServerId() {
|
|
1439
1546
|
const response = await this.request("GET", "/server/id", { headers: { Accept: "text/plain" } });
|
|
1440
|
-
|
|
1547
|
+
const id = (await response.text()).trim();
|
|
1548
|
+
if (!/^[^\p{Cc}\p{Cf}]{1,255}$/u.test(id)) throw new Error("the server returned an invalid installation ID");
|
|
1549
|
+
return id;
|
|
1441
1550
|
}
|
|
1442
1551
|
async getServerConfigurationXml() {
|
|
1443
1552
|
const response = await this.request("GET", "/server/configuration", { headers: { Accept: "application/xml" } });
|
|
@@ -1454,12 +1563,23 @@ var MirthClientImpl = class {
|
|
|
1454
1563
|
// Override is on: Mirth does not reject a stale revision anyway (verified on
|
|
1455
1564
|
// 4.5.2), so conflict detection happens in the push planner instead.
|
|
1456
1565
|
async getChannel(id) {
|
|
1457
|
-
|
|
1566
|
+
return this.getResource(`/channels/${encodeURIComponent(id)}`);
|
|
1567
|
+
}
|
|
1568
|
+
async getCodeTemplate(id) {
|
|
1569
|
+
return this.getResource(`/codeTemplates/${encodeURIComponent(id)}`);
|
|
1570
|
+
}
|
|
1571
|
+
async getResource(resourcePath) {
|
|
1572
|
+
const response = await this.request("GET", resourcePath, {
|
|
1458
1573
|
headers: { Accept: "application/json" }
|
|
1574
|
+
}).catch((err) => {
|
|
1575
|
+
if (err.status === 404) return null;
|
|
1576
|
+
throw err;
|
|
1459
1577
|
});
|
|
1578
|
+
if (!response) return null;
|
|
1460
1579
|
const text = await response.text();
|
|
1461
1580
|
if (text.trim() === "") return null;
|
|
1462
|
-
|
|
1581
|
+
const parsed = JSON.parse(text);
|
|
1582
|
+
return parsed === null ? null : unwrapSingleKey(parsed);
|
|
1463
1583
|
}
|
|
1464
1584
|
async close() {
|
|
1465
1585
|
await this.dispatcher.close();
|
|
@@ -1493,15 +1613,15 @@ var MirthClientImpl = class {
|
|
|
1493
1613
|
await this.request("POST", `/channels/${encodeURIComponent(id)}/_deploy`, { query: { returnErrors: true } });
|
|
1494
1614
|
}
|
|
1495
1615
|
/** Send a JSON body; Mirth answers some updates with `{"boolean": false}` instead of an error status. */
|
|
1496
|
-
async sendJson(method,
|
|
1497
|
-
const response = await this.request(method,
|
|
1616
|
+
async sendJson(method, path7, body, query) {
|
|
1617
|
+
const response = await this.request(method, path7, {
|
|
1498
1618
|
query,
|
|
1499
1619
|
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
1500
1620
|
body: JSON.stringify(body)
|
|
1501
1621
|
});
|
|
1502
1622
|
const text = await response.text();
|
|
1503
1623
|
if (/^\s*\{\s*"boolean"\s*:\s*false\s*\}\s*$/.test(text)) {
|
|
1504
|
-
throw new Error(`${method} ${
|
|
1624
|
+
throw new Error(`${method} ${path7}: the server refused the update`);
|
|
1505
1625
|
}
|
|
1506
1626
|
}
|
|
1507
1627
|
// --- internal transport ---------------------------------------------------
|
|
@@ -1510,11 +1630,11 @@ var MirthClientImpl = class {
|
|
|
1510
1630
|
* on a 401 while authenticated resets auth, re-logs in once, and retries.
|
|
1511
1631
|
* Throws an {@link ApiError}-shaped error on a non-2xx response.
|
|
1512
1632
|
*/
|
|
1513
|
-
async request(method,
|
|
1633
|
+
async request(method, path7, options = {}, isRetry = false) {
|
|
1514
1634
|
if (!this.authenticated) {
|
|
1515
1635
|
await this.login();
|
|
1516
1636
|
}
|
|
1517
|
-
const url = this.buildUrl(
|
|
1637
|
+
const url = this.buildUrl(path7, options.query);
|
|
1518
1638
|
const headers = {
|
|
1519
1639
|
"X-Requested-With": "XMLHttpRequest",
|
|
1520
1640
|
...options.headers
|
|
@@ -1528,7 +1648,7 @@ var MirthClientImpl = class {
|
|
|
1528
1648
|
if (response.status === 401 && this.authenticated && !isRetry) {
|
|
1529
1649
|
this.authenticated = false;
|
|
1530
1650
|
await this.login();
|
|
1531
|
-
return this.request(method,
|
|
1651
|
+
return this.request(method, path7, options, true);
|
|
1532
1652
|
}
|
|
1533
1653
|
if (!response.ok) {
|
|
1534
1654
|
throw await this.toApiError(response);
|
|
@@ -1548,8 +1668,8 @@ var MirthClientImpl = class {
|
|
|
1548
1668
|
}
|
|
1549
1669
|
}
|
|
1550
1670
|
/** Build an absolute URL with an optional query string. */
|
|
1551
|
-
buildUrl(
|
|
1552
|
-
const url = `${this.baseUrl}${
|
|
1671
|
+
buildUrl(path7, query) {
|
|
1672
|
+
const url = `${this.baseUrl}${path7}`;
|
|
1553
1673
|
if (!query || Object.keys(query).length === 0) {
|
|
1554
1674
|
return url;
|
|
1555
1675
|
}
|
|
@@ -1654,8 +1774,17 @@ function same(a, b) {
|
|
|
1654
1774
|
}
|
|
1655
1775
|
return false;
|
|
1656
1776
|
}
|
|
1777
|
+
var ASSOCIATIONS = ["channelTags", "dependentIds", "dependencyIds"];
|
|
1778
|
+
function withSortedContexts(o) {
|
|
1779
|
+
const set = o["contextSet"];
|
|
1780
|
+
const delegate = isObj(set) ? set["delegate"] : void 0;
|
|
1781
|
+
const types = isObj(delegate) ? delegate["contextType"] : void 0;
|
|
1782
|
+
if (!isObj(set) || !isObj(delegate) || !Array.isArray(types)) return o;
|
|
1783
|
+
const sorted = [...types].sort((a, b) => String(a).localeCompare(String(b), "en"));
|
|
1784
|
+
return { ...o, contextSet: { ...set, delegate: { ...delegate, contextType: sorted } } };
|
|
1785
|
+
}
|
|
1657
1786
|
function stripVolatile(o) {
|
|
1658
|
-
const out = { ...o };
|
|
1787
|
+
const out = withSortedContexts({ ...o });
|
|
1659
1788
|
delete out["revision"];
|
|
1660
1789
|
delete out["lastModified"];
|
|
1661
1790
|
const exportData = out["exportData"];
|
|
@@ -1669,11 +1798,62 @@ function stripVolatile(o) {
|
|
|
1669
1798
|
}
|
|
1670
1799
|
return out;
|
|
1671
1800
|
}
|
|
1801
|
+
var groupsOf = (c) => isObj(c["channelGroups"]) ? list(c["channelGroups"]["channelGroup"]) : [];
|
|
1802
|
+
function withoutVolatile(c) {
|
|
1803
|
+
const out = structuredClone(c);
|
|
1804
|
+
const strip = (o) => {
|
|
1805
|
+
delete o["revision"];
|
|
1806
|
+
delete o["lastModified"];
|
|
1807
|
+
const exportData = o["exportData"];
|
|
1808
|
+
const md = isObj(exportData) ? exportData["metadata"] : void 0;
|
|
1809
|
+
if (isObj(md)) {
|
|
1810
|
+
delete md["lastModified"];
|
|
1811
|
+
delete md["userId"];
|
|
1812
|
+
}
|
|
1813
|
+
if (isObj(exportData)) {
|
|
1814
|
+
for (const key of ASSOCIATIONS) if (exportData[key] === null) delete exportData[key];
|
|
1815
|
+
}
|
|
1816
|
+
if (isObj(o["contextSet"])) o["contextSet"] = withSortedContexts(o)["contextSet"];
|
|
1817
|
+
};
|
|
1818
|
+
for (const ch of channelsOf(out)) strip(ch);
|
|
1819
|
+
for (const lib of librariesOf(out)) {
|
|
1820
|
+
strip(lib);
|
|
1821
|
+
for (const t of templatesOf2(lib)) strip(t);
|
|
1822
|
+
}
|
|
1823
|
+
for (const g of groupsOf(out)) {
|
|
1824
|
+
strip(g);
|
|
1825
|
+
for (const member of isObj(g["channels"]) ? list(g["channels"]["channel"]) : []) delete member["revision"];
|
|
1826
|
+
}
|
|
1827
|
+
return out;
|
|
1828
|
+
}
|
|
1829
|
+
function newerOnServer(tree, server) {
|
|
1830
|
+
const out = [];
|
|
1831
|
+
const compare = (kind, local, remote) => {
|
|
1832
|
+
const mine = new Map(local.map((o) => [idOf(o), revisionOf(o)]));
|
|
1833
|
+
for (const r of remote) {
|
|
1834
|
+
const rev = mine.get(idOf(r));
|
|
1835
|
+
if (rev !== void 0 && revisionOf(r) > rev) out.push(`${kind} "${nameOf(r)}"`);
|
|
1836
|
+
}
|
|
1837
|
+
};
|
|
1838
|
+
compare("channel", channelsOf(tree), channelsOf(server));
|
|
1839
|
+
compare("library", librariesOf(tree), librariesOf(server));
|
|
1840
|
+
compare("code template", librariesOf(tree).flatMap(templatesOf2), librariesOf(server).flatMap(templatesOf2));
|
|
1841
|
+
compare("channel group", groupsOf(tree), groupsOf(server));
|
|
1842
|
+
return out;
|
|
1843
|
+
}
|
|
1672
1844
|
function libraryShape(lib) {
|
|
1673
1845
|
const out = stripVolatile(lib);
|
|
1674
1846
|
out["codeTemplates"] = templatesOf2(lib).map(idOf);
|
|
1675
1847
|
return out;
|
|
1676
1848
|
}
|
|
1849
|
+
function withRetainedMembers(local, remote, localIds, deletedIds) {
|
|
1850
|
+
const retained = templatesOf2(remote).filter((t) => !localIds.has(idOf(t)) && !deletedIds.has(idOf(t)));
|
|
1851
|
+
if (!retained.length) return local;
|
|
1852
|
+
return { ...local, codeTemplates: {
|
|
1853
|
+
...isObj(local["codeTemplates"]) ? local["codeTemplates"] : {},
|
|
1854
|
+
codeTemplate: [...templatesOf2(local), ...retained]
|
|
1855
|
+
} };
|
|
1856
|
+
}
|
|
1677
1857
|
function hashGlobalScripts(c) {
|
|
1678
1858
|
return createHash2("sha256").update(JSON.stringify(normalizeEolDeep(c["globalScripts"] ?? null))).digest("hex");
|
|
1679
1859
|
}
|
|
@@ -1687,6 +1867,25 @@ function resourceIds(c) {
|
|
|
1687
1867
|
globalScripts: hashGlobalScripts(c)
|
|
1688
1868
|
};
|
|
1689
1869
|
}
|
|
1870
|
+
function adoptTarget(local, target) {
|
|
1871
|
+
const config = structuredClone(local);
|
|
1872
|
+
const mine = resourceIds(local);
|
|
1873
|
+
const theirs = resourceIds(target);
|
|
1874
|
+
const intersect = (key) => Object.fromEntries(Object.entries(theirs[key]).filter(([id]) => id in mine[key]));
|
|
1875
|
+
const known = {
|
|
1876
|
+
channels: intersect("channels"),
|
|
1877
|
+
libraries: intersect("libraries"),
|
|
1878
|
+
codeTemplates: intersect("codeTemplates"),
|
|
1879
|
+
globalScripts: theirs.globalScripts
|
|
1880
|
+
};
|
|
1881
|
+
const rebase = (items, revisions) => {
|
|
1882
|
+
for (const item of items) item["revision"] = revisions[idOf(item)] ?? 0;
|
|
1883
|
+
};
|
|
1884
|
+
rebase(channelsOf(config), theirs.channels);
|
|
1885
|
+
rebase(librariesOf(config), theirs.libraries);
|
|
1886
|
+
rebase(librariesOf(config).flatMap(templatesOf2), theirs.codeTemplates);
|
|
1887
|
+
return { config, known };
|
|
1888
|
+
}
|
|
1690
1889
|
function knownFrom(raw) {
|
|
1691
1890
|
if (!isObj(raw)) return void 0;
|
|
1692
1891
|
const r = raw;
|
|
@@ -1823,10 +2022,12 @@ function planPush(local, remote, scope = {}, known, opts = {}) {
|
|
|
1823
2022
|
for (const r of channelsOf(remote)) if (!deletedChannels.has(idOf(r))) effective.set(idOf(r), r);
|
|
1824
2023
|
for (const l of channelsOf(local)) if (writtenChannels.has(idOf(l))) effective.set(idOf(l), l);
|
|
1825
2024
|
const nameKey = (c) => nameOf(c).toLowerCase();
|
|
2025
|
+
const remoteNames = new Map(channelsOf(remote).map((c) => [idOf(c), nameKey(c)]));
|
|
2026
|
+
const introducesName = (c) => writtenChannels.has(idOf(c)) && remoteNames.get(idOf(c)) !== nameKey(c);
|
|
1826
2027
|
const during = opts.wholeReplace ? [] : channelsOf(remote);
|
|
1827
2028
|
const holders = [...new Map([...during, ...effective.values()].map((c) => [`${idOf(c)}
|
|
1828
2029
|
${nameKey(c)}`, c])).values()];
|
|
1829
|
-
const clashes = duplicates(holders, nameKey).filter(([, g]) => g.some(
|
|
2030
|
+
const clashes = duplicates(holders, nameKey).filter(([, g]) => g.some(introducesName));
|
|
1830
2031
|
if (clashes.length > 0) {
|
|
1831
2032
|
throw new Error(
|
|
1832
2033
|
`the push would save a channel under a name another channel holds:
|
|
@@ -1842,11 +2043,13 @@ rename one of them, or delete or rename the other in a push of its own first`
|
|
|
1842
2043
|
const remoteLibById = new Map(rl.map((l) => [idOf(l), l]));
|
|
1843
2044
|
const remoteTemplates = new Map(rl.flatMap((l) => templatesOf2(l).map((t) => [idOf(t), t])));
|
|
1844
2045
|
const localTemplateIds = new Set(ll.flatMap((l) => templatesOf2(l).map(idOf)));
|
|
2046
|
+
const deletedTemplateIds = new Set([...remoteTemplates.keys()].filter((id) => !localTemplateIds.has(id) && (!known || id in known.codeTemplates)));
|
|
1845
2047
|
const allChannelIds = [...effective.keys()];
|
|
1846
2048
|
for (const lib of ll.filter(inScope)) {
|
|
1847
2049
|
const r = remoteLibById.get(idOf(lib));
|
|
1848
2050
|
let touched = false;
|
|
1849
|
-
|
|
2051
|
+
const effectiveLib = r && !opts.wholeReplace ? withRetainedMembers(lib, r, localTemplateIds, deletedTemplateIds) : lib;
|
|
2052
|
+
if (!r || !same(libraryShape(effectiveLib), libraryShape(r))) {
|
|
1850
2053
|
changes.push({ kind: "library", op: r ? "update" : "create", id: idOf(lib), label: nameOf(lib) });
|
|
1851
2054
|
touched = true;
|
|
1852
2055
|
if (r && revisionOf(r) > revisionOf(lib)) conflicts.push(`library "${nameOf(lib)}" (server revision ${revisionOf(r)}, tree ${revisionOf(lib)})`);
|
|
@@ -1871,6 +2074,9 @@ rename one of them, or delete or rename the other in a push of its own first`
|
|
|
1871
2074
|
}
|
|
1872
2075
|
for (const r of rl.filter(inScope)) {
|
|
1873
2076
|
if (!ll.some((l) => idOf(l) === idOf(r))) {
|
|
2077
|
+
if (!opts.wholeReplace && known && idOf(r) in known.libraries && templatesOf2(r).some((t) => !localTemplateIds.has(idOf(t)) && !(idOf(t) in known.codeTemplates))) {
|
|
2078
|
+
throw new Error(`cannot delete library "${nameOf(r)}": it contains server-only code templates; pull and review their membership first`);
|
|
2079
|
+
}
|
|
1874
2080
|
const before = changes.length;
|
|
1875
2081
|
missingLocally("library", r, nameOf(r), known?.libraries);
|
|
1876
2082
|
if (changes.length > before) for (const id of channelsUsing(r, allChannelIds)) deploy.add(id);
|
|
@@ -1906,12 +2112,19 @@ function librariesToSend(local, remote, scope, plan) {
|
|
|
1906
2112
|
const rl = librariesOf(remote);
|
|
1907
2113
|
const inScope = scope.libraries === void 0 ? () => true : (o) => scope.libraries.includes(nameOf(o)) || scope.libraries.includes(idOf(o));
|
|
1908
2114
|
const deleted = new Set(plan.changes.filter((c) => c.kind === "library" && c.op === "delete").map((c) => c.id));
|
|
2115
|
+
const deletedTemplates = new Set(plan.changes.filter((c) => c.kind === "codeTemplate" && c.op === "delete").map((c) => c.id));
|
|
2116
|
+
const localTemplateIds = new Set(ll.flatMap(templatesOf2).map(idOf));
|
|
1909
2117
|
const localById = new Map(ll.map((l) => [idOf(l), l]));
|
|
1910
2118
|
const out = [];
|
|
1911
2119
|
for (const r of rl) {
|
|
1912
|
-
if (deleted.has(idOf(r)))
|
|
2120
|
+
if (deleted.has(idOf(r))) {
|
|
2121
|
+
if (templatesOf2(r).some((t) => !localTemplateIds.has(idOf(t)) && !deletedTemplates.has(idOf(t)))) {
|
|
2122
|
+
throw new Error(`cannot delete library "${nameOf(r)}": it contains server-only code templates; pull and review their membership first`);
|
|
2123
|
+
}
|
|
2124
|
+
continue;
|
|
2125
|
+
}
|
|
1913
2126
|
const l = localById.get(idOf(r));
|
|
1914
|
-
out.push(l && inScope(l) ? l : r);
|
|
2127
|
+
out.push(l && inScope(l) ? withRetainedMembers(l, r, localTemplateIds, deletedTemplates) : r);
|
|
1915
2128
|
}
|
|
1916
2129
|
for (const l of ll) if (inScope(l) && !rl.some((r) => idOf(r) === idOf(l))) out.push(l);
|
|
1917
2130
|
return out;
|
|
@@ -1928,16 +2141,20 @@ function changedSince(plan, before, after) {
|
|
|
1928
2141
|
else if (c.kind === "library") [b, a] = [lb.get(c.id), la.get(c.id)];
|
|
1929
2142
|
else if (!same(before["globalScripts"], after["globalScripts"])) out.push("global scripts");
|
|
1930
2143
|
if (c.kind === "globalScripts") continue;
|
|
1931
|
-
|
|
1932
|
-
const exists = a !== void 0;
|
|
1933
|
-
if (existed !== exists || a && b && revisionOf(a) !== revisionOf(b)) out.push(`${c.kind} "${c.label}"`);
|
|
2144
|
+
if (resourceChanged(c.kind, b, a)) out.push(`${c.kind} "${c.label}"`);
|
|
1934
2145
|
}
|
|
1935
2146
|
if (plan.changes.some((c) => c.kind === "library")) {
|
|
1936
|
-
|
|
1937
|
-
|
|
2147
|
+
if (lb.size !== la.size || [...lb].some(([id, l]) => resourceChanged("library", l, la.get(id)))) {
|
|
2148
|
+
out.push("code template libraries (the library list is saved as a whole)");
|
|
2149
|
+
}
|
|
1938
2150
|
}
|
|
1939
2151
|
return [...new Set(out)];
|
|
1940
2152
|
}
|
|
2153
|
+
function resourceChanged(kind, before, after) {
|
|
2154
|
+
if (!before || !after) return before !== after;
|
|
2155
|
+
const shape = kind === "library" ? libraryShape : stripVolatile;
|
|
2156
|
+
return revisionOf(before) !== revisionOf(after) || !same(shape(before), shape(after));
|
|
2157
|
+
}
|
|
1941
2158
|
function sameServerConfig(a, b) {
|
|
1942
2159
|
const { date: _a, ...ra } = a;
|
|
1943
2160
|
const { date: _b, ...rb } = b;
|
|
@@ -1962,7 +2179,7 @@ function findChannel(c, id) {
|
|
|
1962
2179
|
}
|
|
1963
2180
|
|
|
1964
2181
|
// src/push/apply.ts
|
|
1965
|
-
import { readdir, writeFile as writeFile2 } from "fs/promises";
|
|
2182
|
+
import { readdir as readdir2, writeFile as writeFile2 } from "fs/promises";
|
|
1966
2183
|
import { existsSync as existsSync2 } from "fs";
|
|
1967
2184
|
import * as path2 from "path";
|
|
1968
2185
|
var ORDER = [
|
|
@@ -1977,13 +2194,19 @@ async function applyPlan(client, plan, local, remote, scope, opts = {}) {
|
|
|
1977
2194
|
const applied = [];
|
|
1978
2195
|
const touchedIds = /* @__PURE__ */ new Set();
|
|
1979
2196
|
let librariesSent = false;
|
|
2197
|
+
let sentLibraries;
|
|
1980
2198
|
for (const [kind, ops] of ORDER) {
|
|
1981
2199
|
for (const change of plan.changes.filter((c) => c.kind === kind && ops.includes(c.op))) {
|
|
1982
2200
|
try {
|
|
1983
2201
|
if (kind === "library") {
|
|
1984
2202
|
if (!librariesSent) {
|
|
1985
|
-
const
|
|
1986
|
-
|
|
2203
|
+
const current = await client.getServerConfiguration();
|
|
2204
|
+
const moved = changedSince({ ...plan, changes: plan.changes.filter((c) => c.kind === "library") }, remote, current);
|
|
2205
|
+
if (!opts.force && moved.length) throw new Error(`changed on the server during the push: ${moved.join(", ")}; pull and try again`);
|
|
2206
|
+
const inSync = librariesInSync(local, current);
|
|
2207
|
+
const payload = librariesToSend(local, current, scope, plan);
|
|
2208
|
+
await client.putCodeTemplateLibraries(payload);
|
|
2209
|
+
sentLibraries = payload;
|
|
1987
2210
|
librariesSent = true;
|
|
1988
2211
|
const sentFromTree = librariesOf(local).filter(
|
|
1989
2212
|
(l) => scope.libraries === void 0 || scope.libraries.includes(String(l["name"])) || scope.libraries.includes(String(l["id"]))
|
|
@@ -1992,35 +2215,52 @@ async function applyPlan(client, plan, local, remote, scope, opts = {}) {
|
|
|
1992
2215
|
for (const id of inSync) touchedIds.add(id);
|
|
1993
2216
|
}
|
|
1994
2217
|
} else if (kind === "codeTemplate" && change.op === "delete") {
|
|
2218
|
+
await checkTemplate(client, change, remote, opts.force === true);
|
|
1995
2219
|
await client.deleteCodeTemplate(change.id);
|
|
1996
2220
|
} else if (kind === "codeTemplate") {
|
|
2221
|
+
await checkTemplate(client, change, remote, opts.force === true);
|
|
1997
2222
|
await client.putCodeTemplate(findTemplate(local, change.id));
|
|
1998
2223
|
} else if (kind === "channel" && change.op === "delete") {
|
|
2224
|
+
const current = await client.getChannel(change.id);
|
|
2225
|
+
checkResource(change, findChannel(remote, change.id), current, opts.force === true);
|
|
1999
2226
|
await client.deleteChannel(change.id);
|
|
2000
2227
|
} else if (kind === "channel") {
|
|
2228
|
+
const before = findChannel(remote, change.id);
|
|
2229
|
+
const channel = findChannel(local, change.id);
|
|
2230
|
+
if (!before || before["name"] !== channel["name"]) {
|
|
2231
|
+
planPush(local, await client.getServerConfiguration(), scope);
|
|
2232
|
+
}
|
|
2001
2233
|
await client.putChannel(
|
|
2002
|
-
await withServerAssociations(client,
|
|
2234
|
+
await withServerAssociations(client, channel, change, before, opts.force === true)
|
|
2003
2235
|
);
|
|
2004
2236
|
} else {
|
|
2237
|
+
const current = await client.getServerConfiguration();
|
|
2238
|
+
if (!opts.force && changedSince({ ...plan, changes: [change] }, remote, current).length) {
|
|
2239
|
+
throw new Error("global scripts changed on the server during the push; pull and try again");
|
|
2240
|
+
}
|
|
2005
2241
|
await client.putGlobalScripts(local["globalScripts"]);
|
|
2006
2242
|
}
|
|
2007
2243
|
} catch (err) {
|
|
2008
|
-
return { applied, failed: { change, error: err instanceof Error ? err.message : String(err) }, touchedIds };
|
|
2244
|
+
return { applied, failed: { change, error: err instanceof Error ? err.message : String(err) }, touchedIds, sentLibraries };
|
|
2009
2245
|
}
|
|
2010
2246
|
applied.push(change);
|
|
2011
2247
|
touchedIds.add(change.id);
|
|
2012
2248
|
}
|
|
2013
2249
|
}
|
|
2014
|
-
return { applied, touchedIds };
|
|
2250
|
+
return { applied, touchedIds, sentLibraries };
|
|
2015
2251
|
}
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
const server = await client.getChannel(String(channel["id"]));
|
|
2020
|
-
const [now, then] = [Number(server?.["revision"] ?? 0), Number(planned?.["revision"] ?? 0)];
|
|
2021
|
-
if (!force && now > then) {
|
|
2022
|
-
throw new Error(`changed on the server during the push (revision ${now}, planned against ${then}); pull and try again`);
|
|
2252
|
+
function checkResource(change, before, current, force) {
|
|
2253
|
+
if (!force && resourceChanged(change.kind, before, current ?? void 0)) {
|
|
2254
|
+
throw new Error(`${change.label} changed on the server during the push (revision ${String(current?.["revision"] ?? "absent")}, planned against ${String(before?.["revision"] ?? "absent")}); pull and try again`);
|
|
2023
2255
|
}
|
|
2256
|
+
}
|
|
2257
|
+
async function checkTemplate(client, change, remote, force) {
|
|
2258
|
+
checkResource(change, findTemplate(remote, change.id), await client.getCodeTemplate(change.id), force);
|
|
2259
|
+
}
|
|
2260
|
+
async function withServerAssociations(client, channel, change, planned, force) {
|
|
2261
|
+
const server = await client.getChannel(String(channel["id"]));
|
|
2262
|
+
checkResource(change, planned, server, force);
|
|
2263
|
+
if (change.op !== "update") return channel;
|
|
2024
2264
|
const serverExport = server?.["exportData"];
|
|
2025
2265
|
if (!serverExport) return channel;
|
|
2026
2266
|
const exportData = { ...channel["exportData"] ?? {} };
|
|
@@ -2028,15 +2268,22 @@ async function withServerAssociations(client, channel, op, planned, force) {
|
|
|
2028
2268
|
return { ...channel, exportData };
|
|
2029
2269
|
}
|
|
2030
2270
|
async function deployChannels(client, ids, nameOf2) {
|
|
2271
|
+
const deployed = [];
|
|
2272
|
+
const skipped = [];
|
|
2031
2273
|
const failures = [];
|
|
2032
2274
|
for (const id of ids) {
|
|
2033
2275
|
try {
|
|
2276
|
+
if (!(await client.getDeployedChannelIds()).has(id)) {
|
|
2277
|
+
skipped.push(nameOf2(id));
|
|
2278
|
+
continue;
|
|
2279
|
+
}
|
|
2034
2280
|
await client.deployChannel(id);
|
|
2281
|
+
deployed.push(nameOf2(id));
|
|
2035
2282
|
} catch (err) {
|
|
2036
2283
|
failures.push({ name: nameOf2(id), error: err instanceof Error ? err.message : String(err) });
|
|
2037
2284
|
}
|
|
2038
2285
|
}
|
|
2039
|
-
return failures;
|
|
2286
|
+
return { deployed, skipped, failures };
|
|
2040
2287
|
}
|
|
2041
2288
|
function copyVersionFields(target, source) {
|
|
2042
2289
|
if (!source) return false;
|
|
@@ -2057,7 +2304,7 @@ function copyVersionFields(target, source) {
|
|
|
2057
2304
|
}
|
|
2058
2305
|
async function jsonFiles(dir, name) {
|
|
2059
2306
|
if (!existsSync2(dir)) return [];
|
|
2060
|
-
const entries = await
|
|
2307
|
+
const entries = await readdir2(dir, { withFileTypes: true });
|
|
2061
2308
|
return entries.filter((e) => e.isDirectory()).map((e) => path2.join(dir, e.name, name)).filter((f) => existsSync2(f));
|
|
2062
2309
|
}
|
|
2063
2310
|
async function refreshRevisions(root, server, ids) {
|
|
@@ -2082,7 +2329,7 @@ async function refreshRevisions(root, server, ids) {
|
|
|
2082
2329
|
// src/secrets/envfile.ts
|
|
2083
2330
|
import { randomBytes } from "crypto";
|
|
2084
2331
|
import { existsSync as existsSync3 } from "fs";
|
|
2085
|
-
import { appendFile, chmod, copyFile, mkdir as mkdir2, readFile as readFile3, readdir as
|
|
2332
|
+
import { appendFile, chmod, copyFile, mkdir as mkdir2, readFile as readFile3, readdir as readdir3, realpath as realpath2, rename, rm, writeFile as writeFile3 } from "fs/promises";
|
|
2086
2333
|
import * as path3 from "path";
|
|
2087
2334
|
import { parse } from "dotenv";
|
|
2088
2335
|
var BASE64_PREFIX = "cv-base64:";
|
|
@@ -2168,25 +2415,25 @@ async function backupEnvFile(file, updates, dir) {
|
|
|
2168
2415
|
for (let n = 2; existsSync3(target); n += 1) target = path3.join(dir, `${prefix}${stamp2}-${String(n).padStart(2, "0")}`);
|
|
2169
2416
|
await copyFile(file, target);
|
|
2170
2417
|
await chmod(target, 384);
|
|
2171
|
-
const others = (await
|
|
2418
|
+
const others = (await readdir3(dir)).filter((f) => f.startsWith(prefix) && f !== path3.basename(target)).sort();
|
|
2172
2419
|
for (const old of others.slice(0, Math.max(0, others.length - (ENV_BACKUPS_KEPT - 1)))) {
|
|
2173
2420
|
await rm(path3.join(dir, old));
|
|
2174
2421
|
}
|
|
2175
2422
|
return target;
|
|
2176
2423
|
}
|
|
2177
2424
|
var IGNORE_LINES = [".env", ".env.*", "!.env.example", ".secrets/"];
|
|
2178
|
-
async function ensureEnvIgnored(dir, envFile) {
|
|
2425
|
+
async function ensureEnvIgnored(dir, envFile, treeRoot = dir) {
|
|
2179
2426
|
const file = path3.join(dir, ".gitignore");
|
|
2180
2427
|
const text = existsSync3(file) ? await readFile3(file, "utf8") : "";
|
|
2181
|
-
const
|
|
2428
|
+
const present2 = new Set(text.split(/\r?\n/).map((l) => l.trim()));
|
|
2182
2429
|
const wanted = [...IGNORE_LINES];
|
|
2183
2430
|
if (envFile) {
|
|
2184
|
-
const rel = path3.relative(
|
|
2431
|
+
const rel = path3.relative(treeRoot, envFile).split(path3.sep).join("/");
|
|
2185
2432
|
const base = path3.basename(envFile);
|
|
2186
2433
|
const covered = !rel.includes("/") && (base === ".env" || base.startsWith(".env.") && base !== ".env.example");
|
|
2187
2434
|
if (!covered && !rel.startsWith("..") && !path3.isAbsolute(rel)) wanted.push(`/${rel}`);
|
|
2188
2435
|
}
|
|
2189
|
-
const missing = wanted.filter((l) => !
|
|
2436
|
+
const missing = wanted.filter((l) => !present2.has(l));
|
|
2190
2437
|
if (missing.length === 0) return false;
|
|
2191
2438
|
const prefix = text === "" || text.endsWith("\n") ? "" : "\n";
|
|
2192
2439
|
await appendFile(file, `${prefix}# channelvault: secrets and per-environment values
|
|
@@ -2198,7 +2445,7 @@ ${missing.join("\n")}
|
|
|
2198
2445
|
// src/backup/index.ts
|
|
2199
2446
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
2200
2447
|
import { existsSync as existsSync4, realpathSync } from "fs";
|
|
2201
|
-
import { mkdir as mkdir3, readdir as
|
|
2448
|
+
import { mkdir as mkdir3, readdir as readdir4, readFile as readFile4, rename as rename2, rm as rm2, writeFile as writeFile4 } from "fs/promises";
|
|
2202
2449
|
import * as path4 from "path";
|
|
2203
2450
|
var DEFAULT_BACKUP_DIR = ".backup";
|
|
2204
2451
|
var DEFAULT_KEEP = 10;
|
|
@@ -2223,7 +2470,7 @@ function stamp(date) {
|
|
|
2223
2470
|
async function listBackups(dir) {
|
|
2224
2471
|
if (!existsSync4(dir)) return [];
|
|
2225
2472
|
const out = [];
|
|
2226
|
-
for (const name of await
|
|
2473
|
+
for (const name of await readdir4(dir)) {
|
|
2227
2474
|
const m = FILE_NAME.exec(name);
|
|
2228
2475
|
if (m) out.push({ file: path4.join(dir, name), server: m[1], stamp: m[2], seq: m[3] ? Number(m[3]) : 1 });
|
|
2229
2476
|
}
|
|
@@ -2241,8 +2488,8 @@ async function readManifest(dir) {
|
|
|
2241
2488
|
}
|
|
2242
2489
|
}
|
|
2243
2490
|
async function writeManifest(dir, files) {
|
|
2244
|
-
const
|
|
2245
|
-
await writePrivate(path4.join(dir, MANIFEST), `${JSON.stringify({ version: 1, files:
|
|
2491
|
+
const present2 = Object.fromEntries(Object.entries(files).filter(([name]) => existsSync4(path4.join(dir, name))));
|
|
2492
|
+
await writePrivate(path4.join(dir, MANIFEST), `${JSON.stringify({ version: 1, files: present2 }, null, 2)}
|
|
2246
2493
|
`);
|
|
2247
2494
|
}
|
|
2248
2495
|
async function backupsOf(dir, serverId) {
|
|
@@ -2312,6 +2559,202 @@ function compareVersions(a, b) {
|
|
|
2312
2559
|
return 0;
|
|
2313
2560
|
}
|
|
2314
2561
|
|
|
2562
|
+
// src/tree/transaction.ts
|
|
2563
|
+
import { randomUUID } from "crypto";
|
|
2564
|
+
import { constants, existsSync as existsSync5 } from "fs";
|
|
2565
|
+
import { copyFile as copyFile2, lstat as lstat2, mkdir as mkdir4, readlink, realpath as realpath3, rename as rename3, rm as rm3, rmdir, unlink, writeFile as writeFile5 } from "fs/promises";
|
|
2566
|
+
import { hostname } from "os";
|
|
2567
|
+
import * as path5 from "path";
|
|
2568
|
+
import { setTimeout as delay } from "timers/promises";
|
|
2569
|
+
var MANAGED_DIRS = ["server", "channels", "codeTemplates", "channelGroups"];
|
|
2570
|
+
var STAGING_DIR = ".channelvault-staging";
|
|
2571
|
+
var JOURNAL = ".channelvault-transaction.json";
|
|
2572
|
+
var ITEMS = [...MANAGED_DIRS, "channelvault.json", ".gitignore", ".secrets", "env"];
|
|
2573
|
+
var RM = { recursive: true, force: true, maxRetries: 5, retryDelay: 50 };
|
|
2574
|
+
async function present(file) {
|
|
2575
|
+
return lstat2(file).then(() => true, (err) => {
|
|
2576
|
+
if (err.code === "ENOENT") return false;
|
|
2577
|
+
throw err;
|
|
2578
|
+
});
|
|
2579
|
+
}
|
|
2580
|
+
async function canonical(file, depth = 0) {
|
|
2581
|
+
if (depth > 64) throw new Error(`too many links in path: ${file}`);
|
|
2582
|
+
let existing = path5.resolve(file);
|
|
2583
|
+
while (!await present(existing) && path5.dirname(existing) !== existing) existing = path5.dirname(existing);
|
|
2584
|
+
const info = await lstat2(existing);
|
|
2585
|
+
const base = info.isSymbolicLink() ? await canonical(path5.resolve(path5.dirname(existing), await readlink(existing)), depth + 1) : await realpath3(existing);
|
|
2586
|
+
return path5.join(base, path5.relative(existing, path5.resolve(file)));
|
|
2587
|
+
}
|
|
2588
|
+
var samePath = (a, b) => process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
2589
|
+
async function move(from, to) {
|
|
2590
|
+
for (let attempt = 0; ; attempt++) {
|
|
2591
|
+
try {
|
|
2592
|
+
await rename3(from, to);
|
|
2593
|
+
return;
|
|
2594
|
+
} catch (err) {
|
|
2595
|
+
if (attempt >= 5 || !["EPERM", "EBUSY", "ENOTEMPTY", "EACCES"].includes(err.code ?? "")) throw err;
|
|
2596
|
+
await delay(50 * (attempt + 1));
|
|
2597
|
+
}
|
|
2598
|
+
}
|
|
2599
|
+
}
|
|
2600
|
+
async function lockTree(root) {
|
|
2601
|
+
await mkdir4(path5.dirname(root), { recursive: true });
|
|
2602
|
+
const lock = `${await canonical(root)}.channelvault-lock`;
|
|
2603
|
+
const ownerFile = path5.join(lock, "owner.json");
|
|
2604
|
+
const owner = { pid: process.pid, host: hostname(), token: randomUUID() };
|
|
2605
|
+
try {
|
|
2606
|
+
await mkdir4(lock);
|
|
2607
|
+
} catch (err) {
|
|
2608
|
+
if (err.code !== "EEXIST") throw err;
|
|
2609
|
+
if ((await lstat2(lock)).isSymbolicLink()) throw new Error(`refusing a linked working-tree lock: ${lock}`);
|
|
2610
|
+
let previous;
|
|
2611
|
+
try {
|
|
2612
|
+
previous = await readJson(ownerFile);
|
|
2613
|
+
} catch {
|
|
2614
|
+
throw new Error(`working-tree lock has no readable owner: ${lock}; inspect it before removing it`);
|
|
2615
|
+
}
|
|
2616
|
+
const dead = () => {
|
|
2617
|
+
if (previous.host !== hostname() || !Number.isInteger(previous.pid) || previous.pid <= 0) return false;
|
|
2618
|
+
try {
|
|
2619
|
+
process.kill(previous.pid, 0);
|
|
2620
|
+
return false;
|
|
2621
|
+
} catch (error) {
|
|
2622
|
+
return error.code === "ESRCH";
|
|
2623
|
+
}
|
|
2624
|
+
};
|
|
2625
|
+
if (!dead()) throw new Error(`working tree is locked by process ${previous.pid} on ${previous.host}: ${lock}`);
|
|
2626
|
+
const reaping = path5.join(lock, "reaping");
|
|
2627
|
+
try {
|
|
2628
|
+
await mkdir4(reaping);
|
|
2629
|
+
} catch {
|
|
2630
|
+
throw new Error(`another process is recovering the working-tree lock: ${lock}; retry`);
|
|
2631
|
+
}
|
|
2632
|
+
try {
|
|
2633
|
+
const check = await readJson(ownerFile);
|
|
2634
|
+
if (check.token !== previous.token || !dead()) throw new Error(`working-tree lock changed: ${lock}; retry`);
|
|
2635
|
+
await unlink(ownerFile);
|
|
2636
|
+
} finally {
|
|
2637
|
+
await rmdir(reaping);
|
|
2638
|
+
}
|
|
2639
|
+
await rmdir(lock);
|
|
2640
|
+
await mkdir4(lock);
|
|
2641
|
+
}
|
|
2642
|
+
try {
|
|
2643
|
+
await writeFile5(ownerFile, JSON.stringify(owner), { flag: "wx", mode: 384 });
|
|
2644
|
+
} catch (err) {
|
|
2645
|
+
await rmdir(lock).catch(() => void 0);
|
|
2646
|
+
throw err;
|
|
2647
|
+
}
|
|
2648
|
+
return async () => {
|
|
2649
|
+
const check = await readJson(ownerFile);
|
|
2650
|
+
if (check.token !== owner.token) throw new Error(`working-tree lock ownership changed: ${lock}`);
|
|
2651
|
+
await unlink(ownerFile);
|
|
2652
|
+
await rmdir(lock);
|
|
2653
|
+
};
|
|
2654
|
+
}
|
|
2655
|
+
async function assertStage(root) {
|
|
2656
|
+
for (const suffix of ["", "next", "previous"]) {
|
|
2657
|
+
const stage = path5.join(root, STAGING_DIR, suffix);
|
|
2658
|
+
const info = await lstat2(stage).catch((err) => {
|
|
2659
|
+
if (err.code !== "ENOENT") throw err;
|
|
2660
|
+
return void 0;
|
|
2661
|
+
});
|
|
2662
|
+
if (info?.isSymbolicLink()) throw new Error(`refusing a linked staging directory: ${stage}`);
|
|
2663
|
+
}
|
|
2664
|
+
}
|
|
2665
|
+
function targetOf(root, journal, name) {
|
|
2666
|
+
return name === "env" ? journal.envFile : path5.join(root, name);
|
|
2667
|
+
}
|
|
2668
|
+
function copies(root, journal, name) {
|
|
2669
|
+
return name === "env" ? { old: `${journal.envFile}.channelvault-${journal.id}.previous`, next: `${journal.envFile}.channelvault-${journal.id}.next` } : { old: path5.join(root, STAGING_DIR, "previous", name), next: path5.join(root, STAGING_DIR, "next", name) };
|
|
2670
|
+
}
|
|
2671
|
+
async function cleanup(root, journal) {
|
|
2672
|
+
if (journal.entries.some((e) => e.name === "env")) {
|
|
2673
|
+
const { old, next } = copies(root, journal, "env");
|
|
2674
|
+
await rm3(old, { force: true });
|
|
2675
|
+
await rm3(next, { force: true });
|
|
2676
|
+
}
|
|
2677
|
+
await rm3(path5.join(root, STAGING_DIR), RM);
|
|
2678
|
+
}
|
|
2679
|
+
async function rollback(root, journal) {
|
|
2680
|
+
for (const entry of [...journal.entries].reverse()) {
|
|
2681
|
+
const target = targetOf(root, journal, entry.name);
|
|
2682
|
+
const { old, next } = copies(root, journal, entry.name);
|
|
2683
|
+
if (await present(old)) {
|
|
2684
|
+
await rm3(target, RM);
|
|
2685
|
+
await move(old, target);
|
|
2686
|
+
} else if (!entry.hadOld && !await present(next)) {
|
|
2687
|
+
await rm3(target, RM);
|
|
2688
|
+
}
|
|
2689
|
+
}
|
|
2690
|
+
}
|
|
2691
|
+
async function recoverTree(root, envFile) {
|
|
2692
|
+
const file = path5.join(root, JOURNAL);
|
|
2693
|
+
if (!existsSync5(file)) return;
|
|
2694
|
+
await assertStage(root);
|
|
2695
|
+
const journal = await readJson(file);
|
|
2696
|
+
if (journal.version !== 1 || !/^[a-f0-9-]{36}$/.test(journal.id) || !["prepared", "committed"].includes(journal.state) || !Array.isArray(journal.entries) || journal.entries.some((e) => !ITEMS.includes(e.name) || typeof e.hadOld !== "boolean") || new Set(journal.entries.map((e) => e.name)).size !== journal.entries.length || typeof journal.envFile !== "string" || !samePath(journal.envFile, await canonical(envFile))) {
|
|
2697
|
+
throw new Error(`invalid transaction journal or different env file: ${file}; use the original --dotenv selection to recover`);
|
|
2698
|
+
}
|
|
2699
|
+
if (journal.state === "prepared") await rollback(root, journal);
|
|
2700
|
+
await cleanup(root, journal);
|
|
2701
|
+
await unlink(file);
|
|
2702
|
+
}
|
|
2703
|
+
async function replaceTree(root, envFile, prepare) {
|
|
2704
|
+
await recoverTree(root, envFile);
|
|
2705
|
+
await assertStage(root);
|
|
2706
|
+
const stage = path5.join(root, STAGING_DIR);
|
|
2707
|
+
await rm3(stage, RM);
|
|
2708
|
+
const next = path5.join(stage, "next");
|
|
2709
|
+
await mkdir4(next, { recursive: true });
|
|
2710
|
+
let journal;
|
|
2711
|
+
try {
|
|
2712
|
+
await prepare(next);
|
|
2713
|
+
const targetEnv = await canonical(envFile);
|
|
2714
|
+
journal = { version: 1, id: randomUUID(), state: "prepared", envFile: targetEnv, entries: [] };
|
|
2715
|
+
for (const name of ITEMS) {
|
|
2716
|
+
if (!MANAGED_DIRS.includes(name) && !existsSync5(path5.join(next, name === "env" ? ".env" : name))) continue;
|
|
2717
|
+
const target = targetOf(root, journal, name);
|
|
2718
|
+
const info = await lstat2(target).catch((err) => {
|
|
2719
|
+
if (err.code !== "ENOENT") throw err;
|
|
2720
|
+
return void 0;
|
|
2721
|
+
});
|
|
2722
|
+
journal.entries.push({ name, hadOld: info !== void 0 });
|
|
2723
|
+
}
|
|
2724
|
+
await mkdir4(path5.join(stage, "previous"));
|
|
2725
|
+
await writePrivate(path5.join(root, JOURNAL), JSON.stringify(journal));
|
|
2726
|
+
if (journal.entries.some((e) => e.name === "env")) {
|
|
2727
|
+
await mkdir4(path5.dirname(targetEnv), { recursive: true });
|
|
2728
|
+
await copyFile2(path5.join(next, ".env"), copies(root, journal, "env").next, constants.COPYFILE_EXCL);
|
|
2729
|
+
}
|
|
2730
|
+
for (const entry of journal.entries) {
|
|
2731
|
+
const target = targetOf(root, journal, entry.name);
|
|
2732
|
+
const files = copies(root, journal, entry.name);
|
|
2733
|
+
if (entry.hadOld) await move(target, files.old);
|
|
2734
|
+
if (existsSync5(files.next)) {
|
|
2735
|
+
await mkdir4(path5.dirname(target), { recursive: true });
|
|
2736
|
+
await move(files.next, target);
|
|
2737
|
+
}
|
|
2738
|
+
}
|
|
2739
|
+
journal.state = "committed";
|
|
2740
|
+
await writePrivate(path5.join(root, JOURNAL), JSON.stringify(journal));
|
|
2741
|
+
} catch (err) {
|
|
2742
|
+
if (journal && existsSync5(path5.join(root, JOURNAL))) {
|
|
2743
|
+
try {
|
|
2744
|
+
await rollback(root, journal);
|
|
2745
|
+
} catch (recoveryError) {
|
|
2746
|
+
throw new Error(`replacement failed and recovery is pending in ${path5.join(root, JOURNAL)}; retry this command with the same env file`, { cause: recoveryError });
|
|
2747
|
+
}
|
|
2748
|
+
await cleanup(root, journal);
|
|
2749
|
+
await unlink(path5.join(root, JOURNAL));
|
|
2750
|
+
}
|
|
2751
|
+
await rm3(stage, RM);
|
|
2752
|
+
throw err;
|
|
2753
|
+
}
|
|
2754
|
+
await cleanup(root, journal);
|
|
2755
|
+
await unlink(path5.join(root, JOURNAL));
|
|
2756
|
+
}
|
|
2757
|
+
|
|
2315
2758
|
// src/cli.ts
|
|
2316
2759
|
var engine = createExplodeEngine();
|
|
2317
2760
|
var xml = new XmlConfigAdapter();
|
|
@@ -2322,8 +2765,6 @@ function fail(message) {
|
|
|
2322
2765
|
throw new CliError(message);
|
|
2323
2766
|
}
|
|
2324
2767
|
var errorExitCode = 1;
|
|
2325
|
-
var MANAGED_DIRS = ["server", "channels", "codeTemplates", "channelGroups"];
|
|
2326
|
-
var STAGING_DIR = ".channelvault-staging";
|
|
2327
2768
|
var RM_OPTS = { recursive: true, force: true, maxRetries: 5, retryDelay: 50 };
|
|
2328
2769
|
function resolveClientConfig(flags) {
|
|
2329
2770
|
const host = flags.host ?? process.env.MIRTH_HOST;
|
|
@@ -2371,7 +2812,7 @@ function addBackupDirFlags(cmd) {
|
|
|
2371
2812
|
return cmd.option("--backup-dir <dir>", `where backups are kept (default ./${DEFAULT_BACKUP_DIR})`).option("--keep <n>", `backups kept per server (default ${DEFAULT_KEEP})`);
|
|
2372
2813
|
}
|
|
2373
2814
|
function backupDirOf(flags) {
|
|
2374
|
-
return
|
|
2815
|
+
return path6.resolve(flags.backupDir ?? DEFAULT_BACKUP_DIR);
|
|
2375
2816
|
}
|
|
2376
2817
|
function keepOf(flags) {
|
|
2377
2818
|
if (flags.keep === void 0) return DEFAULT_KEEP;
|
|
@@ -2403,8 +2844,36 @@ async function saveServerBackup(client, text, flags, protect) {
|
|
|
2403
2844
|
async function backupBeforePush(client, flags) {
|
|
2404
2845
|
if (flags.backup === false) return;
|
|
2405
2846
|
const file = await saveServerBackup(client, await client.getServerConfigurationXml(), flags);
|
|
2406
|
-
process.stdout.write(`backed up the server to ${file} (undo with:
|
|
2847
|
+
process.stdout.write(`backed up the server to ${file} (undo with: ${undoCommand(file, flags)})
|
|
2407
2848
|
`);
|
|
2849
|
+
printUndoLimits(flags);
|
|
2850
|
+
}
|
|
2851
|
+
function shellArgument(value) {
|
|
2852
|
+
return process.platform === "win32" ? `'${value.replace(/'/g, "''")}'` : `'${value.replace(/'/g, "'\\''")}'`;
|
|
2853
|
+
}
|
|
2854
|
+
function undoCommand(file, flags) {
|
|
2855
|
+
const cfg = resolveClientConfig(flags);
|
|
2856
|
+
const args = [
|
|
2857
|
+
"channelvault",
|
|
2858
|
+
"restore",
|
|
2859
|
+
shellArgument(file),
|
|
2860
|
+
"--host",
|
|
2861
|
+
shellArgument(cfg.host),
|
|
2862
|
+
"--port",
|
|
2863
|
+
String(cfg.port),
|
|
2864
|
+
"--user",
|
|
2865
|
+
shellArgument(cfg.username),
|
|
2866
|
+
"--backup-dir",
|
|
2867
|
+
shellArgument(backupDirOf(flags))
|
|
2868
|
+
];
|
|
2869
|
+
if (cfg.https === false) args.push("--no-https");
|
|
2870
|
+
if (cfg.disableTlsCheck) args.push("--insecure");
|
|
2871
|
+
if (flags.overwriteConfigMap) args.push("--overwrite-config-map");
|
|
2872
|
+
return args.join(" ");
|
|
2873
|
+
}
|
|
2874
|
+
function printUndoLimits(flags) {
|
|
2875
|
+
if (flags.pass !== void 0) process.stdout.write("undo authentication: supply this server's password through MIRTH_PASS; it is omitted from the command\n");
|
|
2876
|
+
if (flags.deploy) process.stdout.write("the undo restores saved configuration; runtime deployment state is not in the backup. Review targeted redeployment separately\n");
|
|
2408
2877
|
}
|
|
2409
2878
|
function hostOf(flags) {
|
|
2410
2879
|
const cfg = resolveClientConfig(flags);
|
|
@@ -2446,7 +2915,7 @@ function summarize(config) {
|
|
|
2446
2915
|
codeTemplates
|
|
2447
2916
|
};
|
|
2448
2917
|
}
|
|
2449
|
-
async function writeMeta(root, source, config, previous) {
|
|
2918
|
+
async function writeMeta(root, source, config, previous, serverId, resources = resourceIds(config)) {
|
|
2450
2919
|
const meta = {
|
|
2451
2920
|
tool: "channelvault",
|
|
2452
2921
|
version: VERSION,
|
|
@@ -2454,14 +2923,15 @@ async function writeMeta(root, source, config, previous) {
|
|
|
2454
2923
|
pulledAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2455
2924
|
// XML adapter yields `@_version`; the live JSON API yields `@version` (Jackson).
|
|
2456
2925
|
engineVersion: typeof config["@_version"] === "string" ? config["@_version"] : typeof config["@version"] === "string" ? config["@version"] : null,
|
|
2457
|
-
resources
|
|
2926
|
+
resources,
|
|
2927
|
+
serverId
|
|
2458
2928
|
};
|
|
2459
|
-
const file =
|
|
2460
|
-
if (previous && JSON.stringify({ ...previous, pulledAt: "" }) === JSON.stringify({ ...meta, pulledAt: "" }))
|
|
2461
|
-
await
|
|
2929
|
+
const file = path6.join(root, "channelvault.json");
|
|
2930
|
+
if (previous && JSON.stringify({ ...previous, pulledAt: "" }) === JSON.stringify({ ...meta, pulledAt: "" })) meta.pulledAt = previous.pulledAt;
|
|
2931
|
+
await writeFile6(file, JSON.stringify(meta, null, 2) + "\n", "utf8");
|
|
2462
2932
|
}
|
|
2463
2933
|
function envFilePath(root, flags) {
|
|
2464
|
-
return flags.dotenv ?
|
|
2934
|
+
return flags.dotenv ? path6.resolve(flags.dotenv) : path6.join(root, ".env");
|
|
2465
2935
|
}
|
|
2466
2936
|
async function loadEnv(file) {
|
|
2467
2937
|
return { ...await readEnvFile(file), ...process.env };
|
|
@@ -2473,7 +2943,7 @@ function addExtractFlag(cmd) {
|
|
|
2473
2943
|
return cmd.option("--extract-secrets", "move secrets found inside values (URLs, scripts, headers) to the env file", false);
|
|
2474
2944
|
}
|
|
2475
2945
|
async function existingTree(root) {
|
|
2476
|
-
return
|
|
2946
|
+
return existsSync6(path6.join(root, "server", "configuration.json")) ? engine.implode({ root }) : null;
|
|
2477
2947
|
}
|
|
2478
2948
|
async function renderedTree(root, flags) {
|
|
2479
2949
|
const tree = await engine.implode({ root });
|
|
@@ -2502,12 +2972,12 @@ function scrub(text) {
|
|
|
2502
2972
|
}
|
|
2503
2973
|
var ALLOW_FILE = "channelvault.allow.json";
|
|
2504
2974
|
async function readAllow(root) {
|
|
2505
|
-
const file =
|
|
2506
|
-
if (!
|
|
2975
|
+
const file = path6.join(root, ALLOW_FILE);
|
|
2976
|
+
if (!existsSync6(file)) return [];
|
|
2507
2977
|
const parsed = await readJson(file);
|
|
2508
2978
|
return parsed.ignore ?? [];
|
|
2509
2979
|
}
|
|
2510
|
-
async function writeTree(root, fetched, source, flags) {
|
|
2980
|
+
async function writeTree(root, fetched, source, flags, serverId) {
|
|
2511
2981
|
const envFile = envFilePath(root, flags);
|
|
2512
2982
|
const previousMeta = await preflightTree(root, envFile);
|
|
2513
2983
|
const env = await loadEnv(envFile);
|
|
@@ -2528,15 +2998,30 @@ Rerun with --extract-secrets to move them to ${envFile}, or list false positives
|
|
|
2528
2998
|
const envUpdates = { ...templated.envUpdates, ...scan.envUpdates };
|
|
2529
2999
|
rememberSecrets(config, { ...env, ...envUpdates });
|
|
2530
3000
|
const echoes = findEchoes(config, { ...await readEnvFile(envFile), ...envUpdates });
|
|
2531
|
-
|
|
2532
|
-
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
|
|
2536
|
-
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
3001
|
+
const rel = path6.relative(root, envFile);
|
|
3002
|
+
const envInTree = !rel.startsWith("..") && !path6.isAbsolute(rel);
|
|
3003
|
+
let backup = null;
|
|
3004
|
+
await replaceTree(root, envFile, async (next) => {
|
|
3005
|
+
await engine.explode(config, { root: next });
|
|
3006
|
+
await writeMeta(next, source, fetched, previousMeta, serverId);
|
|
3007
|
+
if (Object.keys(envUpdates).length > 0) {
|
|
3008
|
+
const history = path6.join(root, ".secrets");
|
|
3009
|
+
if (existsSync6(history)) {
|
|
3010
|
+
if ((await lstat3(history)).isSymbolicLink()) fail(`refusing a linked secret history directory: ${history}`);
|
|
3011
|
+
await cp(history, path6.join(next, ".secrets"), { recursive: true });
|
|
3012
|
+
}
|
|
3013
|
+
const stagedBackup = await backupEnvFile(envFile, envUpdates, path6.join(next, ".secrets"));
|
|
3014
|
+
if (stagedBackup) backup = path6.join(root, ".secrets", path6.basename(stagedBackup));
|
|
3015
|
+
if (backup || envInTree) {
|
|
3016
|
+
const ignore = path6.join(root, ".gitignore");
|
|
3017
|
+
if (existsSync6(ignore)) await writeFile6(path6.join(next, ".gitignore"), await readFile5(ignore));
|
|
3018
|
+
await ensureEnvIgnored(next, envInTree ? envFile : void 0, root);
|
|
3019
|
+
}
|
|
3020
|
+
const stagedEnv = path6.join(next, ".env");
|
|
3021
|
+
if (existsSync6(envFile)) await writeFile6(stagedEnv, await readFile5(envFile), { mode: 384 });
|
|
3022
|
+
await updateEnvFile(stagedEnv, envUpdates);
|
|
3023
|
+
}
|
|
3024
|
+
});
|
|
2540
3025
|
if (scan.findings.length > 0) process.stdout.write(`extracted ${scan.findings.length} secret(s) found in values
|
|
2541
3026
|
`);
|
|
2542
3027
|
const updated = Object.keys(envUpdates).length;
|
|
@@ -2550,34 +3035,34 @@ Rerun with --extract-secrets to move them to ${envFile}, or list false positives
|
|
|
2550
3035
|
process.stderr.write(`warning: the value of ${e.name} also appears in plain text at ${e.where}
|
|
2551
3036
|
`);
|
|
2552
3037
|
}
|
|
2553
|
-
if (
|
|
3038
|
+
if (existsSync6(envFile) && gitWouldCommit(envFile)) {
|
|
2554
3039
|
process.stderr.write(`warning: git does not ignore ${envFile}, so its secret values could be committed; add it to .gitignore
|
|
2555
3040
|
`);
|
|
2556
3041
|
}
|
|
2557
3042
|
}
|
|
2558
3043
|
function gitWouldCommit(file) {
|
|
2559
|
-
const r = spawnSync("git", ["check-ignore", "-q",
|
|
3044
|
+
const r = spawnSync("git", ["check-ignore", "-q", path6.basename(file)], { cwd: path6.dirname(file) });
|
|
2560
3045
|
return r.status === 1;
|
|
2561
3046
|
}
|
|
2562
3047
|
async function resolvedPath(p) {
|
|
2563
|
-
const abs =
|
|
3048
|
+
const abs = path6.resolve(p);
|
|
2564
3049
|
let existing = abs;
|
|
2565
|
-
while (!
|
|
2566
|
-
return
|
|
3050
|
+
while (!existsSync6(existing) && path6.dirname(existing) !== existing) existing = path6.dirname(existing);
|
|
3051
|
+
return path6.join(await realpath4(existing), path6.relative(existing, abs));
|
|
2567
3052
|
}
|
|
2568
3053
|
function isWithin(child, parent) {
|
|
2569
3054
|
const norm = (p) => process.platform === "win32" ? p.toLowerCase() : p;
|
|
2570
|
-
const rel =
|
|
2571
|
-
return rel === "" || rel !== ".." && !rel.startsWith(`..${
|
|
3055
|
+
const rel = path6.relative(norm(parent), norm(child));
|
|
3056
|
+
return rel === "" || rel !== ".." && !rel.startsWith(`..${path6.sep}`) && !path6.isAbsolute(rel);
|
|
2572
3057
|
}
|
|
2573
3058
|
async function preflightTree(root, envFile) {
|
|
2574
3059
|
const [realRoot, realEnv] = await Promise.all([resolvedPath(root), resolvedPath(envFile)]);
|
|
2575
|
-
const doomed = [...MANAGED_DIRS, STAGING_DIR].find(
|
|
2576
|
-
(d) => isWithin(
|
|
3060
|
+
const doomed = [...MANAGED_DIRS, STAGING_DIR, JOURNAL, "channelvault.json", ".gitignore", ".secrets"].find(
|
|
3061
|
+
(d) => isWithin(path6.resolve(envFile), path6.resolve(root, d)) || isWithin(realEnv, path6.join(realRoot, d))
|
|
2577
3062
|
);
|
|
2578
3063
|
if (doomed) fail(`the env file ${envFile} is inside ${doomed}/, which this command replaces; keep it elsewhere`);
|
|
2579
|
-
const metaPath =
|
|
2580
|
-
if (
|
|
3064
|
+
const metaPath = path6.join(root, "channelvault.json");
|
|
3065
|
+
if (existsSync6(metaPath)) {
|
|
2581
3066
|
let meta;
|
|
2582
3067
|
try {
|
|
2583
3068
|
meta = await readJson(metaPath);
|
|
@@ -2591,7 +3076,7 @@ async function preflightTree(root, envFile) {
|
|
|
2591
3076
|
}
|
|
2592
3077
|
return meta;
|
|
2593
3078
|
}
|
|
2594
|
-
const foreign = MANAGED_DIRS.filter((d) =>
|
|
3079
|
+
const foreign = MANAGED_DIRS.filter((d) => existsSync6(path6.join(root, d)));
|
|
2595
3080
|
if (foreign.length > 0) {
|
|
2596
3081
|
fail(
|
|
2597
3082
|
`${root} is not a channelvault tree (no channelvault.json) but has ${foreign.map((d) => `${d}/`).join(", ")}, which this command would replace; nothing was written. Use a new or empty directory (or, if an earlier pull or explode into it was interrupted, delete those directories).`
|
|
@@ -2599,27 +3084,14 @@ async function preflightTree(root, envFile) {
|
|
|
2599
3084
|
}
|
|
2600
3085
|
return null;
|
|
2601
3086
|
}
|
|
2602
|
-
async function replaceTree(root, config) {
|
|
2603
|
-
const staging = path5.join(root, STAGING_DIR);
|
|
2604
|
-
await rm3(staging, RM_OPTS);
|
|
2605
|
-
try {
|
|
2606
|
-
await engine.explode(config, { root: staging });
|
|
2607
|
-
for (const d of MANAGED_DIRS) {
|
|
2608
|
-
await rm3(path5.join(root, d), RM_OPTS);
|
|
2609
|
-
if (existsSync5(path5.join(staging, d))) await rename3(path5.join(staging, d), path5.join(root, d));
|
|
2610
|
-
}
|
|
2611
|
-
} finally {
|
|
2612
|
-
await rm3(staging, RM_OPTS);
|
|
2613
|
-
}
|
|
2614
|
-
}
|
|
2615
3087
|
function assertTree(root) {
|
|
2616
|
-
if (!
|
|
3088
|
+
if (!existsSync6(path6.join(root, "server", "configuration.json"))) {
|
|
2617
3089
|
fail(`${root} is not a channelvault tree (missing server/configuration.json). Run 'pull' or 'explode' first.`);
|
|
2618
3090
|
}
|
|
2619
3091
|
}
|
|
2620
3092
|
async function readTreeOrigin(root) {
|
|
2621
|
-
const metaPath =
|
|
2622
|
-
if (!
|
|
3093
|
+
const metaPath = path6.join(root, "channelvault.json");
|
|
3094
|
+
if (!existsSync6(metaPath)) return "unknown";
|
|
2623
3095
|
try {
|
|
2624
3096
|
const meta = await readJson(metaPath);
|
|
2625
3097
|
if (typeof meta.source === "string") {
|
|
@@ -2646,18 +3118,28 @@ async function assertCompatibleOrigin(root, config, wants, force) {
|
|
|
2646
3118
|
function collect(value, previous) {
|
|
2647
3119
|
return [...previous ?? [], value];
|
|
2648
3120
|
}
|
|
3121
|
+
async function bindingProblems(root, serverId) {
|
|
3122
|
+
const file = path6.join(root, "channelvault.json");
|
|
3123
|
+
const meta = existsSync6(file) ? await readJson(file) : null;
|
|
3124
|
+
if (meta?.serverId === serverId) return [];
|
|
3125
|
+
return [`this tree's baseline belongs to ${meta?.serverId ? `installation ${meta.serverId}` : "an unknown installation"}, not the target (${serverId}); pull the target and merge your edits, or review with 'adopt <dir> --plan-only' and run 'adopt <dir>' to establish its baseline; --force does not bypass installation binding`];
|
|
3126
|
+
}
|
|
3127
|
+
async function assertBinding(client, root) {
|
|
3128
|
+
const problems = await bindingProblems(root, await client.getServerId());
|
|
3129
|
+
if (problems.length) fail(problems.join("\n"));
|
|
3130
|
+
}
|
|
2649
3131
|
async function readKnown(root) {
|
|
2650
|
-
const metaPath =
|
|
2651
|
-
if (!
|
|
3132
|
+
const metaPath = path6.join(root, "channelvault.json");
|
|
3133
|
+
if (!existsSync6(metaPath)) return void 0;
|
|
2652
3134
|
return knownFrom((await readJson(metaPath)).resources);
|
|
2653
3135
|
}
|
|
2654
3136
|
async function writeKnown(root, known) {
|
|
2655
|
-
const metaPath =
|
|
2656
|
-
if (!
|
|
3137
|
+
const metaPath = path6.join(root, "channelvault.json");
|
|
3138
|
+
if (!existsSync6(metaPath)) return;
|
|
2657
3139
|
const meta = await readJson(metaPath);
|
|
2658
3140
|
if (!meta.resources) return;
|
|
2659
3141
|
meta.resources = known;
|
|
2660
|
-
await
|
|
3142
|
+
await writeFile6(metaPath, JSON.stringify(meta, null, 2) + "\n", "utf8");
|
|
2661
3143
|
}
|
|
2662
3144
|
function printNameChange(incoming, current) {
|
|
2663
3145
|
const [to, from] = [configuredName(incoming), configuredName(current)];
|
|
@@ -2699,6 +3181,7 @@ function reportPlanOnly(flags, plan, problems, extra) {
|
|
|
2699
3181
|
writeJson2({
|
|
2700
3182
|
target: extra.target,
|
|
2701
3183
|
mode: extra.mode,
|
|
3184
|
+
...extra.serverId ? { serverId: extra.serverId } : {},
|
|
2702
3185
|
changes: plan.changes,
|
|
2703
3186
|
conflicts: plan.conflicts,
|
|
2704
3187
|
serverOnly: plan.serverOnly,
|
|
@@ -2716,6 +3199,7 @@ async function scopedPush(client, root, local, scope, target, flags) {
|
|
|
2716
3199
|
const remote = await client.getServerConfiguration();
|
|
2717
3200
|
const known = await readKnown(root);
|
|
2718
3201
|
const plan = planPush(local, remote, scope, known);
|
|
3202
|
+
const problems = [...await bindingProblems(root, await client.getServerId()), ...planProblems(plan, flags)];
|
|
2719
3203
|
const names = new Map(
|
|
2720
3204
|
[...channelsOf(remote), ...channelsOf(local)].map((c) => [String(c["id"]), String(c["name"])])
|
|
2721
3205
|
);
|
|
@@ -2725,7 +3209,7 @@ async function scopedPush(client, root, local, scope, target, flags) {
|
|
|
2725
3209
|
const notDeployed = flags.deploy ? plan.deployIds.filter((id) => !deployed.has(id)) : [];
|
|
2726
3210
|
if (flags.planOnly && flags.json) {
|
|
2727
3211
|
const redeploy = flags.deploy ? { redeploy: toDeploy.map(nameOf2), notRedeployed: notDeployed.map(nameOf2) } : {};
|
|
2728
|
-
reportPlanOnly(flags, plan,
|
|
3212
|
+
reportPlanOnly(flags, plan, problems, { target, mode: "scoped", ...redeploy });
|
|
2729
3213
|
return;
|
|
2730
3214
|
}
|
|
2731
3215
|
if (plan.changes.length === 0) {
|
|
@@ -2751,12 +3235,11 @@ async function scopedPush(client, root, local, scope, target, flags) {
|
|
|
2751
3235
|
`);
|
|
2752
3236
|
}
|
|
2753
3237
|
if (flags.planOnly) {
|
|
2754
|
-
reportPlanOnly(flags, plan,
|
|
3238
|
+
reportPlanOnly(flags, plan, problems, { target, mode: "scoped" });
|
|
2755
3239
|
return;
|
|
2756
3240
|
}
|
|
2757
|
-
if (plan.changes.length === 0) return;
|
|
2758
|
-
const problems = planProblems(plan, flags);
|
|
2759
3241
|
if (problems.length > 0) fail(problems.join("\n"));
|
|
3242
|
+
if (plan.changes.length === 0) return;
|
|
2760
3243
|
if (!flags.yes && !await confirm("Continue?")) {
|
|
2761
3244
|
process.stdout.write("aborted.\n");
|
|
2762
3245
|
return;
|
|
@@ -2769,11 +3252,18 @@ async function scopedPush(client, root, local, scope, target, flags) {
|
|
|
2769
3252
|
pull and try again, or pass --force`);
|
|
2770
3253
|
}
|
|
2771
3254
|
await backupBeforePush(client, flags);
|
|
2772
|
-
const
|
|
3255
|
+
const afterBackup = await client.getServerConfiguration();
|
|
3256
|
+
const changedDuringBackup = changedSince(plan, fresh, afterBackup);
|
|
3257
|
+
if (!flags.force && changedDuringBackup.length) {
|
|
3258
|
+
fail(`changed on the server during backup: ${changedDuringBackup.join(", ")}; pull and try again`);
|
|
3259
|
+
}
|
|
3260
|
+
await assertBinding(client, root);
|
|
3261
|
+
const result = await applyPlan(client, plan, local, afterBackup, scope, { force: flags.force === true });
|
|
2773
3262
|
try {
|
|
2774
3263
|
const after = await client.getServerConfiguration();
|
|
2775
3264
|
const refreshedLibraries = librariesOf(local).filter((l) => result.touchedIds.has(String(l["id"]))).map((l) => ({ kind: "library", op: "update", id: String(l["id"]), label: String(l["name"]) }));
|
|
2776
|
-
const
|
|
3265
|
+
const membershipSent = result.sentLibraries ? { ...local, codeTemplateLibraries: { codeTemplateLibrary: result.sentLibraries } } : local;
|
|
3266
|
+
const changedAgain = [...result.applied, ...refreshedLibraries].filter((c) => !savedChangeMatches(c, c.kind === "library" ? membershipSent : local, after));
|
|
2777
3267
|
if (changedAgain.length > 0) fail(`changed again after saving: ${[...new Set(changedAgain.map((c) => c.label))].join(", ")}; pull and review before retrying`);
|
|
2778
3268
|
if (result.touchedIds.size > 0) await refreshRevisions(root, after, result.touchedIds);
|
|
2779
3269
|
if (known) await writeKnown(root, knownAfterPush(known, result.applied, result.touchedIds, after));
|
|
@@ -2790,8 +3280,10 @@ pull and try again, or pass --force`);
|
|
|
2790
3280
|
process.stdout.write(`pushed ${result.applied.length} change(s)
|
|
2791
3281
|
`);
|
|
2792
3282
|
if (toDeploy.length > 0) {
|
|
2793
|
-
const failures = await deployChannels(client, toDeploy, nameOf2);
|
|
2794
|
-
process.stdout.write(`deployed ${
|
|
3283
|
+
const { deployed: deployed2, skipped, failures } = await deployChannels(client, toDeploy, nameOf2);
|
|
3284
|
+
process.stdout.write(`deployed ${deployed2.length} of ${toDeploy.length} channel(s)
|
|
3285
|
+
`);
|
|
3286
|
+
if (skipped.length) process.stdout.write(`redeploy skipped (no longer deployed): ${skipped.join(", ")}
|
|
2795
3287
|
`);
|
|
2796
3288
|
for (const f of failures) process.stderr.write(`deploy failed: ${f.name}: ${scrub(f.error)}
|
|
2797
3289
|
`);
|
|
@@ -2802,8 +3294,9 @@ async function wholeServerPush(client, root, local, target, flags) {
|
|
|
2802
3294
|
const remote = await client.getServerConfiguration();
|
|
2803
3295
|
const known = await readKnown(root);
|
|
2804
3296
|
const plan = planPush(local, remote, {}, known, { wholeReplace: true });
|
|
3297
|
+
const problems = [...await bindingProblems(root, await client.getServerId()), ...wholeServerProblems(plan, flags)];
|
|
2805
3298
|
if (flags.planOnly && flags.json) {
|
|
2806
|
-
reportPlanOnly(flags, plan,
|
|
3299
|
+
reportPlanOnly(flags, plan, problems, { target, mode: "whole-server" });
|
|
2807
3300
|
return;
|
|
2808
3301
|
}
|
|
2809
3302
|
const s = summarize(local);
|
|
@@ -2823,7 +3316,6 @@ async function wholeServerPush(client, root, local, target, flags) {
|
|
|
2823
3316
|
if (replaced.length > 0) process.stdout.write(`also replaced: ${replaced.join(", ")}
|
|
2824
3317
|
`);
|
|
2825
3318
|
if (keptMap) process.stdout.write("configuration map differs but is kept (--overwrite-config-map replaces it)\n");
|
|
2826
|
-
const problems = wholeServerProblems(plan, flags);
|
|
2827
3319
|
if (flags.planOnly) {
|
|
2828
3320
|
reportPlanOnly(flags, plan, problems, { target, mode: "whole-server" });
|
|
2829
3321
|
return;
|
|
@@ -2842,6 +3334,13 @@ async function wholeServerPush(client, root, local, target, flags) {
|
|
|
2842
3334
|
fail("the replace now deletes resources from the server; review the new plan and pass --allow-deletes");
|
|
2843
3335
|
}
|
|
2844
3336
|
await backupBeforePush(client, flags);
|
|
3337
|
+
const afterBackup = await client.getServerConfiguration();
|
|
3338
|
+
if (!sameServerConfig(fresh, afterBackup) && !flags.force) fail("the server changed during backup; pull and try again");
|
|
3339
|
+
const finalPlan = planPush(local, afterBackup, {}, known, { wholeReplace: true });
|
|
3340
|
+
if (!flags.allowDeletes && (finalPlan.serverOnly.length || finalPlan.changes.some((c) => c.op === "delete"))) {
|
|
3341
|
+
fail("the replace now deletes resources from the server; review the new plan and pass --allow-deletes");
|
|
3342
|
+
}
|
|
3343
|
+
await assertBinding(client, root);
|
|
2845
3344
|
await client.putServerConfiguration(local, {
|
|
2846
3345
|
deploy: flags.deploy === true,
|
|
2847
3346
|
overwriteConfigMap: flags.overwriteConfigMap === true
|
|
@@ -2862,8 +3361,8 @@ addExtractFlag(addEnvFlag(
|
|
|
2862
3361
|
program.command("explode").description("Explode a Mirth backup XML into a working tree").argument("<backup.xml>", "path to a Mirth backup config XML file").argument("<dir>", "output working-tree directory")
|
|
2863
3362
|
)).action(async (backupPath, dir, flags) => {
|
|
2864
3363
|
const config = xml.parse(await readFile5(backupPath, "utf8"));
|
|
2865
|
-
const root =
|
|
2866
|
-
await writeTree(root, config, `file:${
|
|
3364
|
+
const root = path6.resolve(dir);
|
|
3365
|
+
await writeTree(root, config, `file:${path6.resolve(backupPath)}`, flags);
|
|
2867
3366
|
const s = summarize(config);
|
|
2868
3367
|
process.stdout.write(`exploded ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}
|
|
2869
3368
|
`);
|
|
@@ -2871,27 +3370,81 @@ addExtractFlag(addEnvFlag(
|
|
|
2871
3370
|
addEnvFlag(
|
|
2872
3371
|
program.command("implode").description("Reassemble a working tree into a Mirth backup XML").argument("<dir>", "working-tree directory").argument("<backup.xml>", "output XML path").option("--force", "implode even if the tree was pulled from a live server", false)
|
|
2873
3372
|
).action(async (dir, outPath, flags) => {
|
|
2874
|
-
const root =
|
|
3373
|
+
const root = path6.resolve(dir);
|
|
2875
3374
|
assertTree(root);
|
|
2876
3375
|
const config = await renderedTree(root, flags);
|
|
2877
3376
|
await assertCompatibleOrigin(root, config, "xml", flags.force === true);
|
|
2878
3377
|
const xmlStr = xml.build(config);
|
|
2879
|
-
await
|
|
2880
|
-
process.stdout.write(`imploded ${root} -> ${
|
|
3378
|
+
await writeFile6(outPath, xmlStr, "utf8");
|
|
3379
|
+
process.stdout.write(`imploded ${root} -> ${path6.resolve(outPath)}
|
|
2881
3380
|
`);
|
|
2882
3381
|
});
|
|
2883
3382
|
addExtractFlag(addEnvFlag(addConnectionFlags(
|
|
2884
3383
|
program.command("pull").description("Pull the live server configuration into a working tree").argument("<dir>", "working-tree directory")
|
|
2885
3384
|
))).action(async (dir, flags) => {
|
|
2886
|
-
const root =
|
|
3385
|
+
const root = path6.resolve(dir);
|
|
2887
3386
|
await preflightTree(root, envFilePath(root, flags));
|
|
2888
|
-
const config = await withClient(flags, (client) =>
|
|
3387
|
+
const { config, serverId } = await withClient(flags, async (client) => {
|
|
3388
|
+
const serverId2 = await client.getServerId();
|
|
3389
|
+
const config2 = await client.getServerConfiguration();
|
|
3390
|
+
if (await client.getServerId() !== serverId2) fail("the installation changed while pulling; nothing was written");
|
|
3391
|
+
return { config: config2, serverId: serverId2 };
|
|
3392
|
+
});
|
|
2889
3393
|
const cfg = resolveClientConfig(flags);
|
|
2890
|
-
await writeTree(root, config, `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`, flags);
|
|
3394
|
+
await writeTree(root, config, `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`, flags, serverId);
|
|
2891
3395
|
const s = summarize(config);
|
|
2892
3396
|
process.stdout.write(`pulled ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}
|
|
2893
3397
|
`);
|
|
2894
3398
|
});
|
|
3399
|
+
addJsonFlag(addEnvFlag(addConnectionFlags(
|
|
3400
|
+
program.command("adopt").description("Review and capture this installation as the tree baseline, preserving local content; writes no server resources").argument("<dir>", "working-tree directory").option("--plan-only", "preview the resulting push plan without changing the tree", false).option("-y, --yes", "accept the reviewed destination baseline without a prompt", false)
|
|
3401
|
+
))).action(async (dir, flags) => {
|
|
3402
|
+
const root = path6.resolve(dir);
|
|
3403
|
+
assertTree(root);
|
|
3404
|
+
const previous = await preflightTree(root, envFilePath(root, flags));
|
|
3405
|
+
const stored = await engine.implode({ root });
|
|
3406
|
+
const local = await renderedTree(root, flags);
|
|
3407
|
+
await assertCompatibleOrigin(root, local, "live", false);
|
|
3408
|
+
if (flags.json && !flags.planOnly) fail("--json needs --plan-only");
|
|
3409
|
+
if (!flags.yes && !flags.planOnly && !process.stdin.isTTY) fail("no terminal to confirm on; review with `adopt --plan-only` and pass --yes");
|
|
3410
|
+
const cfg = resolveClientConfig(flags);
|
|
3411
|
+
const target = `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`;
|
|
3412
|
+
await withClient(flags, async (client) => {
|
|
3413
|
+
const serverId = await client.getServerId();
|
|
3414
|
+
const remote = await client.getServerConfiguration();
|
|
3415
|
+
const adopted = adoptTarget(local, remote);
|
|
3416
|
+
const plan = planPush(adopted.config, remote, {}, adopted.known);
|
|
3417
|
+
if (!flags.json) {
|
|
3418
|
+
process.stdout.write(`Adopt ${target} (installation ${serverId}) as this tree's baseline.
|
|
3419
|
+
Local content is preserved; the following differences become reviewed edits for a subsequent push:
|
|
3420
|
+
`);
|
|
3421
|
+
printChanges(plan);
|
|
3422
|
+
if (plan.serverOnly.length) process.stdout.write(`left alone: ${plan.serverOnly.join(", ")}
|
|
3423
|
+
`);
|
|
3424
|
+
if (plan.notPushed.length) process.stdout.write(`not pushed by scoped push: ${plan.notPushed.join(", ")}
|
|
3425
|
+
`);
|
|
3426
|
+
}
|
|
3427
|
+
if (flags.planOnly) {
|
|
3428
|
+
reportPlanOnly(flags, plan, planProblems(plan, {}), { target, mode: "adopt", serverId });
|
|
3429
|
+
return;
|
|
3430
|
+
}
|
|
3431
|
+
if (!flags.yes && !await confirm("Accept this baseline?")) {
|
|
3432
|
+
process.stdout.write("aborted.\n");
|
|
3433
|
+
return;
|
|
3434
|
+
}
|
|
3435
|
+
if (await client.getServerId() !== serverId || !sameServerConfig(remote, await client.getServerConfiguration())) {
|
|
3436
|
+
fail("the target changed while adopting; nothing was written. Review the new baseline and try again");
|
|
3437
|
+
}
|
|
3438
|
+
if (!sameServerConfig(stored, await engine.implode({ root }))) fail("the local tree changed while adopting; nothing was written");
|
|
3439
|
+
await replaceTree(root, envFilePath(root, flags), async (next) => {
|
|
3440
|
+
const rebased = adoptTarget(stored, remote);
|
|
3441
|
+
await engine.explode(rebased.config, { root: next });
|
|
3442
|
+
await writeMeta(next, target, rebased.config, previous, serverId, adopted.known);
|
|
3443
|
+
});
|
|
3444
|
+
process.stdout.write(`adopted installation ${serverId}; review with push --plan-only before writing the server
|
|
3445
|
+
`);
|
|
3446
|
+
});
|
|
3447
|
+
});
|
|
2895
3448
|
addBackupDirFlags(addEnvFlag(addConnectionFlags(
|
|
2896
3449
|
program.command("push").description("Push changed channels, code templates and global scripts to the live server").argument("<dir>", "working-tree directory").option("--channel <name>", "only this channel (name or id); repeatable", collect).option("--library <name>", "only this code template library (name or id); repeatable", collect).option("--global-scripts", "with --channel/--library: also push global scripts").option("--allow-deletes", "delete server resources that are missing from the tree", false).option("--deploy", "redeploy the changed channels and the channels using changed code templates", false).option("--force", "push even if the server changed since the last pull (overwrites the server's version)", false).option("--ignore-origin", "push a tree that was exploded from an XML backup (normally refused)", false).option("--whole-server", "replace the entire server configuration instead (settings, config map, groups too)", false).option("--overwrite-config-map", "with --whole-server: also overwrite the configuration map", false).option("--no-backup", "skip the backup of the server taken before anything changes").option("--plan-only", "show what would be pushed and what would stop it; change nothing (no prompt)", false).option("--json", "with --plan-only: print the plan as one JSON document", false).option("-y, --yes", "skip the confirmation prompt", false)
|
|
2897
3450
|
))).action(
|
|
@@ -2899,7 +3452,8 @@ addBackupDirFlags(addEnvFlag(addConnectionFlags(
|
|
|
2899
3452
|
if (flags.wholeServer && (flags.channel || flags.library || flags.globalScripts)) {
|
|
2900
3453
|
fail("--whole-server replaces everything; it cannot be combined with --channel, --library or --global-scripts");
|
|
2901
3454
|
}
|
|
2902
|
-
|
|
3455
|
+
if (flags.overwriteConfigMap && !flags.wholeServer) fail("--overwrite-config-map needs --whole-server");
|
|
3456
|
+
const root = path6.resolve(dir);
|
|
2903
3457
|
assertTree(root);
|
|
2904
3458
|
const config = await renderedTree(root, flags);
|
|
2905
3459
|
await assertCompatibleOrigin(root, config, "live", flags.ignoreOrigin === true);
|
|
@@ -2925,10 +3479,10 @@ addBackupDirFlags(addConnectionFlags(
|
|
|
2925
3479
|
const file = await withClient(flags, async (client) => {
|
|
2926
3480
|
const text = await client.getServerConfigurationXml();
|
|
2927
3481
|
if (!flags.out) return saveServerBackup(client, text, flags);
|
|
2928
|
-
const out =
|
|
3482
|
+
const out = path6.resolve(flags.out);
|
|
2929
3483
|
parseBackup(text, "the server configuration");
|
|
2930
|
-
if (
|
|
2931
|
-
await
|
|
3484
|
+
if (existsSync6(out)) fail(`${out} already exists; choose another name`);
|
|
3485
|
+
await mkdir5(path6.dirname(out), { recursive: true });
|
|
2932
3486
|
await writePrivate(out, text);
|
|
2933
3487
|
if (gitWouldCommit(out)) {
|
|
2934
3488
|
process.stderr.write(`warning: git does not ignore ${out}, which holds credentials in plain text; add it to .gitignore
|
|
@@ -2952,8 +3506,8 @@ addBackupDirFlags(addConnectionFlags(
|
|
|
2952
3506
|
const serverId = await client.getServerId();
|
|
2953
3507
|
let chosen;
|
|
2954
3508
|
if (file) {
|
|
2955
|
-
chosen =
|
|
2956
|
-
if (!
|
|
3509
|
+
chosen = path6.resolve(file);
|
|
3510
|
+
if (!existsSync6(chosen)) fail(`${chosen} does not exist`);
|
|
2957
3511
|
} else {
|
|
2958
3512
|
const mine = await backupsOf(dir, serverId);
|
|
2959
3513
|
if (mine.length === 0) {
|
|
@@ -2974,7 +3528,7 @@ addBackupDirFlags(addConnectionFlags(
|
|
|
2974
3528
|
if (fromContent !== "" && fromServer !== "" && fromContent !== fromServer && !flags.force) {
|
|
2975
3529
|
fail(`${chosen} is a backup of ${fromContent}, not ${fromServer}; pass --force to restore it here anyway`);
|
|
2976
3530
|
}
|
|
2977
|
-
process.stderr.write(`warning: ${chosen} is not in ${
|
|
3531
|
+
process.stderr.write(`warning: ${chosen} is not in ${path6.join(dir, MANIFEST)}, so which server it came from cannot be checked
|
|
2978
3532
|
`);
|
|
2979
3533
|
}
|
|
2980
3534
|
const [bv, sv] = [backup["@_version"], current["@_version"]];
|
|
@@ -3009,8 +3563,13 @@ to ${target}, replacing its ENTIRE configuration${flags.deploy ? ", then redeplo
|
|
|
3009
3563
|
fail("the server changed while this restore was being confirmed; nothing was restored. Run it again to review the new state");
|
|
3010
3564
|
}
|
|
3011
3565
|
const undo = await saveServerBackup(client, freshText, flags, chosen);
|
|
3012
|
-
process.stdout.write(`saved the current configuration to ${undo} (undo with:
|
|
3566
|
+
process.stdout.write(`saved the current configuration to ${undo} (undo with: ${undoCommand(undo, flags)})
|
|
3013
3567
|
`);
|
|
3568
|
+
printUndoLimits(flags);
|
|
3569
|
+
const afterBackup = parseBackup(await client.getServerConfigurationXml(), "the server configuration");
|
|
3570
|
+
if (!sameServerConfig(parseBackup(freshText, "the server configuration"), afterBackup)) {
|
|
3571
|
+
fail("the server changed during the undo backup; nothing was restored. Run it again to review the new state");
|
|
3572
|
+
}
|
|
3014
3573
|
await client.putServerConfigurationXml(text, { deploy: flags.deploy === true, overwriteConfigMap: flags.overwriteConfigMap === true });
|
|
3015
3574
|
const after = parseBackup(await client.getServerConfigurationXml(), "the server configuration");
|
|
3016
3575
|
const differ = planPush(backup, after, {}, void 0, { wholeReplace: true }).changes;
|
|
@@ -3028,7 +3587,7 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
|
|
|
3028
3587
|
})
|
|
3029
3588
|
))).action(async (dir, flags) => {
|
|
3030
3589
|
errorExitCode = 2;
|
|
3031
|
-
const root =
|
|
3590
|
+
const root = path6.resolve(dir);
|
|
3032
3591
|
assertTree(root);
|
|
3033
3592
|
const fetched = await withClient(flags, (client) => client.getServerConfiguration());
|
|
3034
3593
|
const tree = await engine.implode({ root });
|
|
@@ -3038,23 +3597,27 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
|
|
|
3038
3597
|
...notes
|
|
3039
3598
|
];
|
|
3040
3599
|
const allow = await readAllow(root);
|
|
3041
|
-
const
|
|
3042
|
-
|
|
3600
|
+
const staleRevisions = newerOnServer(tree, templatedRemote);
|
|
3601
|
+
if (staleRevisions.length > 0) {
|
|
3602
|
+
messages.push(`${staleRevisions.length} resource(s) have a newer revision on the server; pull to update the tree's baseline`);
|
|
3603
|
+
}
|
|
3604
|
+
const treeView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withoutVolatile(tree))), { mode: "redact", allow });
|
|
3605
|
+
const serverView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withoutVolatile(templatedRemote))), { mode: "redact", allow });
|
|
3043
3606
|
if (treeView.findings.length > 0) {
|
|
3044
3607
|
messages.push(`the tree holds ${treeView.findings.length} unextracted secret(s), redacted below; pull --extract-secrets`);
|
|
3045
3608
|
}
|
|
3046
3609
|
if (serverView.findings.length > 0) messages.push(`${serverView.findings.length} possible secret(s) on the server are redacted below`);
|
|
3047
3610
|
if (!flags.json) for (const m of messages) process.stderr.write(`note: ${m}
|
|
3048
3611
|
`);
|
|
3049
|
-
const tmp = await mkdtemp(
|
|
3612
|
+
const tmp = await mkdtemp(path6.join(tmpdir(), "channelvault-diff-"));
|
|
3050
3613
|
try {
|
|
3051
|
-
await engine.explode(treeView.config, { root:
|
|
3052
|
-
await engine.explode(serverView.config, { root:
|
|
3053
|
-
await
|
|
3614
|
+
await engine.explode(treeView.config, { root: path6.join(tmp, "tree") });
|
|
3615
|
+
await engine.explode(serverView.config, { root: path6.join(tmp, "server") });
|
|
3616
|
+
await mkdir5(path6.join(tmp, ".empty"));
|
|
3054
3617
|
const chunks = [];
|
|
3055
3618
|
for (const d of MANAGED_DIRS) {
|
|
3056
|
-
const local =
|
|
3057
|
-
const server =
|
|
3619
|
+
const local = existsSync6(path6.join(tmp, "tree", d)) ? `tree/${d}` : ".empty";
|
|
3620
|
+
const server = existsSync6(path6.join(tmp, "server", d)) ? `server/${d}` : ".empty";
|
|
3058
3621
|
if (local === ".empty" && server === ".empty") continue;
|
|
3059
3622
|
const result = spawnSync(
|
|
3060
3623
|
"git",
|
|
@@ -3076,8 +3639,8 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
|
|
|
3076
3639
|
const clean = out === "" && secretDrift.length === 0;
|
|
3077
3640
|
if (!clean) process.exitCode = 1;
|
|
3078
3641
|
if (flags.json) {
|
|
3079
|
-
const files = await changedFiles(
|
|
3080
|
-
writeJson2({ clean, files, secretDrift, notes: messages, patch: out });
|
|
3642
|
+
const files = await changedFiles(path6.join(tmp, "tree"), path6.join(tmp, "server"));
|
|
3643
|
+
writeJson2({ clean, files, secretDrift, staleRevisions, notes: messages, patch: out });
|
|
3081
3644
|
} else if (clean) {
|
|
3082
3645
|
process.stdout.write("no differences \u2014 working tree matches the server.\n");
|
|
3083
3646
|
} else {
|
|
@@ -3088,16 +3651,16 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
|
|
|
3088
3651
|
}
|
|
3089
3652
|
}
|
|
3090
3653
|
} finally {
|
|
3091
|
-
await
|
|
3654
|
+
await rm4(tmp, RM_OPTS);
|
|
3092
3655
|
}
|
|
3093
3656
|
});
|
|
3094
3657
|
async function changedFiles(treeDir, serverDir) {
|
|
3095
3658
|
const list2 = async (base) => {
|
|
3096
3659
|
const out = [];
|
|
3097
3660
|
for (const d of MANAGED_DIRS) {
|
|
3098
|
-
if (!
|
|
3099
|
-
for (const entry of await
|
|
3100
|
-
if (entry.isFile()) out.push(
|
|
3661
|
+
if (!existsSync6(path6.join(base, d))) continue;
|
|
3662
|
+
for (const entry of await readdir5(path6.join(base, d), { recursive: true, withFileTypes: true })) {
|
|
3663
|
+
if (entry.isFile()) out.push(path6.relative(base, path6.join(entry.parentPath, entry.name)).split(path6.sep).join("/"));
|
|
3101
3664
|
}
|
|
3102
3665
|
}
|
|
3103
3666
|
return out;
|
|
@@ -3107,21 +3670,21 @@ async function changedFiles(treeDir, serverDir) {
|
|
|
3107
3670
|
const files = [];
|
|
3108
3671
|
for (const p of local) {
|
|
3109
3672
|
if (!remoteSet.has(p)) files.push({ path: p, change: "only-in-tree" });
|
|
3110
|
-
else if (await readFile5(
|
|
3673
|
+
else if (await readFile5(path6.join(treeDir, p), "utf8") !== await readFile5(path6.join(serverDir, p), "utf8")) files.push({ path: p, change: "modified" });
|
|
3111
3674
|
}
|
|
3112
3675
|
const localSet = new Set(local);
|
|
3113
3676
|
for (const p of remote) if (!localSet.has(p)) files.push({ path: p, change: "only-on-server" });
|
|
3114
3677
|
return files.sort((a, b) => a.path.localeCompare(b.path));
|
|
3115
3678
|
}
|
|
3116
|
-
addJsonFlag(
|
|
3679
|
+
addJsonFlag(addEnvFlag(
|
|
3117
3680
|
program.command("status").description("Summarize a working tree").argument("<dir>", "working-tree directory")
|
|
3118
|
-
).action(async (dir, flags) => {
|
|
3119
|
-
const root =
|
|
3681
|
+
)).action(async (dir, flags) => {
|
|
3682
|
+
const root = path6.resolve(dir);
|
|
3120
3683
|
assertTree(root);
|
|
3121
3684
|
const config = await engine.implode({ root });
|
|
3122
3685
|
const s = summarize(config);
|
|
3123
|
-
const metaPath =
|
|
3124
|
-
const meta =
|
|
3686
|
+
const metaPath = path6.join(root, "channelvault.json");
|
|
3687
|
+
const meta = existsSync6(metaPath) ? await readJson(metaPath) : null;
|
|
3125
3688
|
if (flags.json) {
|
|
3126
3689
|
writeJson2({ root, source: meta?.source ?? null, pulledAt: meta?.pulledAt ?? null, engineVersion: meta?.engineVersion ?? null, counts: s });
|
|
3127
3690
|
return;
|
|
@@ -3142,6 +3705,15 @@ code templates: ${s.codeTemplates}
|
|
|
3142
3705
|
`
|
|
3143
3706
|
);
|
|
3144
3707
|
});
|
|
3708
|
+
var unlock;
|
|
3709
|
+
program.hook("preAction", async (_program, command) => {
|
|
3710
|
+
const name = command.name();
|
|
3711
|
+
if (!["explode", "pull", "adopt", "push", "implode", "diff", "status"].includes(name)) return;
|
|
3712
|
+
if (name === "diff") errorExitCode = 2;
|
|
3713
|
+
const root = path6.resolve(String(command.processedArgs[name === "explode" ? 1 : 0]));
|
|
3714
|
+
unlock = await lockTree(root);
|
|
3715
|
+
await recoverTree(root, envFilePath(root, command.opts()));
|
|
3716
|
+
});
|
|
3145
3717
|
program.parseAsync().catch((err) => {
|
|
3146
3718
|
if (err instanceof CommanderError) return;
|
|
3147
3719
|
process.stderr.write(`error: ${scrub(err instanceof Error ? err.message : String(err))}
|
|
@@ -3157,5 +3729,15 @@ program.parseAsync().catch((err) => {
|
|
|
3157
3729
|
`);
|
|
3158
3730
|
}
|
|
3159
3731
|
process.exitCode = errorExitCode;
|
|
3732
|
+
}).finally(async () => {
|
|
3733
|
+
if (unlock) {
|
|
3734
|
+
try {
|
|
3735
|
+
await unlock();
|
|
3736
|
+
} catch (err) {
|
|
3737
|
+
process.stderr.write(`error: could not release working-tree lock: ${scrub(err instanceof Error ? err.message : String(err))}
|
|
3738
|
+
`);
|
|
3739
|
+
process.exitCode = errorExitCode;
|
|
3740
|
+
}
|
|
3741
|
+
}
|
|
3160
3742
|
});
|
|
3161
3743
|
//# sourceMappingURL=cli.js.map
|