@ubercode/channelvault 0.2.1 → 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 +28 -0
- package/README.md +26 -7
- package/dist/cli.js +700 -167
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +124 -18
- package/dist/index.js.map +1 -1
- 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
|
|
@@ -600,12 +600,13 @@ async function readWithinRoot(root, target, rel) {
|
|
|
600
600
|
}
|
|
601
601
|
return readFile2(realTarget, "utf8");
|
|
602
602
|
}
|
|
603
|
-
|
|
603
|
+
var pathKey = (file) => process.platform === "win32" ? file.toLowerCase() : file;
|
|
604
|
+
async function resolveMarkers(value, jsonDir, root, referenced) {
|
|
604
605
|
if (Array.isArray(value)) {
|
|
605
606
|
const out = [];
|
|
606
607
|
for (const item of value) {
|
|
607
608
|
if (isRefMarker(item) && !existsSync(resolveWithinRoot(root, jsonDir, item["@ref"]))) continue;
|
|
608
|
-
out.push(await resolveMarkers(item, jsonDir, root));
|
|
609
|
+
out.push(await resolveMarkers(item, jsonDir, root, referenced));
|
|
609
610
|
}
|
|
610
611
|
return out;
|
|
611
612
|
}
|
|
@@ -616,25 +617,81 @@ async function resolveMarkers(value, jsonDir, root) {
|
|
|
616
617
|
if (isRefMarker(value)) {
|
|
617
618
|
const target = resolveWithinRoot(root, jsonDir, value["@ref"]);
|
|
618
619
|
const text = await readWithinRoot(root, target, value["@ref"]);
|
|
620
|
+
referenced.add(pathKey(await realpath(target)));
|
|
619
621
|
const parsed = parseJson(text, target);
|
|
620
|
-
return resolveMarkers(parsed, path.dirname(target), root);
|
|
622
|
+
return resolveMarkers(parsed, path.dirname(target), root, referenced);
|
|
621
623
|
}
|
|
622
624
|
if (isPlainObject(value)) {
|
|
623
625
|
const out = {};
|
|
624
626
|
for (const [k, v] of Object.entries(value)) {
|
|
625
627
|
if (isRefMarker(v) && !existsSync(resolveWithinRoot(root, jsonDir, v["@ref"]))) continue;
|
|
626
|
-
out[k] = await resolveMarkers(v, jsonDir, root);
|
|
628
|
+
out[k] = await resolveMarkers(v, jsonDir, root, referenced);
|
|
627
629
|
}
|
|
628
630
|
return out;
|
|
629
631
|
}
|
|
630
632
|
return value;
|
|
631
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
|
+
}
|
|
632
683
|
async function implode(opts) {
|
|
633
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
|
+
}
|
|
634
688
|
const serverDir = path.join(root, "server");
|
|
635
689
|
const configPath = path.join(serverDir, "configuration.json");
|
|
636
|
-
const parsed = await
|
|
637
|
-
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);
|
|
638
695
|
return resolved;
|
|
639
696
|
}
|
|
640
697
|
function createExplodeEngine() {
|
|
@@ -932,25 +989,31 @@ function elementSegment(el, index) {
|
|
|
932
989
|
if (el && typeof el === "object" && !Array.isArray(el)) {
|
|
933
990
|
const id = el["id"] ?? el["metaDataId"];
|
|
934
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}]`;
|
|
935
994
|
}
|
|
936
995
|
return `[${index}]`;
|
|
937
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
|
+
}
|
|
938
1002
|
function mapLeaves(config, visit) {
|
|
939
|
-
const walk = (node, key,
|
|
1003
|
+
const walk = (node, key, path7, labels, section, cmKey) => {
|
|
940
1004
|
if (typeof node === "string") {
|
|
941
|
-
return visit(node, { location:
|
|
1005
|
+
return visit(node, { location: path7.join("/"), key, labels, section, configMapKey: cmKey });
|
|
942
1006
|
}
|
|
943
1007
|
if (Array.isArray(node)) {
|
|
944
|
-
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));
|
|
945
1009
|
}
|
|
946
1010
|
if (node && typeof node === "object") {
|
|
947
1011
|
const name = node["name"];
|
|
948
1012
|
const inner = typeof name === "string" && name.trim() !== "" ? [...labels, name] : labels;
|
|
949
|
-
const
|
|
950
|
-
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;
|
|
951
1014
|
const out = {};
|
|
952
1015
|
for (const [k, v] of Object.entries(node)) {
|
|
953
|
-
out[k] = walk(v, k, [...
|
|
1016
|
+
out[k] = walk(v, k, [...path7, k], inner, section || k, mapKey);
|
|
954
1017
|
}
|
|
955
1018
|
return out;
|
|
956
1019
|
}
|
|
@@ -1292,6 +1355,41 @@ function formatFindings(findings) {
|
|
|
1292
1355
|
${"".padEnd(20)} at ${f.location} context ${f.context}`).join("\n");
|
|
1293
1356
|
}
|
|
1294
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
|
+
|
|
1295
1393
|
// src/client/index.ts
|
|
1296
1394
|
var UNTRUSTED_CERT_CODES = /* @__PURE__ */ new Set([
|
|
1297
1395
|
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
@@ -1405,16 +1503,20 @@ var MirthClientImpl = class {
|
|
|
1405
1503
|
/**
|
|
1406
1504
|
* GET /server/configuration -> canonical config.
|
|
1407
1505
|
*
|
|
1408
|
-
* Requests JSON
|
|
1409
|
-
*
|
|
1410
|
-
* 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.
|
|
1411
1508
|
*/
|
|
1412
1509
|
async getServerConfiguration() {
|
|
1413
1510
|
const response = await this.request("GET", "/server/configuration", {
|
|
1414
1511
|
headers: { Accept: "application/json" }
|
|
1415
1512
|
});
|
|
1416
|
-
|
|
1417
|
-
|
|
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);
|
|
1418
1520
|
}
|
|
1419
1521
|
/**
|
|
1420
1522
|
* PUT /server/configuration <- canonical config.
|
|
@@ -1442,7 +1544,9 @@ var MirthClientImpl = class {
|
|
|
1442
1544
|
}
|
|
1443
1545
|
async getServerId() {
|
|
1444
1546
|
const response = await this.request("GET", "/server/id", { headers: { Accept: "text/plain" } });
|
|
1445
|
-
|
|
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;
|
|
1446
1550
|
}
|
|
1447
1551
|
async getServerConfigurationXml() {
|
|
1448
1552
|
const response = await this.request("GET", "/server/configuration", { headers: { Accept: "application/xml" } });
|
|
@@ -1459,12 +1563,23 @@ var MirthClientImpl = class {
|
|
|
1459
1563
|
// Override is on: Mirth does not reject a stale revision anyway (verified on
|
|
1460
1564
|
// 4.5.2), so conflict detection happens in the push planner instead.
|
|
1461
1565
|
async getChannel(id) {
|
|
1462
|
-
|
|
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, {
|
|
1463
1573
|
headers: { Accept: "application/json" }
|
|
1574
|
+
}).catch((err) => {
|
|
1575
|
+
if (err.status === 404) return null;
|
|
1576
|
+
throw err;
|
|
1464
1577
|
});
|
|
1578
|
+
if (!response) return null;
|
|
1465
1579
|
const text = await response.text();
|
|
1466
1580
|
if (text.trim() === "") return null;
|
|
1467
|
-
|
|
1581
|
+
const parsed = JSON.parse(text);
|
|
1582
|
+
return parsed === null ? null : unwrapSingleKey(parsed);
|
|
1468
1583
|
}
|
|
1469
1584
|
async close() {
|
|
1470
1585
|
await this.dispatcher.close();
|
|
@@ -1498,15 +1613,15 @@ var MirthClientImpl = class {
|
|
|
1498
1613
|
await this.request("POST", `/channels/${encodeURIComponent(id)}/_deploy`, { query: { returnErrors: true } });
|
|
1499
1614
|
}
|
|
1500
1615
|
/** Send a JSON body; Mirth answers some updates with `{"boolean": false}` instead of an error status. */
|
|
1501
|
-
async sendJson(method,
|
|
1502
|
-
const response = await this.request(method,
|
|
1616
|
+
async sendJson(method, path7, body, query) {
|
|
1617
|
+
const response = await this.request(method, path7, {
|
|
1503
1618
|
query,
|
|
1504
1619
|
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
1505
1620
|
body: JSON.stringify(body)
|
|
1506
1621
|
});
|
|
1507
1622
|
const text = await response.text();
|
|
1508
1623
|
if (/^\s*\{\s*"boolean"\s*:\s*false\s*\}\s*$/.test(text)) {
|
|
1509
|
-
throw new Error(`${method} ${
|
|
1624
|
+
throw new Error(`${method} ${path7}: the server refused the update`);
|
|
1510
1625
|
}
|
|
1511
1626
|
}
|
|
1512
1627
|
// --- internal transport ---------------------------------------------------
|
|
@@ -1515,11 +1630,11 @@ var MirthClientImpl = class {
|
|
|
1515
1630
|
* on a 401 while authenticated resets auth, re-logs in once, and retries.
|
|
1516
1631
|
* Throws an {@link ApiError}-shaped error on a non-2xx response.
|
|
1517
1632
|
*/
|
|
1518
|
-
async request(method,
|
|
1633
|
+
async request(method, path7, options = {}, isRetry = false) {
|
|
1519
1634
|
if (!this.authenticated) {
|
|
1520
1635
|
await this.login();
|
|
1521
1636
|
}
|
|
1522
|
-
const url = this.buildUrl(
|
|
1637
|
+
const url = this.buildUrl(path7, options.query);
|
|
1523
1638
|
const headers = {
|
|
1524
1639
|
"X-Requested-With": "XMLHttpRequest",
|
|
1525
1640
|
...options.headers
|
|
@@ -1533,7 +1648,7 @@ var MirthClientImpl = class {
|
|
|
1533
1648
|
if (response.status === 401 && this.authenticated && !isRetry) {
|
|
1534
1649
|
this.authenticated = false;
|
|
1535
1650
|
await this.login();
|
|
1536
|
-
return this.request(method,
|
|
1651
|
+
return this.request(method, path7, options, true);
|
|
1537
1652
|
}
|
|
1538
1653
|
if (!response.ok) {
|
|
1539
1654
|
throw await this.toApiError(response);
|
|
@@ -1553,8 +1668,8 @@ var MirthClientImpl = class {
|
|
|
1553
1668
|
}
|
|
1554
1669
|
}
|
|
1555
1670
|
/** Build an absolute URL with an optional query string. */
|
|
1556
|
-
buildUrl(
|
|
1557
|
-
const url = `${this.baseUrl}${
|
|
1671
|
+
buildUrl(path7, query) {
|
|
1672
|
+
const url = `${this.baseUrl}${path7}`;
|
|
1558
1673
|
if (!query || Object.keys(query).length === 0) {
|
|
1559
1674
|
return url;
|
|
1560
1675
|
}
|
|
@@ -1659,8 +1774,17 @@ function same(a, b) {
|
|
|
1659
1774
|
}
|
|
1660
1775
|
return false;
|
|
1661
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
|
+
}
|
|
1662
1786
|
function stripVolatile(o) {
|
|
1663
|
-
const out = { ...o };
|
|
1787
|
+
const out = withSortedContexts({ ...o });
|
|
1664
1788
|
delete out["revision"];
|
|
1665
1789
|
delete out["lastModified"];
|
|
1666
1790
|
const exportData = out["exportData"];
|
|
@@ -1680,11 +1804,16 @@ function withoutVolatile(c) {
|
|
|
1680
1804
|
const strip = (o) => {
|
|
1681
1805
|
delete o["revision"];
|
|
1682
1806
|
delete o["lastModified"];
|
|
1683
|
-
const
|
|
1807
|
+
const exportData = o["exportData"];
|
|
1808
|
+
const md = isObj(exportData) ? exportData["metadata"] : void 0;
|
|
1684
1809
|
if (isObj(md)) {
|
|
1685
1810
|
delete md["lastModified"];
|
|
1686
1811
|
delete md["userId"];
|
|
1687
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"];
|
|
1688
1817
|
};
|
|
1689
1818
|
for (const ch of channelsOf(out)) strip(ch);
|
|
1690
1819
|
for (const lib of librariesOf(out)) {
|
|
@@ -1717,6 +1846,14 @@ function libraryShape(lib) {
|
|
|
1717
1846
|
out["codeTemplates"] = templatesOf2(lib).map(idOf);
|
|
1718
1847
|
return out;
|
|
1719
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
|
+
}
|
|
1720
1857
|
function hashGlobalScripts(c) {
|
|
1721
1858
|
return createHash2("sha256").update(JSON.stringify(normalizeEolDeep(c["globalScripts"] ?? null))).digest("hex");
|
|
1722
1859
|
}
|
|
@@ -1730,6 +1867,25 @@ function resourceIds(c) {
|
|
|
1730
1867
|
globalScripts: hashGlobalScripts(c)
|
|
1731
1868
|
};
|
|
1732
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
|
+
}
|
|
1733
1889
|
function knownFrom(raw) {
|
|
1734
1890
|
if (!isObj(raw)) return void 0;
|
|
1735
1891
|
const r = raw;
|
|
@@ -1887,11 +2043,13 @@ rename one of them, or delete or rename the other in a push of its own first`
|
|
|
1887
2043
|
const remoteLibById = new Map(rl.map((l) => [idOf(l), l]));
|
|
1888
2044
|
const remoteTemplates = new Map(rl.flatMap((l) => templatesOf2(l).map((t) => [idOf(t), t])));
|
|
1889
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)));
|
|
1890
2047
|
const allChannelIds = [...effective.keys()];
|
|
1891
2048
|
for (const lib of ll.filter(inScope)) {
|
|
1892
2049
|
const r = remoteLibById.get(idOf(lib));
|
|
1893
2050
|
let touched = false;
|
|
1894
|
-
|
|
2051
|
+
const effectiveLib = r && !opts.wholeReplace ? withRetainedMembers(lib, r, localTemplateIds, deletedTemplateIds) : lib;
|
|
2052
|
+
if (!r || !same(libraryShape(effectiveLib), libraryShape(r))) {
|
|
1895
2053
|
changes.push({ kind: "library", op: r ? "update" : "create", id: idOf(lib), label: nameOf(lib) });
|
|
1896
2054
|
touched = true;
|
|
1897
2055
|
if (r && revisionOf(r) > revisionOf(lib)) conflicts.push(`library "${nameOf(lib)}" (server revision ${revisionOf(r)}, tree ${revisionOf(lib)})`);
|
|
@@ -1916,6 +2074,9 @@ rename one of them, or delete or rename the other in a push of its own first`
|
|
|
1916
2074
|
}
|
|
1917
2075
|
for (const r of rl.filter(inScope)) {
|
|
1918
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
|
+
}
|
|
1919
2080
|
const before = changes.length;
|
|
1920
2081
|
missingLocally("library", r, nameOf(r), known?.libraries);
|
|
1921
2082
|
if (changes.length > before) for (const id of channelsUsing(r, allChannelIds)) deploy.add(id);
|
|
@@ -1951,12 +2112,19 @@ function librariesToSend(local, remote, scope, plan) {
|
|
|
1951
2112
|
const rl = librariesOf(remote);
|
|
1952
2113
|
const inScope = scope.libraries === void 0 ? () => true : (o) => scope.libraries.includes(nameOf(o)) || scope.libraries.includes(idOf(o));
|
|
1953
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));
|
|
1954
2117
|
const localById = new Map(ll.map((l) => [idOf(l), l]));
|
|
1955
2118
|
const out = [];
|
|
1956
2119
|
for (const r of rl) {
|
|
1957
|
-
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
|
+
}
|
|
1958
2126
|
const l = localById.get(idOf(r));
|
|
1959
|
-
out.push(l && inScope(l) ? l : r);
|
|
2127
|
+
out.push(l && inScope(l) ? withRetainedMembers(l, r, localTemplateIds, deletedTemplates) : r);
|
|
1960
2128
|
}
|
|
1961
2129
|
for (const l of ll) if (inScope(l) && !rl.some((r) => idOf(r) === idOf(l))) out.push(l);
|
|
1962
2130
|
return out;
|
|
@@ -1973,16 +2141,20 @@ function changedSince(plan, before, after) {
|
|
|
1973
2141
|
else if (c.kind === "library") [b, a] = [lb.get(c.id), la.get(c.id)];
|
|
1974
2142
|
else if (!same(before["globalScripts"], after["globalScripts"])) out.push("global scripts");
|
|
1975
2143
|
if (c.kind === "globalScripts") continue;
|
|
1976
|
-
|
|
1977
|
-
const exists = a !== void 0;
|
|
1978
|
-
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}"`);
|
|
1979
2145
|
}
|
|
1980
2146
|
if (plan.changes.some((c) => c.kind === "library")) {
|
|
1981
|
-
|
|
1982
|
-
|
|
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
|
+
}
|
|
1983
2150
|
}
|
|
1984
2151
|
return [...new Set(out)];
|
|
1985
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
|
+
}
|
|
1986
2158
|
function sameServerConfig(a, b) {
|
|
1987
2159
|
const { date: _a, ...ra } = a;
|
|
1988
2160
|
const { date: _b, ...rb } = b;
|
|
@@ -2007,7 +2179,7 @@ function findChannel(c, id) {
|
|
|
2007
2179
|
}
|
|
2008
2180
|
|
|
2009
2181
|
// src/push/apply.ts
|
|
2010
|
-
import { readdir, writeFile as writeFile2 } from "fs/promises";
|
|
2182
|
+
import { readdir as readdir2, writeFile as writeFile2 } from "fs/promises";
|
|
2011
2183
|
import { existsSync as existsSync2 } from "fs";
|
|
2012
2184
|
import * as path2 from "path";
|
|
2013
2185
|
var ORDER = [
|
|
@@ -2022,13 +2194,19 @@ async function applyPlan(client, plan, local, remote, scope, opts = {}) {
|
|
|
2022
2194
|
const applied = [];
|
|
2023
2195
|
const touchedIds = /* @__PURE__ */ new Set();
|
|
2024
2196
|
let librariesSent = false;
|
|
2197
|
+
let sentLibraries;
|
|
2025
2198
|
for (const [kind, ops] of ORDER) {
|
|
2026
2199
|
for (const change of plan.changes.filter((c) => c.kind === kind && ops.includes(c.op))) {
|
|
2027
2200
|
try {
|
|
2028
2201
|
if (kind === "library") {
|
|
2029
2202
|
if (!librariesSent) {
|
|
2030
|
-
const
|
|
2031
|
-
|
|
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;
|
|
2032
2210
|
librariesSent = true;
|
|
2033
2211
|
const sentFromTree = librariesOf(local).filter(
|
|
2034
2212
|
(l) => scope.libraries === void 0 || scope.libraries.includes(String(l["name"])) || scope.libraries.includes(String(l["id"]))
|
|
@@ -2037,35 +2215,52 @@ async function applyPlan(client, plan, local, remote, scope, opts = {}) {
|
|
|
2037
2215
|
for (const id of inSync) touchedIds.add(id);
|
|
2038
2216
|
}
|
|
2039
2217
|
} else if (kind === "codeTemplate" && change.op === "delete") {
|
|
2218
|
+
await checkTemplate(client, change, remote, opts.force === true);
|
|
2040
2219
|
await client.deleteCodeTemplate(change.id);
|
|
2041
2220
|
} else if (kind === "codeTemplate") {
|
|
2221
|
+
await checkTemplate(client, change, remote, opts.force === true);
|
|
2042
2222
|
await client.putCodeTemplate(findTemplate(local, change.id));
|
|
2043
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);
|
|
2044
2226
|
await client.deleteChannel(change.id);
|
|
2045
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
|
+
}
|
|
2046
2233
|
await client.putChannel(
|
|
2047
|
-
await withServerAssociations(client,
|
|
2234
|
+
await withServerAssociations(client, channel, change, before, opts.force === true)
|
|
2048
2235
|
);
|
|
2049
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
|
+
}
|
|
2050
2241
|
await client.putGlobalScripts(local["globalScripts"]);
|
|
2051
2242
|
}
|
|
2052
2243
|
} catch (err) {
|
|
2053
|
-
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 };
|
|
2054
2245
|
}
|
|
2055
2246
|
applied.push(change);
|
|
2056
2247
|
touchedIds.add(change.id);
|
|
2057
2248
|
}
|
|
2058
2249
|
}
|
|
2059
|
-
return { applied, touchedIds };
|
|
2250
|
+
return { applied, touchedIds, sentLibraries };
|
|
2060
2251
|
}
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
const server = await client.getChannel(String(channel["id"]));
|
|
2065
|
-
const [now, then] = [Number(server?.["revision"] ?? 0), Number(planned?.["revision"] ?? 0)];
|
|
2066
|
-
if (!force && now > then) {
|
|
2067
|
-
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`);
|
|
2068
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;
|
|
2069
2264
|
const serverExport = server?.["exportData"];
|
|
2070
2265
|
if (!serverExport) return channel;
|
|
2071
2266
|
const exportData = { ...channel["exportData"] ?? {} };
|
|
@@ -2073,15 +2268,22 @@ async function withServerAssociations(client, channel, op, planned, force) {
|
|
|
2073
2268
|
return { ...channel, exportData };
|
|
2074
2269
|
}
|
|
2075
2270
|
async function deployChannels(client, ids, nameOf2) {
|
|
2271
|
+
const deployed = [];
|
|
2272
|
+
const skipped = [];
|
|
2076
2273
|
const failures = [];
|
|
2077
2274
|
for (const id of ids) {
|
|
2078
2275
|
try {
|
|
2276
|
+
if (!(await client.getDeployedChannelIds()).has(id)) {
|
|
2277
|
+
skipped.push(nameOf2(id));
|
|
2278
|
+
continue;
|
|
2279
|
+
}
|
|
2079
2280
|
await client.deployChannel(id);
|
|
2281
|
+
deployed.push(nameOf2(id));
|
|
2080
2282
|
} catch (err) {
|
|
2081
2283
|
failures.push({ name: nameOf2(id), error: err instanceof Error ? err.message : String(err) });
|
|
2082
2284
|
}
|
|
2083
2285
|
}
|
|
2084
|
-
return failures;
|
|
2286
|
+
return { deployed, skipped, failures };
|
|
2085
2287
|
}
|
|
2086
2288
|
function copyVersionFields(target, source) {
|
|
2087
2289
|
if (!source) return false;
|
|
@@ -2102,7 +2304,7 @@ function copyVersionFields(target, source) {
|
|
|
2102
2304
|
}
|
|
2103
2305
|
async function jsonFiles(dir, name) {
|
|
2104
2306
|
if (!existsSync2(dir)) return [];
|
|
2105
|
-
const entries = await
|
|
2307
|
+
const entries = await readdir2(dir, { withFileTypes: true });
|
|
2106
2308
|
return entries.filter((e) => e.isDirectory()).map((e) => path2.join(dir, e.name, name)).filter((f) => existsSync2(f));
|
|
2107
2309
|
}
|
|
2108
2310
|
async function refreshRevisions(root, server, ids) {
|
|
@@ -2127,7 +2329,7 @@ async function refreshRevisions(root, server, ids) {
|
|
|
2127
2329
|
// src/secrets/envfile.ts
|
|
2128
2330
|
import { randomBytes } from "crypto";
|
|
2129
2331
|
import { existsSync as existsSync3 } from "fs";
|
|
2130
|
-
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";
|
|
2131
2333
|
import * as path3 from "path";
|
|
2132
2334
|
import { parse } from "dotenv";
|
|
2133
2335
|
var BASE64_PREFIX = "cv-base64:";
|
|
@@ -2213,25 +2415,25 @@ async function backupEnvFile(file, updates, dir) {
|
|
|
2213
2415
|
for (let n = 2; existsSync3(target); n += 1) target = path3.join(dir, `${prefix}${stamp2}-${String(n).padStart(2, "0")}`);
|
|
2214
2416
|
await copyFile(file, target);
|
|
2215
2417
|
await chmod(target, 384);
|
|
2216
|
-
const others = (await
|
|
2418
|
+
const others = (await readdir3(dir)).filter((f) => f.startsWith(prefix) && f !== path3.basename(target)).sort();
|
|
2217
2419
|
for (const old of others.slice(0, Math.max(0, others.length - (ENV_BACKUPS_KEPT - 1)))) {
|
|
2218
2420
|
await rm(path3.join(dir, old));
|
|
2219
2421
|
}
|
|
2220
2422
|
return target;
|
|
2221
2423
|
}
|
|
2222
2424
|
var IGNORE_LINES = [".env", ".env.*", "!.env.example", ".secrets/"];
|
|
2223
|
-
async function ensureEnvIgnored(dir, envFile) {
|
|
2425
|
+
async function ensureEnvIgnored(dir, envFile, treeRoot = dir) {
|
|
2224
2426
|
const file = path3.join(dir, ".gitignore");
|
|
2225
2427
|
const text = existsSync3(file) ? await readFile3(file, "utf8") : "";
|
|
2226
|
-
const
|
|
2428
|
+
const present2 = new Set(text.split(/\r?\n/).map((l) => l.trim()));
|
|
2227
2429
|
const wanted = [...IGNORE_LINES];
|
|
2228
2430
|
if (envFile) {
|
|
2229
|
-
const rel = path3.relative(
|
|
2431
|
+
const rel = path3.relative(treeRoot, envFile).split(path3.sep).join("/");
|
|
2230
2432
|
const base = path3.basename(envFile);
|
|
2231
2433
|
const covered = !rel.includes("/") && (base === ".env" || base.startsWith(".env.") && base !== ".env.example");
|
|
2232
2434
|
if (!covered && !rel.startsWith("..") && !path3.isAbsolute(rel)) wanted.push(`/${rel}`);
|
|
2233
2435
|
}
|
|
2234
|
-
const missing = wanted.filter((l) => !
|
|
2436
|
+
const missing = wanted.filter((l) => !present2.has(l));
|
|
2235
2437
|
if (missing.length === 0) return false;
|
|
2236
2438
|
const prefix = text === "" || text.endsWith("\n") ? "" : "\n";
|
|
2237
2439
|
await appendFile(file, `${prefix}# channelvault: secrets and per-environment values
|
|
@@ -2243,7 +2445,7 @@ ${missing.join("\n")}
|
|
|
2243
2445
|
// src/backup/index.ts
|
|
2244
2446
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
2245
2447
|
import { existsSync as existsSync4, realpathSync } from "fs";
|
|
2246
|
-
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";
|
|
2247
2449
|
import * as path4 from "path";
|
|
2248
2450
|
var DEFAULT_BACKUP_DIR = ".backup";
|
|
2249
2451
|
var DEFAULT_KEEP = 10;
|
|
@@ -2268,7 +2470,7 @@ function stamp(date) {
|
|
|
2268
2470
|
async function listBackups(dir) {
|
|
2269
2471
|
if (!existsSync4(dir)) return [];
|
|
2270
2472
|
const out = [];
|
|
2271
|
-
for (const name of await
|
|
2473
|
+
for (const name of await readdir4(dir)) {
|
|
2272
2474
|
const m = FILE_NAME.exec(name);
|
|
2273
2475
|
if (m) out.push({ file: path4.join(dir, name), server: m[1], stamp: m[2], seq: m[3] ? Number(m[3]) : 1 });
|
|
2274
2476
|
}
|
|
@@ -2286,8 +2488,8 @@ async function readManifest(dir) {
|
|
|
2286
2488
|
}
|
|
2287
2489
|
}
|
|
2288
2490
|
async function writeManifest(dir, files) {
|
|
2289
|
-
const
|
|
2290
|
-
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)}
|
|
2291
2493
|
`);
|
|
2292
2494
|
}
|
|
2293
2495
|
async function backupsOf(dir, serverId) {
|
|
@@ -2357,6 +2559,202 @@ function compareVersions(a, b) {
|
|
|
2357
2559
|
return 0;
|
|
2358
2560
|
}
|
|
2359
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
|
+
|
|
2360
2758
|
// src/cli.ts
|
|
2361
2759
|
var engine = createExplodeEngine();
|
|
2362
2760
|
var xml = new XmlConfigAdapter();
|
|
@@ -2367,8 +2765,6 @@ function fail(message) {
|
|
|
2367
2765
|
throw new CliError(message);
|
|
2368
2766
|
}
|
|
2369
2767
|
var errorExitCode = 1;
|
|
2370
|
-
var MANAGED_DIRS = ["server", "channels", "codeTemplates", "channelGroups"];
|
|
2371
|
-
var STAGING_DIR = ".channelvault-staging";
|
|
2372
2768
|
var RM_OPTS = { recursive: true, force: true, maxRetries: 5, retryDelay: 50 };
|
|
2373
2769
|
function resolveClientConfig(flags) {
|
|
2374
2770
|
const host = flags.host ?? process.env.MIRTH_HOST;
|
|
@@ -2416,7 +2812,7 @@ function addBackupDirFlags(cmd) {
|
|
|
2416
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})`);
|
|
2417
2813
|
}
|
|
2418
2814
|
function backupDirOf(flags) {
|
|
2419
|
-
return
|
|
2815
|
+
return path6.resolve(flags.backupDir ?? DEFAULT_BACKUP_DIR);
|
|
2420
2816
|
}
|
|
2421
2817
|
function keepOf(flags) {
|
|
2422
2818
|
if (flags.keep === void 0) return DEFAULT_KEEP;
|
|
@@ -2448,8 +2844,36 @@ async function saveServerBackup(client, text, flags, protect) {
|
|
|
2448
2844
|
async function backupBeforePush(client, flags) {
|
|
2449
2845
|
if (flags.backup === false) return;
|
|
2450
2846
|
const file = await saveServerBackup(client, await client.getServerConfigurationXml(), flags);
|
|
2451
|
-
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)})
|
|
2452
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");
|
|
2453
2877
|
}
|
|
2454
2878
|
function hostOf(flags) {
|
|
2455
2879
|
const cfg = resolveClientConfig(flags);
|
|
@@ -2491,7 +2915,7 @@ function summarize(config) {
|
|
|
2491
2915
|
codeTemplates
|
|
2492
2916
|
};
|
|
2493
2917
|
}
|
|
2494
|
-
async function writeMeta(root, source, config, previous) {
|
|
2918
|
+
async function writeMeta(root, source, config, previous, serverId, resources = resourceIds(config)) {
|
|
2495
2919
|
const meta = {
|
|
2496
2920
|
tool: "channelvault",
|
|
2497
2921
|
version: VERSION,
|
|
@@ -2499,14 +2923,15 @@ async function writeMeta(root, source, config, previous) {
|
|
|
2499
2923
|
pulledAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2500
2924
|
// XML adapter yields `@_version`; the live JSON API yields `@version` (Jackson).
|
|
2501
2925
|
engineVersion: typeof config["@_version"] === "string" ? config["@_version"] : typeof config["@version"] === "string" ? config["@version"] : null,
|
|
2502
|
-
resources
|
|
2926
|
+
resources,
|
|
2927
|
+
serverId
|
|
2503
2928
|
};
|
|
2504
|
-
const file =
|
|
2505
|
-
if (previous && JSON.stringify({ ...previous, pulledAt: "" }) === JSON.stringify({ ...meta, pulledAt: "" }))
|
|
2506
|
-
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");
|
|
2507
2932
|
}
|
|
2508
2933
|
function envFilePath(root, flags) {
|
|
2509
|
-
return flags.dotenv ?
|
|
2934
|
+
return flags.dotenv ? path6.resolve(flags.dotenv) : path6.join(root, ".env");
|
|
2510
2935
|
}
|
|
2511
2936
|
async function loadEnv(file) {
|
|
2512
2937
|
return { ...await readEnvFile(file), ...process.env };
|
|
@@ -2518,7 +2943,7 @@ function addExtractFlag(cmd) {
|
|
|
2518
2943
|
return cmd.option("--extract-secrets", "move secrets found inside values (URLs, scripts, headers) to the env file", false);
|
|
2519
2944
|
}
|
|
2520
2945
|
async function existingTree(root) {
|
|
2521
|
-
return
|
|
2946
|
+
return existsSync6(path6.join(root, "server", "configuration.json")) ? engine.implode({ root }) : null;
|
|
2522
2947
|
}
|
|
2523
2948
|
async function renderedTree(root, flags) {
|
|
2524
2949
|
const tree = await engine.implode({ root });
|
|
@@ -2547,12 +2972,12 @@ function scrub(text) {
|
|
|
2547
2972
|
}
|
|
2548
2973
|
var ALLOW_FILE = "channelvault.allow.json";
|
|
2549
2974
|
async function readAllow(root) {
|
|
2550
|
-
const file =
|
|
2551
|
-
if (!
|
|
2975
|
+
const file = path6.join(root, ALLOW_FILE);
|
|
2976
|
+
if (!existsSync6(file)) return [];
|
|
2552
2977
|
const parsed = await readJson(file);
|
|
2553
2978
|
return parsed.ignore ?? [];
|
|
2554
2979
|
}
|
|
2555
|
-
async function writeTree(root, fetched, source, flags) {
|
|
2980
|
+
async function writeTree(root, fetched, source, flags, serverId) {
|
|
2556
2981
|
const envFile = envFilePath(root, flags);
|
|
2557
2982
|
const previousMeta = await preflightTree(root, envFile);
|
|
2558
2983
|
const env = await loadEnv(envFile);
|
|
@@ -2573,15 +2998,30 @@ Rerun with --extract-secrets to move them to ${envFile}, or list false positives
|
|
|
2573
2998
|
const envUpdates = { ...templated.envUpdates, ...scan.envUpdates };
|
|
2574
2999
|
rememberSecrets(config, { ...env, ...envUpdates });
|
|
2575
3000
|
const echoes = findEchoes(config, { ...await readEnvFile(envFile), ...envUpdates });
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
|
|
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
|
+
});
|
|
2585
3025
|
if (scan.findings.length > 0) process.stdout.write(`extracted ${scan.findings.length} secret(s) found in values
|
|
2586
3026
|
`);
|
|
2587
3027
|
const updated = Object.keys(envUpdates).length;
|
|
@@ -2595,34 +3035,34 @@ Rerun with --extract-secrets to move them to ${envFile}, or list false positives
|
|
|
2595
3035
|
process.stderr.write(`warning: the value of ${e.name} also appears in plain text at ${e.where}
|
|
2596
3036
|
`);
|
|
2597
3037
|
}
|
|
2598
|
-
if (
|
|
3038
|
+
if (existsSync6(envFile) && gitWouldCommit(envFile)) {
|
|
2599
3039
|
process.stderr.write(`warning: git does not ignore ${envFile}, so its secret values could be committed; add it to .gitignore
|
|
2600
3040
|
`);
|
|
2601
3041
|
}
|
|
2602
3042
|
}
|
|
2603
3043
|
function gitWouldCommit(file) {
|
|
2604
|
-
const r = spawnSync("git", ["check-ignore", "-q",
|
|
3044
|
+
const r = spawnSync("git", ["check-ignore", "-q", path6.basename(file)], { cwd: path6.dirname(file) });
|
|
2605
3045
|
return r.status === 1;
|
|
2606
3046
|
}
|
|
2607
3047
|
async function resolvedPath(p) {
|
|
2608
|
-
const abs =
|
|
3048
|
+
const abs = path6.resolve(p);
|
|
2609
3049
|
let existing = abs;
|
|
2610
|
-
while (!
|
|
2611
|
-
return
|
|
3050
|
+
while (!existsSync6(existing) && path6.dirname(existing) !== existing) existing = path6.dirname(existing);
|
|
3051
|
+
return path6.join(await realpath4(existing), path6.relative(existing, abs));
|
|
2612
3052
|
}
|
|
2613
3053
|
function isWithin(child, parent) {
|
|
2614
3054
|
const norm = (p) => process.platform === "win32" ? p.toLowerCase() : p;
|
|
2615
|
-
const rel =
|
|
2616
|
-
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);
|
|
2617
3057
|
}
|
|
2618
3058
|
async function preflightTree(root, envFile) {
|
|
2619
3059
|
const [realRoot, realEnv] = await Promise.all([resolvedPath(root), resolvedPath(envFile)]);
|
|
2620
|
-
const doomed = [...MANAGED_DIRS, STAGING_DIR].find(
|
|
2621
|
-
(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))
|
|
2622
3062
|
);
|
|
2623
3063
|
if (doomed) fail(`the env file ${envFile} is inside ${doomed}/, which this command replaces; keep it elsewhere`);
|
|
2624
|
-
const metaPath =
|
|
2625
|
-
if (
|
|
3064
|
+
const metaPath = path6.join(root, "channelvault.json");
|
|
3065
|
+
if (existsSync6(metaPath)) {
|
|
2626
3066
|
let meta;
|
|
2627
3067
|
try {
|
|
2628
3068
|
meta = await readJson(metaPath);
|
|
@@ -2636,7 +3076,7 @@ async function preflightTree(root, envFile) {
|
|
|
2636
3076
|
}
|
|
2637
3077
|
return meta;
|
|
2638
3078
|
}
|
|
2639
|
-
const foreign = MANAGED_DIRS.filter((d) =>
|
|
3079
|
+
const foreign = MANAGED_DIRS.filter((d) => existsSync6(path6.join(root, d)));
|
|
2640
3080
|
if (foreign.length > 0) {
|
|
2641
3081
|
fail(
|
|
2642
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).`
|
|
@@ -2644,27 +3084,14 @@ async function preflightTree(root, envFile) {
|
|
|
2644
3084
|
}
|
|
2645
3085
|
return null;
|
|
2646
3086
|
}
|
|
2647
|
-
async function replaceTree(root, config) {
|
|
2648
|
-
const staging = path5.join(root, STAGING_DIR);
|
|
2649
|
-
await rm3(staging, RM_OPTS);
|
|
2650
|
-
try {
|
|
2651
|
-
await engine.explode(config, { root: staging });
|
|
2652
|
-
for (const d of MANAGED_DIRS) {
|
|
2653
|
-
await rm3(path5.join(root, d), RM_OPTS);
|
|
2654
|
-
if (existsSync5(path5.join(staging, d))) await rename3(path5.join(staging, d), path5.join(root, d));
|
|
2655
|
-
}
|
|
2656
|
-
} finally {
|
|
2657
|
-
await rm3(staging, RM_OPTS);
|
|
2658
|
-
}
|
|
2659
|
-
}
|
|
2660
3087
|
function assertTree(root) {
|
|
2661
|
-
if (!
|
|
3088
|
+
if (!existsSync6(path6.join(root, "server", "configuration.json"))) {
|
|
2662
3089
|
fail(`${root} is not a channelvault tree (missing server/configuration.json). Run 'pull' or 'explode' first.`);
|
|
2663
3090
|
}
|
|
2664
3091
|
}
|
|
2665
3092
|
async function readTreeOrigin(root) {
|
|
2666
|
-
const metaPath =
|
|
2667
|
-
if (!
|
|
3093
|
+
const metaPath = path6.join(root, "channelvault.json");
|
|
3094
|
+
if (!existsSync6(metaPath)) return "unknown";
|
|
2668
3095
|
try {
|
|
2669
3096
|
const meta = await readJson(metaPath);
|
|
2670
3097
|
if (typeof meta.source === "string") {
|
|
@@ -2691,18 +3118,28 @@ async function assertCompatibleOrigin(root, config, wants, force) {
|
|
|
2691
3118
|
function collect(value, previous) {
|
|
2692
3119
|
return [...previous ?? [], value];
|
|
2693
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
|
+
}
|
|
2694
3131
|
async function readKnown(root) {
|
|
2695
|
-
const metaPath =
|
|
2696
|
-
if (!
|
|
3132
|
+
const metaPath = path6.join(root, "channelvault.json");
|
|
3133
|
+
if (!existsSync6(metaPath)) return void 0;
|
|
2697
3134
|
return knownFrom((await readJson(metaPath)).resources);
|
|
2698
3135
|
}
|
|
2699
3136
|
async function writeKnown(root, known) {
|
|
2700
|
-
const metaPath =
|
|
2701
|
-
if (!
|
|
3137
|
+
const metaPath = path6.join(root, "channelvault.json");
|
|
3138
|
+
if (!existsSync6(metaPath)) return;
|
|
2702
3139
|
const meta = await readJson(metaPath);
|
|
2703
3140
|
if (!meta.resources) return;
|
|
2704
3141
|
meta.resources = known;
|
|
2705
|
-
await
|
|
3142
|
+
await writeFile6(metaPath, JSON.stringify(meta, null, 2) + "\n", "utf8");
|
|
2706
3143
|
}
|
|
2707
3144
|
function printNameChange(incoming, current) {
|
|
2708
3145
|
const [to, from] = [configuredName(incoming), configuredName(current)];
|
|
@@ -2744,6 +3181,7 @@ function reportPlanOnly(flags, plan, problems, extra) {
|
|
|
2744
3181
|
writeJson2({
|
|
2745
3182
|
target: extra.target,
|
|
2746
3183
|
mode: extra.mode,
|
|
3184
|
+
...extra.serverId ? { serverId: extra.serverId } : {},
|
|
2747
3185
|
changes: plan.changes,
|
|
2748
3186
|
conflicts: plan.conflicts,
|
|
2749
3187
|
serverOnly: plan.serverOnly,
|
|
@@ -2761,6 +3199,7 @@ async function scopedPush(client, root, local, scope, target, flags) {
|
|
|
2761
3199
|
const remote = await client.getServerConfiguration();
|
|
2762
3200
|
const known = await readKnown(root);
|
|
2763
3201
|
const plan = planPush(local, remote, scope, known);
|
|
3202
|
+
const problems = [...await bindingProblems(root, await client.getServerId()), ...planProblems(plan, flags)];
|
|
2764
3203
|
const names = new Map(
|
|
2765
3204
|
[...channelsOf(remote), ...channelsOf(local)].map((c) => [String(c["id"]), String(c["name"])])
|
|
2766
3205
|
);
|
|
@@ -2770,7 +3209,7 @@ async function scopedPush(client, root, local, scope, target, flags) {
|
|
|
2770
3209
|
const notDeployed = flags.deploy ? plan.deployIds.filter((id) => !deployed.has(id)) : [];
|
|
2771
3210
|
if (flags.planOnly && flags.json) {
|
|
2772
3211
|
const redeploy = flags.deploy ? { redeploy: toDeploy.map(nameOf2), notRedeployed: notDeployed.map(nameOf2) } : {};
|
|
2773
|
-
reportPlanOnly(flags, plan,
|
|
3212
|
+
reportPlanOnly(flags, plan, problems, { target, mode: "scoped", ...redeploy });
|
|
2774
3213
|
return;
|
|
2775
3214
|
}
|
|
2776
3215
|
if (plan.changes.length === 0) {
|
|
@@ -2796,12 +3235,11 @@ async function scopedPush(client, root, local, scope, target, flags) {
|
|
|
2796
3235
|
`);
|
|
2797
3236
|
}
|
|
2798
3237
|
if (flags.planOnly) {
|
|
2799
|
-
reportPlanOnly(flags, plan,
|
|
3238
|
+
reportPlanOnly(flags, plan, problems, { target, mode: "scoped" });
|
|
2800
3239
|
return;
|
|
2801
3240
|
}
|
|
2802
|
-
if (plan.changes.length === 0) return;
|
|
2803
|
-
const problems = planProblems(plan, flags);
|
|
2804
3241
|
if (problems.length > 0) fail(problems.join("\n"));
|
|
3242
|
+
if (plan.changes.length === 0) return;
|
|
2805
3243
|
if (!flags.yes && !await confirm("Continue?")) {
|
|
2806
3244
|
process.stdout.write("aborted.\n");
|
|
2807
3245
|
return;
|
|
@@ -2814,11 +3252,18 @@ async function scopedPush(client, root, local, scope, target, flags) {
|
|
|
2814
3252
|
pull and try again, or pass --force`);
|
|
2815
3253
|
}
|
|
2816
3254
|
await backupBeforePush(client, flags);
|
|
2817
|
-
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 });
|
|
2818
3262
|
try {
|
|
2819
3263
|
const after = await client.getServerConfiguration();
|
|
2820
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"]) }));
|
|
2821
|
-
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));
|
|
2822
3267
|
if (changedAgain.length > 0) fail(`changed again after saving: ${[...new Set(changedAgain.map((c) => c.label))].join(", ")}; pull and review before retrying`);
|
|
2823
3268
|
if (result.touchedIds.size > 0) await refreshRevisions(root, after, result.touchedIds);
|
|
2824
3269
|
if (known) await writeKnown(root, knownAfterPush(known, result.applied, result.touchedIds, after));
|
|
@@ -2835,8 +3280,10 @@ pull and try again, or pass --force`);
|
|
|
2835
3280
|
process.stdout.write(`pushed ${result.applied.length} change(s)
|
|
2836
3281
|
`);
|
|
2837
3282
|
if (toDeploy.length > 0) {
|
|
2838
|
-
const failures = await deployChannels(client, toDeploy, nameOf2);
|
|
2839
|
-
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(", ")}
|
|
2840
3287
|
`);
|
|
2841
3288
|
for (const f of failures) process.stderr.write(`deploy failed: ${f.name}: ${scrub(f.error)}
|
|
2842
3289
|
`);
|
|
@@ -2847,8 +3294,9 @@ async function wholeServerPush(client, root, local, target, flags) {
|
|
|
2847
3294
|
const remote = await client.getServerConfiguration();
|
|
2848
3295
|
const known = await readKnown(root);
|
|
2849
3296
|
const plan = planPush(local, remote, {}, known, { wholeReplace: true });
|
|
3297
|
+
const problems = [...await bindingProblems(root, await client.getServerId()), ...wholeServerProblems(plan, flags)];
|
|
2850
3298
|
if (flags.planOnly && flags.json) {
|
|
2851
|
-
reportPlanOnly(flags, plan,
|
|
3299
|
+
reportPlanOnly(flags, plan, problems, { target, mode: "whole-server" });
|
|
2852
3300
|
return;
|
|
2853
3301
|
}
|
|
2854
3302
|
const s = summarize(local);
|
|
@@ -2868,7 +3316,6 @@ async function wholeServerPush(client, root, local, target, flags) {
|
|
|
2868
3316
|
if (replaced.length > 0) process.stdout.write(`also replaced: ${replaced.join(", ")}
|
|
2869
3317
|
`);
|
|
2870
3318
|
if (keptMap) process.stdout.write("configuration map differs but is kept (--overwrite-config-map replaces it)\n");
|
|
2871
|
-
const problems = wholeServerProblems(plan, flags);
|
|
2872
3319
|
if (flags.planOnly) {
|
|
2873
3320
|
reportPlanOnly(flags, plan, problems, { target, mode: "whole-server" });
|
|
2874
3321
|
return;
|
|
@@ -2887,6 +3334,13 @@ async function wholeServerPush(client, root, local, target, flags) {
|
|
|
2887
3334
|
fail("the replace now deletes resources from the server; review the new plan and pass --allow-deletes");
|
|
2888
3335
|
}
|
|
2889
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);
|
|
2890
3344
|
await client.putServerConfiguration(local, {
|
|
2891
3345
|
deploy: flags.deploy === true,
|
|
2892
3346
|
overwriteConfigMap: flags.overwriteConfigMap === true
|
|
@@ -2907,8 +3361,8 @@ addExtractFlag(addEnvFlag(
|
|
|
2907
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")
|
|
2908
3362
|
)).action(async (backupPath, dir, flags) => {
|
|
2909
3363
|
const config = xml.parse(await readFile5(backupPath, "utf8"));
|
|
2910
|
-
const root =
|
|
2911
|
-
await writeTree(root, config, `file:${
|
|
3364
|
+
const root = path6.resolve(dir);
|
|
3365
|
+
await writeTree(root, config, `file:${path6.resolve(backupPath)}`, flags);
|
|
2912
3366
|
const s = summarize(config);
|
|
2913
3367
|
process.stdout.write(`exploded ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}
|
|
2914
3368
|
`);
|
|
@@ -2916,27 +3370,81 @@ addExtractFlag(addEnvFlag(
|
|
|
2916
3370
|
addEnvFlag(
|
|
2917
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)
|
|
2918
3372
|
).action(async (dir, outPath, flags) => {
|
|
2919
|
-
const root =
|
|
3373
|
+
const root = path6.resolve(dir);
|
|
2920
3374
|
assertTree(root);
|
|
2921
3375
|
const config = await renderedTree(root, flags);
|
|
2922
3376
|
await assertCompatibleOrigin(root, config, "xml", flags.force === true);
|
|
2923
3377
|
const xmlStr = xml.build(config);
|
|
2924
|
-
await
|
|
2925
|
-
process.stdout.write(`imploded ${root} -> ${
|
|
3378
|
+
await writeFile6(outPath, xmlStr, "utf8");
|
|
3379
|
+
process.stdout.write(`imploded ${root} -> ${path6.resolve(outPath)}
|
|
2926
3380
|
`);
|
|
2927
3381
|
});
|
|
2928
3382
|
addExtractFlag(addEnvFlag(addConnectionFlags(
|
|
2929
3383
|
program.command("pull").description("Pull the live server configuration into a working tree").argument("<dir>", "working-tree directory")
|
|
2930
3384
|
))).action(async (dir, flags) => {
|
|
2931
|
-
const root =
|
|
3385
|
+
const root = path6.resolve(dir);
|
|
2932
3386
|
await preflightTree(root, envFilePath(root, flags));
|
|
2933
|
-
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
|
+
});
|
|
2934
3393
|
const cfg = resolveClientConfig(flags);
|
|
2935
|
-
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);
|
|
2936
3395
|
const s = summarize(config);
|
|
2937
3396
|
process.stdout.write(`pulled ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}
|
|
2938
3397
|
`);
|
|
2939
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
|
+
});
|
|
2940
3448
|
addBackupDirFlags(addEnvFlag(addConnectionFlags(
|
|
2941
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)
|
|
2942
3450
|
))).action(
|
|
@@ -2944,7 +3452,8 @@ addBackupDirFlags(addEnvFlag(addConnectionFlags(
|
|
|
2944
3452
|
if (flags.wholeServer && (flags.channel || flags.library || flags.globalScripts)) {
|
|
2945
3453
|
fail("--whole-server replaces everything; it cannot be combined with --channel, --library or --global-scripts");
|
|
2946
3454
|
}
|
|
2947
|
-
|
|
3455
|
+
if (flags.overwriteConfigMap && !flags.wholeServer) fail("--overwrite-config-map needs --whole-server");
|
|
3456
|
+
const root = path6.resolve(dir);
|
|
2948
3457
|
assertTree(root);
|
|
2949
3458
|
const config = await renderedTree(root, flags);
|
|
2950
3459
|
await assertCompatibleOrigin(root, config, "live", flags.ignoreOrigin === true);
|
|
@@ -2970,10 +3479,10 @@ addBackupDirFlags(addConnectionFlags(
|
|
|
2970
3479
|
const file = await withClient(flags, async (client) => {
|
|
2971
3480
|
const text = await client.getServerConfigurationXml();
|
|
2972
3481
|
if (!flags.out) return saveServerBackup(client, text, flags);
|
|
2973
|
-
const out =
|
|
3482
|
+
const out = path6.resolve(flags.out);
|
|
2974
3483
|
parseBackup(text, "the server configuration");
|
|
2975
|
-
if (
|
|
2976
|
-
await
|
|
3484
|
+
if (existsSync6(out)) fail(`${out} already exists; choose another name`);
|
|
3485
|
+
await mkdir5(path6.dirname(out), { recursive: true });
|
|
2977
3486
|
await writePrivate(out, text);
|
|
2978
3487
|
if (gitWouldCommit(out)) {
|
|
2979
3488
|
process.stderr.write(`warning: git does not ignore ${out}, which holds credentials in plain text; add it to .gitignore
|
|
@@ -2997,8 +3506,8 @@ addBackupDirFlags(addConnectionFlags(
|
|
|
2997
3506
|
const serverId = await client.getServerId();
|
|
2998
3507
|
let chosen;
|
|
2999
3508
|
if (file) {
|
|
3000
|
-
chosen =
|
|
3001
|
-
if (!
|
|
3509
|
+
chosen = path6.resolve(file);
|
|
3510
|
+
if (!existsSync6(chosen)) fail(`${chosen} does not exist`);
|
|
3002
3511
|
} else {
|
|
3003
3512
|
const mine = await backupsOf(dir, serverId);
|
|
3004
3513
|
if (mine.length === 0) {
|
|
@@ -3019,7 +3528,7 @@ addBackupDirFlags(addConnectionFlags(
|
|
|
3019
3528
|
if (fromContent !== "" && fromServer !== "" && fromContent !== fromServer && !flags.force) {
|
|
3020
3529
|
fail(`${chosen} is a backup of ${fromContent}, not ${fromServer}; pass --force to restore it here anyway`);
|
|
3021
3530
|
}
|
|
3022
|
-
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
|
|
3023
3532
|
`);
|
|
3024
3533
|
}
|
|
3025
3534
|
const [bv, sv] = [backup["@_version"], current["@_version"]];
|
|
@@ -3054,8 +3563,13 @@ to ${target}, replacing its ENTIRE configuration${flags.deploy ? ", then redeplo
|
|
|
3054
3563
|
fail("the server changed while this restore was being confirmed; nothing was restored. Run it again to review the new state");
|
|
3055
3564
|
}
|
|
3056
3565
|
const undo = await saveServerBackup(client, freshText, flags, chosen);
|
|
3057
|
-
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)})
|
|
3058
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
|
+
}
|
|
3059
3573
|
await client.putServerConfigurationXml(text, { deploy: flags.deploy === true, overwriteConfigMap: flags.overwriteConfigMap === true });
|
|
3060
3574
|
const after = parseBackup(await client.getServerConfigurationXml(), "the server configuration");
|
|
3061
3575
|
const differ = planPush(backup, after, {}, void 0, { wholeReplace: true }).changes;
|
|
@@ -3073,7 +3587,7 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
|
|
|
3073
3587
|
})
|
|
3074
3588
|
))).action(async (dir, flags) => {
|
|
3075
3589
|
errorExitCode = 2;
|
|
3076
|
-
const root =
|
|
3590
|
+
const root = path6.resolve(dir);
|
|
3077
3591
|
assertTree(root);
|
|
3078
3592
|
const fetched = await withClient(flags, (client) => client.getServerConfiguration());
|
|
3079
3593
|
const tree = await engine.implode({ root });
|
|
@@ -3095,15 +3609,15 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
|
|
|
3095
3609
|
if (serverView.findings.length > 0) messages.push(`${serverView.findings.length} possible secret(s) on the server are redacted below`);
|
|
3096
3610
|
if (!flags.json) for (const m of messages) process.stderr.write(`note: ${m}
|
|
3097
3611
|
`);
|
|
3098
|
-
const tmp = await mkdtemp(
|
|
3612
|
+
const tmp = await mkdtemp(path6.join(tmpdir(), "channelvault-diff-"));
|
|
3099
3613
|
try {
|
|
3100
|
-
await engine.explode(treeView.config, { root:
|
|
3101
|
-
await engine.explode(serverView.config, { root:
|
|
3102
|
-
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"));
|
|
3103
3617
|
const chunks = [];
|
|
3104
3618
|
for (const d of MANAGED_DIRS) {
|
|
3105
|
-
const local =
|
|
3106
|
-
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";
|
|
3107
3621
|
if (local === ".empty" && server === ".empty") continue;
|
|
3108
3622
|
const result = spawnSync(
|
|
3109
3623
|
"git",
|
|
@@ -3125,7 +3639,7 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
|
|
|
3125
3639
|
const clean = out === "" && secretDrift.length === 0;
|
|
3126
3640
|
if (!clean) process.exitCode = 1;
|
|
3127
3641
|
if (flags.json) {
|
|
3128
|
-
const files = await changedFiles(
|
|
3642
|
+
const files = await changedFiles(path6.join(tmp, "tree"), path6.join(tmp, "server"));
|
|
3129
3643
|
writeJson2({ clean, files, secretDrift, staleRevisions, notes: messages, patch: out });
|
|
3130
3644
|
} else if (clean) {
|
|
3131
3645
|
process.stdout.write("no differences \u2014 working tree matches the server.\n");
|
|
@@ -3137,16 +3651,16 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
|
|
|
3137
3651
|
}
|
|
3138
3652
|
}
|
|
3139
3653
|
} finally {
|
|
3140
|
-
await
|
|
3654
|
+
await rm4(tmp, RM_OPTS);
|
|
3141
3655
|
}
|
|
3142
3656
|
});
|
|
3143
3657
|
async function changedFiles(treeDir, serverDir) {
|
|
3144
3658
|
const list2 = async (base) => {
|
|
3145
3659
|
const out = [];
|
|
3146
3660
|
for (const d of MANAGED_DIRS) {
|
|
3147
|
-
if (!
|
|
3148
|
-
for (const entry of await
|
|
3149
|
-
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("/"));
|
|
3150
3664
|
}
|
|
3151
3665
|
}
|
|
3152
3666
|
return out;
|
|
@@ -3156,21 +3670,21 @@ async function changedFiles(treeDir, serverDir) {
|
|
|
3156
3670
|
const files = [];
|
|
3157
3671
|
for (const p of local) {
|
|
3158
3672
|
if (!remoteSet.has(p)) files.push({ path: p, change: "only-in-tree" });
|
|
3159
|
-
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" });
|
|
3160
3674
|
}
|
|
3161
3675
|
const localSet = new Set(local);
|
|
3162
3676
|
for (const p of remote) if (!localSet.has(p)) files.push({ path: p, change: "only-on-server" });
|
|
3163
3677
|
return files.sort((a, b) => a.path.localeCompare(b.path));
|
|
3164
3678
|
}
|
|
3165
|
-
addJsonFlag(
|
|
3679
|
+
addJsonFlag(addEnvFlag(
|
|
3166
3680
|
program.command("status").description("Summarize a working tree").argument("<dir>", "working-tree directory")
|
|
3167
|
-
).action(async (dir, flags) => {
|
|
3168
|
-
const root =
|
|
3681
|
+
)).action(async (dir, flags) => {
|
|
3682
|
+
const root = path6.resolve(dir);
|
|
3169
3683
|
assertTree(root);
|
|
3170
3684
|
const config = await engine.implode({ root });
|
|
3171
3685
|
const s = summarize(config);
|
|
3172
|
-
const metaPath =
|
|
3173
|
-
const meta =
|
|
3686
|
+
const metaPath = path6.join(root, "channelvault.json");
|
|
3687
|
+
const meta = existsSync6(metaPath) ? await readJson(metaPath) : null;
|
|
3174
3688
|
if (flags.json) {
|
|
3175
3689
|
writeJson2({ root, source: meta?.source ?? null, pulledAt: meta?.pulledAt ?? null, engineVersion: meta?.engineVersion ?? null, counts: s });
|
|
3176
3690
|
return;
|
|
@@ -3191,6 +3705,15 @@ code templates: ${s.codeTemplates}
|
|
|
3191
3705
|
`
|
|
3192
3706
|
);
|
|
3193
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
|
+
});
|
|
3194
3717
|
program.parseAsync().catch((err) => {
|
|
3195
3718
|
if (err instanceof CommanderError) return;
|
|
3196
3719
|
process.stderr.write(`error: ${scrub(err instanceof Error ? err.message : String(err))}
|
|
@@ -3206,5 +3729,15 @@ program.parseAsync().catch((err) => {
|
|
|
3206
3729
|
`);
|
|
3207
3730
|
}
|
|
3208
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
|
+
}
|
|
3209
3742
|
});
|
|
3210
3743
|
//# sourceMappingURL=cli.js.map
|