@ubercode/channelvault 0.3.0-rc.2 → 0.3.0-rc.3

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/dist/cli.js CHANGED
@@ -6,7 +6,7 @@ import { cp, lstat as lstat3, mkdir as mkdir5, mkdtemp, readFile as readFile6, r
6
6
  import { existsSync as existsSync6 } from "fs";
7
7
  import { tmpdir } from "os";
8
8
  import { createRequire } from "module";
9
- import * as path7 from "path";
9
+ import * as path8 from "path";
10
10
  import { createInterface } from "readline/promises";
11
11
  import { Command, CommanderError } from "commander";
12
12
 
@@ -1000,12 +1000,12 @@ function configMapKeyOf(entry) {
1000
1000
  return Array.isArray(key) && typeof key[0] === "string" ? key[0] : void 0;
1001
1001
  }
1002
1002
  function mapLeaves(config, visit) {
1003
- const walk = (node, key, path8, labels, section, cmKey) => {
1003
+ const walk = (node, key, path9, labels, section, cmKey) => {
1004
1004
  if (typeof node === "string") {
1005
- return visit(node, { location: path8.join("/"), key, labels, section, configMapKey: cmKey });
1005
+ return visit(node, { location: path9.join("/"), key, labels, section, configMapKey: cmKey });
1006
1006
  }
1007
1007
  if (Array.isArray(node)) {
1008
- return node.map((el, i) => walk(el, key, [...path8.slice(0, -1), `${path8[path8.length - 1]}${elementSegment(el, i)}`], labels, section, cmKey));
1008
+ return node.map((el, i) => walk(el, key, [...path9.slice(0, -1), `${path9[path9.length - 1]}${elementSegment(el, i)}`], labels, section, cmKey));
1009
1009
  }
1010
1010
  if (node && typeof node === "object") {
1011
1011
  const name = node["name"];
@@ -1013,7 +1013,7 @@ function mapLeaves(config, visit) {
1013
1013
  const mapKey = section === "configurationMap" && CONFIG_PROPERTY in node ? configMapKeyOf(node) : cmKey;
1014
1014
  const out = {};
1015
1015
  for (const [k, v] of Object.entries(node)) {
1016
- out[k] = walk(v, k, [...path8, k], inner, section || k, mapKey);
1016
+ out[k] = walk(v, k, [...path9, k], inner, section || k, mapKey);
1017
1017
  }
1018
1018
  return out;
1019
1019
  }
@@ -1411,6 +1411,15 @@ function connectionError(url, err) {
1411
1411
  error.code = code;
1412
1412
  return error;
1413
1413
  }
1414
+ function redirectTarget(url, response) {
1415
+ const location = response.headers.get("location");
1416
+ if (!location) return "";
1417
+ try {
1418
+ return `, to ${new URL(location, url).origin}`;
1419
+ } catch {
1420
+ return "";
1421
+ }
1422
+ }
1414
1423
  var SERVER_CONFIG_KEY = "serverConfiguration";
1415
1424
  function unwrapSingleKey(value) {
1416
1425
  const keys = Object.keys(value);
@@ -1613,15 +1622,15 @@ var MirthClientImpl = class {
1613
1622
  await this.request("POST", `/channels/${encodeURIComponent(id)}/_deploy`, { query: { returnErrors: true } });
1614
1623
  }
1615
1624
  /** Send a JSON body; Mirth answers some updates with `{"boolean": false}` instead of an error status. */
1616
- async sendJson(method, path8, body, query) {
1617
- const response = await this.request(method, path8, {
1625
+ async sendJson(method, path9, body, query) {
1626
+ const response = await this.request(method, path9, {
1618
1627
  query,
1619
1628
  headers: { "Content-Type": "application/json", Accept: "application/json" },
1620
1629
  body: JSON.stringify(body)
1621
1630
  });
1622
1631
  const text = await response.text();
1623
1632
  if (/^\s*\{\s*"boolean"\s*:\s*false\s*\}\s*$/.test(text)) {
1624
- throw new Error(`${method} ${path8}: the server refused the update`);
1633
+ throw new Error(`${method} ${path9}: the server refused the update`);
1625
1634
  }
1626
1635
  }
1627
1636
  // --- internal transport ---------------------------------------------------
@@ -1630,11 +1639,11 @@ var MirthClientImpl = class {
1630
1639
  * on a 401 while authenticated resets auth, re-logs in once, and retries.
1631
1640
  * Throws an {@link ApiError}-shaped error on a non-2xx response.
1632
1641
  */
1633
- async request(method, path8, options = {}, isRetry = false) {
1642
+ async request(method, path9, options = {}, isRetry = false) {
1634
1643
  if (!this.authenticated) {
1635
1644
  await this.login();
1636
1645
  }
1637
- const url = this.buildUrl(path8, options.query);
1646
+ const url = this.buildUrl(path9, options.query);
1638
1647
  const headers = {
1639
1648
  "X-Requested-With": "XMLHttpRequest",
1640
1649
  ...options.headers
@@ -1648,28 +1657,39 @@ var MirthClientImpl = class {
1648
1657
  if (response.status === 401 && this.authenticated && !isRetry) {
1649
1658
  this.authenticated = false;
1650
1659
  await this.login();
1651
- return this.request(method, path8, options, true);
1660
+ return this.request(method, path9, options, true);
1652
1661
  }
1653
1662
  if (!response.ok) {
1654
1663
  throw await this.toApiError(response);
1655
1664
  }
1656
1665
  return response;
1657
1666
  }
1658
- /** fetch through this client's pool, with network failures explained. */
1667
+ /**
1668
+ * fetch through this client's pool, with network failures explained. Never
1669
+ * follows a redirect: fetch re-sends a 307/308 body, so a redirected login
1670
+ * would post the username and password to wherever the server points.
1671
+ */
1659
1672
  async send(url, init) {
1673
+ let response;
1660
1674
  try {
1661
- return await fetch(url, {
1675
+ response = await fetch(url, {
1662
1676
  ...init,
1677
+ redirect: "manual",
1663
1678
  // @ts-expect-error - dispatcher is a Node.js/undici specific option
1664
1679
  dispatcher: this.dispatcher
1665
1680
  });
1666
1681
  } catch (err) {
1667
1682
  throw connectionError(url, err);
1668
1683
  }
1684
+ if (response.status >= 300 && response.status < 400) {
1685
+ await response.body?.cancel();
1686
+ throw new Error(`the server answered ${new URL(url).pathname} with a redirect (HTTP ${response.status}${redirectTarget(url, response)}); channelvault does not follow redirects, so credentials and session cookies are never sent elsewhere. Connect to the address it redirects to: check https vs --no-https, --host and --port (or MIRTH_HOST/MIRTH_PORT)`);
1687
+ }
1688
+ return response;
1669
1689
  }
1670
1690
  /** Build an absolute URL with an optional query string. */
1671
- buildUrl(path8, query) {
1672
- const url = `${this.baseUrl}${path8}`;
1691
+ buildUrl(path9, query) {
1692
+ const url = `${this.baseUrl}${path9}`;
1673
1693
  if (!query || Object.keys(query).length === 0) {
1674
1694
  return url;
1675
1695
  }
@@ -2446,8 +2466,21 @@ ${missing.join("\n")}
2446
2466
  import { randomBytes as randomBytes2 } from "crypto";
2447
2467
  import { existsSync as existsSync4, realpathSync } from "fs";
2448
2468
  import { mkdir as mkdir3, readdir as readdir4, readFile as readFile4, rename as rename2, rm as rm2, writeFile as writeFile4 } from "fs/promises";
2469
+ import * as path5 from "path";
2470
+
2471
+ // src/profiles.ts
2472
+ import { homedir } from "os";
2449
2473
  import * as path4 from "path";
2450
- var DEFAULT_BACKUP_DIR = ".backup";
2474
+ function configDir() {
2475
+ const override = process.env.CHANNELVAULT_CONFIG_DIR;
2476
+ return override ? path4.resolve(override) : path4.join(homedir(), ".channelvault");
2477
+ }
2478
+
2479
+ // src/backup/index.ts
2480
+ function defaultBackupDir() {
2481
+ return path5.join(configDir(), "backups");
2482
+ }
2483
+ var LEGACY_BACKUP_DIR = ".backup";
2451
2484
  var DEFAULT_KEEP = 10;
2452
2485
  var FILE_NAME = /^(.+)-(\d{8}T\d{6}Z)(?:-(\d+))?\.xml$/;
2453
2486
  function serverSlug(name) {
@@ -2472,13 +2505,13 @@ async function listBackups(dir) {
2472
2505
  const out = [];
2473
2506
  for (const name of await readdir4(dir)) {
2474
2507
  const m = FILE_NAME.exec(name);
2475
- if (m) out.push({ file: path4.join(dir, name), server: m[1], stamp: m[2], seq: m[3] ? Number(m[3]) : 1 });
2508
+ if (m) out.push({ file: path5.join(dir, name), server: m[1], stamp: m[2], seq: m[3] ? Number(m[3]) : 1 });
2476
2509
  }
2477
2510
  return out.sort((a, b) => a.stamp.localeCompare(b.stamp) || a.seq - b.seq);
2478
2511
  }
2479
2512
  var MANIFEST = "channelvault-backups.json";
2480
2513
  async function readManifest(dir) {
2481
- const file = path4.join(dir, MANIFEST);
2514
+ const file = path5.join(dir, MANIFEST);
2482
2515
  if (!existsSync4(file)) return {};
2483
2516
  try {
2484
2517
  const parsed = JSON.parse(await readFile4(file, "utf8"));
@@ -2488,17 +2521,17 @@ async function readManifest(dir) {
2488
2521
  }
2489
2522
  }
2490
2523
  async function writeManifest(dir, 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)}
2524
+ const present2 = Object.fromEntries(Object.entries(files).filter(([name]) => existsSync4(path5.join(dir, name))));
2525
+ await writePrivate(path5.join(dir, MANIFEST), `${JSON.stringify({ version: 1, files: present2 }, null, 2)}
2493
2526
  `);
2494
2527
  }
2495
2528
  async function backupsOf(dir, serverId) {
2496
2529
  const manifest = await readManifest(dir);
2497
- return (await listBackups(dir)).filter((b) => manifest[path4.basename(b.file)]?.serverId === serverId);
2530
+ return (await listBackups(dir)).filter((b) => manifest[path5.basename(b.file)]?.serverId === serverId);
2498
2531
  }
2499
2532
  async function originOf(dir, file) {
2500
- if (!existsSync4(dir) || !sameFile(path4.dirname(file), dir)) return null;
2501
- return (await readManifest(dir))[path4.basename(file)] ?? null;
2533
+ if (!existsSync4(dir) || !sameFile(path5.dirname(file), dir)) return null;
2534
+ return (await readManifest(dir))[path5.basename(file)] ?? null;
2502
2535
  }
2503
2536
  async function originsIn(dir) {
2504
2537
  if (!existsSync4(dir)) return [];
@@ -2510,12 +2543,12 @@ async function saveBackup(dir, name, xml2, opts) {
2510
2543
  await ensureBackupDir(dir);
2511
2544
  const manifest = await readManifest(dir);
2512
2545
  const base = `${name}-${stamp(opts.now ?? /* @__PURE__ */ new Date())}`;
2513
- let file = path4.join(dir, `${base}.xml`);
2514
- for (let n = 2; existsSync4(file); n += 1) file = path4.join(dir, `${base}-${n}.xml`);
2546
+ let file = path5.join(dir, `${base}.xml`);
2547
+ for (let n = 2; existsSync4(file); n += 1) file = path5.join(dir, `${base}-${n}.xml`);
2515
2548
  await writePrivate(file, xml2);
2516
- manifest[path4.basename(file)] = opts.origin;
2549
+ manifest[path5.basename(file)] = opts.origin;
2517
2550
  await writeManifest(dir, manifest);
2518
- const mine = (await listBackups(dir)).filter((b) => manifest[path4.basename(b.file)]?.serverId === opts.origin.serverId);
2551
+ const mine = (await listBackups(dir)).filter((b) => manifest[path5.basename(b.file)]?.serverId === opts.origin.serverId);
2519
2552
  for (const old of mine.slice(0, Math.max(0, mine.length - opts.keep))) {
2520
2553
  if (sameFile(old.file, file) || opts.protect !== void 0 && sameFile(old.file, opts.protect)) continue;
2521
2554
  await rm2(old.file);
@@ -2525,15 +2558,15 @@ async function saveBackup(dir, name, xml2, opts) {
2525
2558
  }
2526
2559
  function sameFile(a, b) {
2527
2560
  const real = (p) => {
2528
- const resolved = existsSync4(p) ? realpathSync.native(p) : path4.resolve(p);
2561
+ const resolved = existsSync4(p) ? realpathSync.native(p) : path5.resolve(p);
2529
2562
  return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
2530
2563
  };
2531
2564
  return real(a) === real(b);
2532
2565
  }
2533
2566
  async function ensureBackupDir(dir) {
2534
2567
  if (existsSync4(dir)) return;
2535
- await mkdir3(dir, { recursive: true });
2536
- await writeFile4(path4.join(dir, ".gitignore"), "# channelvault backups hold credentials in plain text\n*\n");
2568
+ await mkdir3(dir, { recursive: true, mode: 448 });
2569
+ await writeFile4(path5.join(dir, ".gitignore"), "# channelvault backups hold credentials in plain text\n*\n");
2537
2570
  }
2538
2571
  async function writePrivate(file, text) {
2539
2572
  const temp = `${file}.${process.pid}-${randomBytes2(4).toString("hex")}.tmp`;
@@ -2561,22 +2594,22 @@ function compareVersions(a, b) {
2561
2594
 
2562
2595
  // src/xml/chars.ts
2563
2596
  import { readFile as readFile5 } from "fs/promises";
2564
- import * as path6 from "path";
2597
+ import * as path7 from "path";
2565
2598
 
2566
2599
  // src/tree/transaction.ts
2567
2600
  import { randomUUID } from "crypto";
2568
2601
  import { constants, existsSync as existsSync5 } from "fs";
2569
2602
  import { copyFile as copyFile2, lstat as lstat2, mkdir as mkdir4, readdir as readdir5, readlink, realpath as realpath3, rename as rename3, rm as rm3, rmdir, unlink, writeFile as writeFile5 } from "fs/promises";
2570
2603
  import { hostname } from "os";
2571
- import * as path5 from "path";
2604
+ import * as path6 from "path";
2572
2605
  import { setTimeout as delay } from "timers/promises";
2573
2606
  var MANAGED_DIRS = ["server", "channels", "codeTemplates", "channelGroups"];
2574
2607
  async function treeFiles(base) {
2575
2608
  const out = [];
2576
2609
  for (const d of MANAGED_DIRS) {
2577
- if (!existsSync5(path5.join(base, d))) continue;
2578
- for (const entry of await readdir5(path5.join(base, d), { recursive: true, withFileTypes: true })) {
2579
- if (entry.isFile()) out.push(path5.relative(base, path5.join(entry.parentPath, entry.name)).split(path5.sep).join("/"));
2610
+ if (!existsSync5(path6.join(base, d))) continue;
2611
+ for (const entry of await readdir5(path6.join(base, d), { recursive: true, withFileTypes: true })) {
2612
+ if (entry.isFile()) out.push(path6.relative(base, path6.join(entry.parentPath, entry.name)).split(path6.sep).join("/"));
2580
2613
  }
2581
2614
  }
2582
2615
  return out;
@@ -2593,11 +2626,11 @@ async function present(file) {
2593
2626
  }
2594
2627
  async function canonical(file, depth = 0) {
2595
2628
  if (depth > 64) throw new Error(`too many links in path: ${file}`);
2596
- let existing = path5.resolve(file);
2597
- while (!await present(existing) && path5.dirname(existing) !== existing) existing = path5.dirname(existing);
2629
+ let existing = path6.resolve(file);
2630
+ while (!await present(existing) && path6.dirname(existing) !== existing) existing = path6.dirname(existing);
2598
2631
  const info = await lstat2(existing);
2599
- const base = info.isSymbolicLink() ? await canonical(path5.resolve(path5.dirname(existing), await readlink(existing)), depth + 1) : await realpath3(existing);
2600
- return path5.join(base, path5.relative(existing, path5.resolve(file)));
2632
+ const base = info.isSymbolicLink() ? await canonical(path6.resolve(path6.dirname(existing), await readlink(existing)), depth + 1) : await realpath3(existing);
2633
+ return path6.join(base, path6.relative(existing, path6.resolve(file)));
2601
2634
  }
2602
2635
  var samePath = (a, b) => process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
2603
2636
  async function move(from, to) {
@@ -2612,9 +2645,9 @@ async function move(from, to) {
2612
2645
  }
2613
2646
  }
2614
2647
  async function lockTree(root) {
2615
- await mkdir4(path5.dirname(root), { recursive: true });
2648
+ await mkdir4(path6.dirname(root), { recursive: true });
2616
2649
  const lock = `${await canonical(root)}.channelvault-lock`;
2617
- const ownerFile = path5.join(lock, "owner.json");
2650
+ const ownerFile = path6.join(lock, "owner.json");
2618
2651
  const owner = { pid: process.pid, host: hostname(), token: randomUUID() };
2619
2652
  try {
2620
2653
  await mkdir4(lock);
@@ -2637,7 +2670,7 @@ async function lockTree(root) {
2637
2670
  }
2638
2671
  };
2639
2672
  if (!dead()) throw new Error(`working tree is locked by process ${previous.pid} on ${previous.host}: ${lock}`);
2640
- const reaping = path5.join(lock, "reaping");
2673
+ const reaping = path6.join(lock, "reaping");
2641
2674
  try {
2642
2675
  await mkdir4(reaping);
2643
2676
  } catch {
@@ -2668,7 +2701,7 @@ async function lockTree(root) {
2668
2701
  }
2669
2702
  async function assertStage(root) {
2670
2703
  for (const suffix of ["", "next", "previous"]) {
2671
- const stage = path5.join(root, STAGING_DIR, suffix);
2704
+ const stage = path6.join(root, STAGING_DIR, suffix);
2672
2705
  const info = await lstat2(stage).catch((err) => {
2673
2706
  if (err.code !== "ENOENT") throw err;
2674
2707
  return void 0;
@@ -2677,10 +2710,10 @@ async function assertStage(root) {
2677
2710
  }
2678
2711
  }
2679
2712
  function targetOf(root, journal, name) {
2680
- return name === "env" ? journal.envFile : path5.join(root, name);
2713
+ return name === "env" ? journal.envFile : path6.join(root, name);
2681
2714
  }
2682
2715
  function copies(root, journal, name) {
2683
- 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) };
2716
+ return name === "env" ? { old: `${journal.envFile}.channelvault-${journal.id}.previous`, next: `${journal.envFile}.channelvault-${journal.id}.next` } : { old: path6.join(root, STAGING_DIR, "previous", name), next: path6.join(root, STAGING_DIR, "next", name) };
2684
2717
  }
2685
2718
  async function cleanup(root, journal) {
2686
2719
  if (journal.entries.some((e) => e.name === "env")) {
@@ -2688,7 +2721,7 @@ async function cleanup(root, journal) {
2688
2721
  await rm3(old, { force: true });
2689
2722
  await rm3(next, { force: true });
2690
2723
  }
2691
- await rm3(path5.join(root, STAGING_DIR), RM);
2724
+ await rm3(path6.join(root, STAGING_DIR), RM);
2692
2725
  }
2693
2726
  async function rollback(root, journal) {
2694
2727
  for (const entry of [...journal.entries].reverse()) {
@@ -2703,7 +2736,7 @@ async function rollback(root, journal) {
2703
2736
  }
2704
2737
  }
2705
2738
  async function recoverTree(root, envFile) {
2706
- const file = path5.join(root, JOURNAL);
2739
+ const file = path6.join(root, JOURNAL);
2707
2740
  if (!existsSync5(file)) return;
2708
2741
  await assertStage(root);
2709
2742
  const journal = await readJson(file);
@@ -2717,9 +2750,9 @@ async function recoverTree(root, envFile) {
2717
2750
  async function replaceTree(root, envFile, prepare) {
2718
2751
  await recoverTree(root, envFile);
2719
2752
  await assertStage(root);
2720
- const stage = path5.join(root, STAGING_DIR);
2753
+ const stage = path6.join(root, STAGING_DIR);
2721
2754
  await rm3(stage, RM);
2722
- const next = path5.join(stage, "next");
2755
+ const next = path6.join(stage, "next");
2723
2756
  await mkdir4(next, { recursive: true });
2724
2757
  let journal;
2725
2758
  try {
@@ -2727,7 +2760,7 @@ async function replaceTree(root, envFile, prepare) {
2727
2760
  const targetEnv = await canonical(envFile);
2728
2761
  journal = { version: 1, id: randomUUID(), state: "prepared", envFile: targetEnv, entries: [] };
2729
2762
  for (const name of ITEMS) {
2730
- if (!MANAGED_DIRS.includes(name) && !existsSync5(path5.join(next, name === "env" ? ".env" : name))) continue;
2763
+ if (!MANAGED_DIRS.includes(name) && !existsSync5(path6.join(next, name === "env" ? ".env" : name))) continue;
2731
2764
  const target = targetOf(root, journal, name);
2732
2765
  const info = await lstat2(target).catch((err) => {
2733
2766
  if (err.code !== "ENOENT") throw err;
@@ -2735,38 +2768,38 @@ async function replaceTree(root, envFile, prepare) {
2735
2768
  });
2736
2769
  journal.entries.push({ name, hadOld: info !== void 0 });
2737
2770
  }
2738
- await mkdir4(path5.join(stage, "previous"));
2739
- await writePrivate(path5.join(root, JOURNAL), JSON.stringify(journal));
2771
+ await mkdir4(path6.join(stage, "previous"));
2772
+ await writePrivate(path6.join(root, JOURNAL), JSON.stringify(journal));
2740
2773
  if (journal.entries.some((e) => e.name === "env")) {
2741
- await mkdir4(path5.dirname(targetEnv), { recursive: true });
2742
- await copyFile2(path5.join(next, ".env"), copies(root, journal, "env").next, constants.COPYFILE_EXCL);
2774
+ await mkdir4(path6.dirname(targetEnv), { recursive: true });
2775
+ await copyFile2(path6.join(next, ".env"), copies(root, journal, "env").next, constants.COPYFILE_EXCL);
2743
2776
  }
2744
2777
  for (const entry of journal.entries) {
2745
2778
  const target = targetOf(root, journal, entry.name);
2746
2779
  const files = copies(root, journal, entry.name);
2747
2780
  if (entry.hadOld) await move(target, files.old);
2748
2781
  if (existsSync5(files.next)) {
2749
- await mkdir4(path5.dirname(target), { recursive: true });
2782
+ await mkdir4(path6.dirname(target), { recursive: true });
2750
2783
  await move(files.next, target);
2751
2784
  }
2752
2785
  }
2753
2786
  journal.state = "committed";
2754
- await writePrivate(path5.join(root, JOURNAL), JSON.stringify(journal));
2787
+ await writePrivate(path6.join(root, JOURNAL), JSON.stringify(journal));
2755
2788
  } catch (err) {
2756
- if (journal && existsSync5(path5.join(root, JOURNAL))) {
2789
+ if (journal && existsSync5(path6.join(root, JOURNAL))) {
2757
2790
  try {
2758
2791
  await rollback(root, journal);
2759
2792
  } catch (recoveryError) {
2760
- throw new Error(`replacement failed and recovery is pending in ${path5.join(root, JOURNAL)}; retry this command with the same env file`, { cause: recoveryError });
2793
+ throw new Error(`replacement failed and recovery is pending in ${path6.join(root, JOURNAL)}; retry this command with the same env file`, { cause: recoveryError });
2761
2794
  }
2762
2795
  await cleanup(root, journal);
2763
- await unlink(path5.join(root, JOURNAL));
2796
+ await unlink(path6.join(root, JOURNAL));
2764
2797
  }
2765
2798
  await rm3(stage, RM);
2766
2799
  throw err;
2767
2800
  }
2768
2801
  await cleanup(root, journal);
2769
- await unlink(path5.join(root, JOURNAL));
2802
+ await unlink(path6.join(root, JOURNAL));
2770
2803
  }
2771
2804
 
2772
2805
  // src/xml/chars.ts
@@ -2793,7 +2826,7 @@ function forbiddenXmlChars(config) {
2793
2826
  async function forbiddenInFiles(root) {
2794
2827
  const out = [];
2795
2828
  for (const file of await treeFiles(root)) {
2796
- for (const p of positions(await readFile5(path6.join(root, file), "utf8"))) out.push(`${file}:${p.line}:${p.column} (${p.codePoint})`);
2829
+ for (const p of positions(await readFile5(path7.join(root, file), "utf8"))) out.push(`${file}:${p.line}:${p.column} (${p.codePoint})`);
2797
2830
  }
2798
2831
  return out;
2799
2832
  }
@@ -2863,10 +2896,10 @@ function writeJson2(value) {
2863
2896
  `);
2864
2897
  }
2865
2898
  function addBackupDirFlags(cmd) {
2866
- return cmd.option("--backup-dir <dir>", `where backups are kept (default ./${DEFAULT_BACKUP_DIR})`).option("--keep <n>", `backups kept per server (default ${DEFAULT_KEEP})`);
2899
+ return cmd.option("--backup-dir <dir>", "where backups are kept (default ~/.channelvault/backups, shared by every checkout)").option("--keep <n>", `backups kept per server (default ${DEFAULT_KEEP})`);
2867
2900
  }
2868
2901
  function backupDirOf(flags) {
2869
- return path7.resolve(flags.backupDir ?? DEFAULT_BACKUP_DIR);
2902
+ return path8.resolve(flags.backupDir ?? defaultBackupDir());
2870
2903
  }
2871
2904
  function keepOf(flags) {
2872
2905
  if (flags.keep === void 0) return DEFAULT_KEEP;
@@ -2933,21 +2966,24 @@ function hostOf(flags) {
2933
2966
  const cfg = resolveClientConfig(flags);
2934
2967
  return `${cfg.host}:${cfg.port}`;
2935
2968
  }
2936
- async function confirm(question) {
2969
+ async function ask(question) {
2937
2970
  const rl = createInterface({ input: process.stdin, output: process.stdout });
2938
2971
  const controller = new AbortController();
2939
2972
  rl.once("close", () => controller.abort());
2940
2973
  rl.once("SIGINT", () => controller.abort());
2941
2974
  try {
2942
- const answer = (await rl.question(`${question} [y/N] `, { signal: controller.signal })).trim().toLowerCase();
2943
- return answer === "y" || answer === "yes";
2975
+ return (await rl.question(question, { signal: controller.signal })).trim();
2944
2976
  } catch (err) {
2945
- if (controller.signal.aborted) fail("confirmation interrupted; nothing was pushed");
2977
+ if (controller.signal.aborted) fail("confirmation interrupted; nothing was changed");
2946
2978
  throw err;
2947
2979
  } finally {
2948
2980
  rl.close();
2949
2981
  }
2950
2982
  }
2983
+ async function confirm(question) {
2984
+ const answer = (await ask(`${question} [y/N] `)).toLowerCase();
2985
+ return answer === "y" || answer === "yes";
2986
+ }
2951
2987
  function summarize(config) {
2952
2988
  const asArray2 = (v) => Array.isArray(v) ? v : v == null ? [] : [v];
2953
2989
  const channels = asArray2(config.channels?.channel);
@@ -2980,24 +3016,24 @@ async function writeMeta(root, source, config, previous, serverId, resources = r
2980
3016
  resources,
2981
3017
  serverId
2982
3018
  };
2983
- const file = path7.join(root, "channelvault.json");
3019
+ const file = path8.join(root, "channelvault.json");
2984
3020
  if (previous && JSON.stringify({ ...previous, pulledAt: "" }) === JSON.stringify({ ...meta, pulledAt: "" })) meta.pulledAt = previous.pulledAt;
2985
3021
  await writeFile6(file, JSON.stringify(meta, null, 2) + "\n", "utf8");
2986
3022
  }
2987
3023
  function envFilePath(root, flags) {
2988
- return flags.dotenv ? path7.resolve(flags.dotenv) : path7.join(root, ".env");
3024
+ return flags.dotenv ? path8.resolve(flags.dotenv) : path8.join(root, ".env");
2989
3025
  }
2990
3026
  async function loadEnv(file) {
2991
3027
  return { ...await readEnvFile(file), ...process.env };
2992
3028
  }
2993
3029
  function addEnvFlag(cmd) {
2994
- return cmd.option("--dotenv <path>", "env file holding secrets and per-environment values (default <dir>/.env)");
3030
+ return cmd.option("--dotenv <path>", "env file holding the tree's placeholder values, not the login (default <dir>/.env)");
2995
3031
  }
2996
3032
  function addExtractFlag(cmd) {
2997
3033
  return cmd.option("--extract-secrets", "move secrets found inside values (URLs, scripts, headers) to the env file", false);
2998
3034
  }
2999
3035
  async function existingTree(root) {
3000
- return existsSync6(path7.join(root, "server", "configuration.json")) ? engine.implode({ root }) : null;
3036
+ return existsSync6(path8.join(root, "server", "configuration.json")) ? engine.implode({ root }) : null;
3001
3037
  }
3002
3038
  async function renderedTree(root, flags) {
3003
3039
  const tree = await engine.implode({ root });
@@ -3026,7 +3062,7 @@ function scrub(text) {
3026
3062
  }
3027
3063
  var ALLOW_FILE = "channelvault.allow.json";
3028
3064
  async function readAllow(root) {
3029
- const file = path7.join(root, ALLOW_FILE);
3065
+ const file = path8.join(root, ALLOW_FILE);
3030
3066
  if (!existsSync6(file)) return [];
3031
3067
  const parsed = await readJson(file);
3032
3068
  return parsed.ignore ?? [];
@@ -3052,26 +3088,26 @@ Rerun with --extract-secrets to move them to ${envFile}, or list false positives
3052
3088
  const envUpdates = { ...templated.envUpdates, ...scan.envUpdates };
3053
3089
  rememberSecrets(config, { ...env, ...envUpdates });
3054
3090
  const echoes = findEchoes(config, { ...await readEnvFile(envFile), ...envUpdates });
3055
- const rel = path7.relative(root, envFile);
3056
- const envInTree = !rel.startsWith("..") && !path7.isAbsolute(rel);
3091
+ const rel = path8.relative(root, envFile);
3092
+ const envInTree = !rel.startsWith("..") && !path8.isAbsolute(rel);
3057
3093
  let backup = null;
3058
3094
  await replaceTree(root, envFile, async (next) => {
3059
3095
  await engine.explode(config, { root: next });
3060
3096
  await writeMeta(next, source, fetched, previousMeta, serverId);
3061
3097
  if (Object.keys(envUpdates).length > 0) {
3062
- const history = path7.join(root, ".secrets");
3098
+ const history = path8.join(root, ".secrets");
3063
3099
  if (existsSync6(history)) {
3064
3100
  if ((await lstat3(history)).isSymbolicLink()) fail(`refusing a linked secret history directory: ${history}`);
3065
- await cp(history, path7.join(next, ".secrets"), { recursive: true });
3101
+ await cp(history, path8.join(next, ".secrets"), { recursive: true });
3066
3102
  }
3067
- const stagedBackup = await backupEnvFile(envFile, envUpdates, path7.join(next, ".secrets"));
3068
- if (stagedBackup) backup = path7.join(root, ".secrets", path7.basename(stagedBackup));
3103
+ const stagedBackup = await backupEnvFile(envFile, envUpdates, path8.join(next, ".secrets"));
3104
+ if (stagedBackup) backup = path8.join(root, ".secrets", path8.basename(stagedBackup));
3069
3105
  if (backup || envInTree) {
3070
- const ignore = path7.join(root, ".gitignore");
3071
- if (existsSync6(ignore)) await writeFile6(path7.join(next, ".gitignore"), await readFile6(ignore));
3106
+ const ignore = path8.join(root, ".gitignore");
3107
+ if (existsSync6(ignore)) await writeFile6(path8.join(next, ".gitignore"), await readFile6(ignore));
3072
3108
  await ensureEnvIgnored(next, envInTree ? envFile : void 0, root);
3073
3109
  }
3074
- const stagedEnv = path7.join(next, ".env");
3110
+ const stagedEnv = path8.join(next, ".env");
3075
3111
  if (existsSync6(envFile)) await writeFile6(stagedEnv, await readFile6(envFile), { mode: 384 });
3076
3112
  await updateEnvFile(stagedEnv, envUpdates);
3077
3113
  }
@@ -3095,27 +3131,27 @@ Rerun with --extract-secrets to move them to ${envFile}, or list false positives
3095
3131
  }
3096
3132
  }
3097
3133
  function gitWouldCommit(file) {
3098
- const r = spawnSync("git", ["check-ignore", "-q", path7.basename(file)], { cwd: path7.dirname(file) });
3134
+ const r = spawnSync("git", ["check-ignore", "-q", path8.basename(file)], { cwd: path8.dirname(file) });
3099
3135
  return r.status === 1;
3100
3136
  }
3101
3137
  async function resolvedPath(p) {
3102
- const abs = path7.resolve(p);
3138
+ const abs = path8.resolve(p);
3103
3139
  let existing = abs;
3104
- while (!existsSync6(existing) && path7.dirname(existing) !== existing) existing = path7.dirname(existing);
3105
- return path7.join(await realpath4(existing), path7.relative(existing, abs));
3140
+ while (!existsSync6(existing) && path8.dirname(existing) !== existing) existing = path8.dirname(existing);
3141
+ return path8.join(await realpath4(existing), path8.relative(existing, abs));
3106
3142
  }
3107
3143
  function isWithin(child, parent) {
3108
3144
  const norm = (p) => process.platform === "win32" ? p.toLowerCase() : p;
3109
- const rel = path7.relative(norm(parent), norm(child));
3110
- return rel === "" || rel !== ".." && !rel.startsWith(`..${path7.sep}`) && !path7.isAbsolute(rel);
3145
+ const rel = path8.relative(norm(parent), norm(child));
3146
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${path8.sep}`) && !path8.isAbsolute(rel);
3111
3147
  }
3112
3148
  async function preflightTree(root, envFile) {
3113
3149
  const [realRoot, realEnv] = await Promise.all([resolvedPath(root), resolvedPath(envFile)]);
3114
3150
  const doomed = [...MANAGED_DIRS, STAGING_DIR, JOURNAL, "channelvault.json", ".gitignore", ".secrets"].find(
3115
- (d) => isWithin(path7.resolve(envFile), path7.resolve(root, d)) || isWithin(realEnv, path7.join(realRoot, d))
3151
+ (d) => isWithin(path8.resolve(envFile), path8.resolve(root, d)) || isWithin(realEnv, path8.join(realRoot, d))
3116
3152
  );
3117
3153
  if (doomed) fail(`the env file ${envFile} is inside ${doomed}/, which this command replaces; keep it elsewhere`);
3118
- const metaPath = path7.join(root, "channelvault.json");
3154
+ const metaPath = path8.join(root, "channelvault.json");
3119
3155
  if (existsSync6(metaPath)) {
3120
3156
  let meta;
3121
3157
  try {
@@ -3130,7 +3166,7 @@ async function preflightTree(root, envFile) {
3130
3166
  }
3131
3167
  return meta;
3132
3168
  }
3133
- const foreign = MANAGED_DIRS.filter((d) => existsSync6(path7.join(root, d)));
3169
+ const foreign = MANAGED_DIRS.filter((d) => existsSync6(path8.join(root, d)));
3134
3170
  if (foreign.length > 0) {
3135
3171
  fail(
3136
3172
  `${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).`
@@ -3139,12 +3175,12 @@ async function preflightTree(root, envFile) {
3139
3175
  return null;
3140
3176
  }
3141
3177
  function assertTree(root) {
3142
- if (!existsSync6(path7.join(root, "server", "configuration.json"))) {
3178
+ if (!existsSync6(path8.join(root, "server", "configuration.json"))) {
3143
3179
  fail(`${root} is not a channelvault tree (missing server/configuration.json). Run 'pull' or 'explode' first.`);
3144
3180
  }
3145
3181
  }
3146
3182
  async function readTreeOrigin(root) {
3147
- const metaPath = path7.join(root, "channelvault.json");
3183
+ const metaPath = path8.join(root, "channelvault.json");
3148
3184
  if (!existsSync6(metaPath)) return "unknown";
3149
3185
  try {
3150
3186
  const meta = await readJson(metaPath);
@@ -3173,7 +3209,7 @@ function collect(value, previous) {
3173
3209
  return [...previous ?? [], value];
3174
3210
  }
3175
3211
  async function bindingProblems(root, serverId) {
3176
- const file = path7.join(root, "channelvault.json");
3212
+ const file = path8.join(root, "channelvault.json");
3177
3213
  const meta = existsSync6(file) ? await readJson(file) : null;
3178
3214
  if (meta?.serverId === serverId) return [];
3179
3215
  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`];
@@ -3187,12 +3223,12 @@ async function assertBinding(client, root) {
3187
3223
  if (problems.length) fail(problems.join("\n"));
3188
3224
  }
3189
3225
  async function readKnown(root) {
3190
- const metaPath = path7.join(root, "channelvault.json");
3226
+ const metaPath = path8.join(root, "channelvault.json");
3191
3227
  if (!existsSync6(metaPath)) return void 0;
3192
3228
  return knownFrom((await readJson(metaPath)).resources);
3193
3229
  }
3194
3230
  async function writeKnown(root, known) {
3195
- const metaPath = path7.join(root, "channelvault.json");
3231
+ const metaPath = path8.join(root, "channelvault.json");
3196
3232
  if (!existsSync6(metaPath)) return;
3197
3233
  const meta = await readJson(metaPath);
3198
3234
  if (!meta.resources) return;
@@ -3372,9 +3408,26 @@ ${baselineError}` : ""}`);
3372
3408
  not checked after saving (these cannot be read one at a time): ${unverified.join(", ")}` : "";
3373
3409
  fail(`pushed ${result.applied.length} change(s), but could not refresh the local sync baseline: ${baselineError}${note}`);
3374
3410
  }
3411
+ printCommitHint(root);
3412
+ }
3413
+ function printCommitHint(root) {
3414
+ const r = spawnSync("git", ["status", "--porcelain", "-z", "--untracked-files=all", "--", "."], { cwd: root, encoding: "utf8" });
3415
+ if (r.status !== 0 || !r.stdout) return;
3416
+ const entries = r.stdout.split("\0");
3417
+ const files = [];
3418
+ for (let i = 0; i < entries.length; i++) {
3419
+ const entry = entries[i];
3420
+ if (entry.length < 4) continue;
3421
+ files.push(entry.slice(3));
3422
+ if (entry[0] === "R" || entry[0] === "C") i++;
3423
+ }
3424
+ if (files.length === 0) return;
3425
+ const shown = files.length > 10 ? [...files.slice(0, 10), `and ${files.length - 10} more`] : files;
3426
+ process.stdout.write(`commit the refreshed baseline with your change (paths from the repository root): ${shown.join(", ")}
3427
+ `);
3375
3428
  }
3376
3429
  function exportBrokenHint(flags) {
3377
- const undo = flags.backup === false ? "" : " (including the undo command above)";
3430
+ const undo = flags.backup === false ? "" : " (including the undo command above, unless you add --export-broken to it, which restores without a preview or an undo backup)";
3378
3431
  return `If the server cannot export its configuration, pull, diff, push and restore${undo} fail until the resource that broke it is fixed in the Administrator; then pull or adopt to refresh the baseline`;
3379
3432
  }
3380
3433
  async function changedAgainSingly(client, applied, local) {
@@ -3465,6 +3518,7 @@ async function wholeServerPush(client, root, local, target, flags) {
3465
3518
  if (known) await writeKnown(root, resourceIds(after));
3466
3519
  process.stdout.write(`pushed ${root} -> ${target}
3467
3520
  `);
3521
+ printCommitHint(root);
3468
3522
  }
3469
3523
  var program = new Command();
3470
3524
  program.name("channelvault").description("Git-style pull/push/diff for Mirth Connect").version(VERSION).allowExcessArguments(false);
@@ -3472,8 +3526,8 @@ addExtractFlag(addEnvFlag(
3472
3526
  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")
3473
3527
  )).action(async (backupPath, dir, flags) => {
3474
3528
  const config = xml.parse(await readFile6(backupPath, "utf8"));
3475
- const root = path7.resolve(dir);
3476
- await writeTree(root, config, `file:${path7.resolve(backupPath)}`, flags);
3529
+ const root = path8.resolve(dir);
3530
+ await writeTree(root, config, `file:${path8.resolve(backupPath)}`, flags);
3477
3531
  const s = summarize(config);
3478
3532
  process.stdout.write(`exploded ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}
3479
3533
  `);
@@ -3481,19 +3535,19 @@ addExtractFlag(addEnvFlag(
3481
3535
  addEnvFlag(
3482
3536
  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)
3483
3537
  ).action(async (dir, outPath, flags) => {
3484
- const root = path7.resolve(dir);
3538
+ const root = path8.resolve(dir);
3485
3539
  assertTree(root);
3486
3540
  const config = await renderedTree(root, flags);
3487
3541
  await assertCompatibleOrigin(root, config, "xml", flags.force === true);
3488
3542
  const xmlStr = xml.build(config);
3489
3543
  await writeFile6(outPath, xmlStr, "utf8");
3490
- process.stdout.write(`imploded ${root} -> ${path7.resolve(outPath)}
3544
+ process.stdout.write(`imploded ${root} -> ${path8.resolve(outPath)}
3491
3545
  `);
3492
3546
  });
3493
3547
  addExtractFlag(addEnvFlag(addConnectionFlags(
3494
3548
  program.command("pull").description("Pull the live server configuration into a working tree").argument("<dir>", "working-tree directory")
3495
3549
  ))).action(async (dir, flags) => {
3496
- const root = path7.resolve(dir);
3550
+ const root = path8.resolve(dir);
3497
3551
  await preflightTree(root, envFilePath(root, flags));
3498
3552
  const { config, serverId } = await withClient(flags, async (client) => {
3499
3553
  const serverId2 = await client.getServerId();
@@ -3510,7 +3564,7 @@ addExtractFlag(addEnvFlag(addConnectionFlags(
3510
3564
  addJsonFlag(addEnvFlag(addConnectionFlags(
3511
3565
  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)
3512
3566
  ))).action(async (dir, flags) => {
3513
- const root = path7.resolve(dir);
3567
+ const root = path8.resolve(dir);
3514
3568
  assertTree(root);
3515
3569
  const previous = await preflightTree(root, envFilePath(root, flags));
3516
3570
  const stored = await engine.implode({ root });
@@ -3564,7 +3618,7 @@ addBackupDirFlags(addEnvFlag(addConnectionFlags(
3564
3618
  fail("--whole-server replaces everything; it cannot be combined with --channel, --library or --global-scripts");
3565
3619
  }
3566
3620
  if (flags.overwriteConfigMap && !flags.wholeServer) fail("--overwrite-config-map needs --whole-server");
3567
- const root = path7.resolve(dir);
3621
+ const root = path8.resolve(dir);
3568
3622
  assertTree(root);
3569
3623
  const config = await renderedTree(root, flags);
3570
3624
  await assertCompatibleOrigin(root, config, "live", flags.ignoreOrigin === true);
@@ -3583,17 +3637,17 @@ addBackupDirFlags(addEnvFlag(addConnectionFlags(
3583
3637
  }
3584
3638
  );
3585
3639
  addBackupDirFlags(addConnectionFlags(
3586
- program.command("backup").description(`Save the server configuration as <server>-<UTC time>.xml in ./${DEFAULT_BACKUP_DIR} (holds credentials in plain text)`).option("--out <file>", "write to this file instead (no rotation)")
3640
+ program.command("backup").description("Save the server configuration as <server>-<UTC time>.xml in ~/.channelvault/backups (holds credentials in plain text)").option("--out <file>", "write to this file instead (no rotation)")
3587
3641
  )).action(async (flags) => {
3588
3642
  const cfg = resolveClientConfig(flags);
3589
3643
  const target = `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`;
3590
3644
  const file = await withClient(flags, async (client) => {
3591
3645
  const text = await client.getServerConfigurationXml();
3592
3646
  if (!flags.out) return saveServerBackup(client, text, flags);
3593
- const out = path7.resolve(flags.out);
3647
+ const out = path8.resolve(flags.out);
3594
3648
  parseBackup(text, "the server configuration");
3595
3649
  if (existsSync6(out)) fail(`${out} already exists; choose another name`);
3596
- await mkdir5(path7.dirname(out), { recursive: true });
3650
+ await mkdir5(path8.dirname(out), { recursive: true });
3597
3651
  await writePrivate(out, text);
3598
3652
  if (gitWouldCommit(out)) {
3599
3653
  process.stderr.write(`warning: git does not ignore ${out}, which holds credentials in plain text; add it to .gitignore
@@ -3604,29 +3658,90 @@ addBackupDirFlags(addConnectionFlags(
3604
3658
  process.stdout.write(`backed up ${target} to ${file}
3605
3659
  `);
3606
3660
  });
3661
+ async function chooseBackup(dir, file, serverId, target) {
3662
+ if (file) {
3663
+ const chosen = path8.resolve(file);
3664
+ if (!existsSync6(chosen)) fail(`${chosen} does not exist`);
3665
+ return chosen;
3666
+ }
3667
+ const mine = await backupsOf(dir, serverId);
3668
+ if (mine.length === 0) {
3669
+ const others = (await originsIn(dir)).map((o) => o.host);
3670
+ const legacy = path8.resolve(LEGACY_BACKUP_DIR);
3671
+ const inLegacy = legacy !== dir && (await backupsOf(legacy, serverId)).length > 0;
3672
+ fail(`no backups of ${target} in ${dir}${others.length ? ` (it has backups of: ${others.join(", ")})` : ""}` + (inLegacy ? `; ${legacy} has backups of this server (the default before 0.3.0-rc.3): pass --backup-dir ${shellArgument(legacy)}` : ""));
3673
+ }
3674
+ return mine[mine.length - 1].file;
3675
+ }
3676
+ async function restoreWithBrokenExport(client, file, flags, target) {
3677
+ try {
3678
+ await client.getServerConfigurationXml();
3679
+ fail("the server can export its configuration; run restore without --export-broken, which shows a preview and saves an undo backup first");
3680
+ } catch (err) {
3681
+ if (err instanceof CliError) throw err;
3682
+ if (err.status !== 500) {
3683
+ fail(`cannot tell whether the export is broken: ${err instanceof Error ? err.message : String(err)}; --export-broken only proceeds when the server answers its export with HTTP 500`);
3684
+ }
3685
+ }
3686
+ const serverId = await client.getServerId();
3687
+ const dir = backupDirOf(flags);
3688
+ const chosen = await chooseBackup(dir, file, serverId, target);
3689
+ const text = await readFile6(chosen, "utf8");
3690
+ const backup = parseBackup(text, chosen);
3691
+ const unsafe = await xmlSafetyProblem(backup);
3692
+ if (unsafe) fail(`${chosen} holds ${unsafe}`);
3693
+ const origin = await originOf(dir, chosen);
3694
+ if (!origin && !flags.force) {
3695
+ fail(`${chosen} is not in ${path8.join(dir, MANIFEST)}, and without the server's export its name cannot be compared either; pass --force to restore it anyway`);
3696
+ }
3697
+ if (origin && origin.serverId !== serverId && !flags.force) {
3698
+ fail(`${chosen} was taken from ${origin.host} (server ID ${origin.serverId}), not this server (${serverId}); pass --force to restore it here anyway`);
3699
+ }
3700
+ process.stdout.write(
3701
+ `Restore ${chosen}
3702
+ to ${target} (installation ${serverId}), replacing its ENTIRE configuration${flags.deploy ? ", then redeploy all channels" : ""}.
3703
+ The server cannot export its configuration, so there is no preview, no undo backup and no version check.
3704
+ `
3705
+ );
3706
+ if (!flags.yes && await ask(`Type the installation ID (${serverId}) to continue: `) !== serverId) {
3707
+ process.stdout.write("aborted.\n");
3708
+ return;
3709
+ }
3710
+ await client.putServerConfigurationXml(text, { deploy: flags.deploy === true, overwriteConfigMap: flags.overwriteConfigMap === true });
3711
+ let afterText;
3712
+ try {
3713
+ afterText = await client.getServerConfigurationXml();
3714
+ } catch (err) {
3715
+ fail(`sent ${chosen} to ${target}, but the server still cannot export its configuration: ${err instanceof Error ? err.message : String(err)}; inspect it in the Administrator`);
3716
+ }
3717
+ const differ = planPush(backup, parseBackup(afterText, "the server configuration"), {}, void 0, { wholeReplace: true }).changes;
3718
+ if (differ.length > 0) {
3719
+ fail(`restored, but these differ from the backup afterwards: ${differ.map((c) => c.label).join(", ")}; inspect the server`);
3720
+ }
3721
+ process.stdout.write(`restored ${chosen} to ${target}; the server exports its configuration again
3722
+ `);
3723
+ }
3607
3724
  addBackupDirFlags(addConnectionFlags(
3608
- program.command("restore").description("Replace the entire server configuration with a backup (default: the newest backup of this server)").argument("[file]", "backup XML to restore").option("--deploy", "redeploy all channels afterwards", false).option("--overwrite-config-map", "also replace the configuration map", false).option("--force", "restore a backup taken from another server", false).option("-y, --yes", "skip the confirmation prompt", false)
3725
+ program.command("restore").description("Replace the entire server configuration with a backup (default: the newest backup of this server)").argument("[file]", "backup XML to restore").option("--deploy", "redeploy all channels afterwards", false).option("--overwrite-config-map", "also replace the configuration map", false).option("--force", "restore a backup taken from another server", false).option("--export-broken", "the server cannot export its configuration (HTTP 500): restore without a preview, undo backup or version check", false).option("-y, --yes", "skip the confirmation prompt", false)
3609
3726
  )).action(async (file, flags) => {
3610
3727
  const cfg = resolveClientConfig(flags);
3611
3728
  const target = `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`;
3612
3729
  if (!flags.yes && !process.stdin.isTTY) fail("no terminal to confirm on; pass --yes");
3613
3730
  const dir = backupDirOf(flags);
3614
3731
  await withClient(flags, async (client) => {
3615
- const currentText = await client.getServerConfigurationXml();
3732
+ if (flags.exportBroken) {
3733
+ await restoreWithBrokenExport(client, file, flags, target);
3734
+ return;
3735
+ }
3736
+ let currentText;
3737
+ try {
3738
+ currentText = await client.getServerConfigurationXml();
3739
+ } catch (err) {
3740
+ fail(`cannot read the server's current configuration: ${err instanceof Error ? err.message : String(err)}. If its export is broken (for example HTTP 500), restore with --export-broken, which skips the preview and the undo backup`);
3741
+ }
3616
3742
  const current = parseBackup(currentText, "the server configuration");
3617
3743
  const serverId = await client.getServerId();
3618
- let chosen;
3619
- if (file) {
3620
- chosen = path7.resolve(file);
3621
- if (!existsSync6(chosen)) fail(`${chosen} does not exist`);
3622
- } else {
3623
- const mine = await backupsOf(dir, serverId);
3624
- if (mine.length === 0) {
3625
- const others = (await originsIn(dir)).map((o) => o.host);
3626
- fail(`no backups of ${target} in ${dir}${others.length ? ` (it has backups of: ${others.join(", ")})` : ""}`);
3627
- }
3628
- chosen = mine[mine.length - 1].file;
3629
- }
3744
+ const chosen = await chooseBackup(dir, file, serverId, target);
3630
3745
  const text = await readFile6(chosen, "utf8");
3631
3746
  const backup = parseBackup(text, chosen);
3632
3747
  const unsafe = await xmlSafetyProblem(backup);
@@ -3641,7 +3756,7 @@ addBackupDirFlags(addConnectionFlags(
3641
3756
  if (fromContent !== "" && fromServer !== "" && fromContent !== fromServer && !flags.force) {
3642
3757
  fail(`${chosen} is a backup of ${fromContent}, not ${fromServer}; pass --force to restore it here anyway`);
3643
3758
  }
3644
- process.stderr.write(`warning: ${chosen} is not in ${path7.join(dir, MANIFEST)}, so which server it came from cannot be checked
3759
+ process.stderr.write(`warning: ${chosen} is not in ${path8.join(dir, MANIFEST)}, so which server it came from cannot be checked
3645
3760
  `);
3646
3761
  }
3647
3762
  const [bv, sv] = [backup["@_version"], current["@_version"]];
@@ -3700,7 +3815,7 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
3700
3815
  })
3701
3816
  ))).action(async (dir, flags) => {
3702
3817
  errorExitCode = 2;
3703
- const root = path7.resolve(dir);
3818
+ const root = path8.resolve(dir);
3704
3819
  assertTree(root);
3705
3820
  const fetched = await withClient(flags, (client) => client.getServerConfiguration());
3706
3821
  const tree = await engine.implode({ root });
@@ -3713,7 +3828,7 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
3713
3828
  const allow = await readAllow(root);
3714
3829
  const staleRevisions = newerOnServer(tree, templatedRemote);
3715
3830
  if (staleRevisions.length > 0) {
3716
- messages.push(`${staleRevisions.length} resource(s) have a newer revision on the server; pull to update the tree's baseline`);
3831
+ messages.push(`${staleRevisions.length} resource(s) have a newer revision on the server; pull to update the tree's baseline, or adopt it when the content already matches`);
3717
3832
  }
3718
3833
  const treeView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withoutVolatile(tree))), { mode: "redact", allow });
3719
3834
  const serverView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withoutVolatile(templatedRemote))), { mode: "redact", allow });
@@ -3723,15 +3838,15 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
3723
3838
  if (serverView.findings.length > 0) messages.push(`${serverView.findings.length} possible secret(s) on the server are redacted below`);
3724
3839
  if (!flags.json) for (const m of messages) process.stderr.write(`note: ${m}
3725
3840
  `);
3726
- const tmp = await mkdtemp(path7.join(tmpdir(), "channelvault-diff-"));
3841
+ const tmp = await mkdtemp(path8.join(tmpdir(), "channelvault-diff-"));
3727
3842
  try {
3728
- await engine.explode(treeView.config, { root: path7.join(tmp, "tree") });
3729
- await engine.explode(serverView.config, { root: path7.join(tmp, "server") });
3730
- await mkdir5(path7.join(tmp, ".empty"));
3843
+ await engine.explode(treeView.config, { root: path8.join(tmp, "tree") });
3844
+ await engine.explode(serverView.config, { root: path8.join(tmp, "server") });
3845
+ await mkdir5(path8.join(tmp, ".empty"));
3731
3846
  const chunks = [];
3732
3847
  for (const d of MANAGED_DIRS) {
3733
- const local = existsSync6(path7.join(tmp, "tree", d)) ? `tree/${d}` : ".empty";
3734
- const server = existsSync6(path7.join(tmp, "server", d)) ? `server/${d}` : ".empty";
3848
+ const local = existsSync6(path8.join(tmp, "tree", d)) ? `tree/${d}` : ".empty";
3849
+ const server = existsSync6(path8.join(tmp, "server", d)) ? `server/${d}` : ".empty";
3735
3850
  if (local === ".empty" && server === ".empty") continue;
3736
3851
  const result = spawnSync(
3737
3852
  "git",
@@ -3753,7 +3868,7 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
3753
3868
  const clean = out === "" && secretDrift.length === 0;
3754
3869
  if (!clean) process.exitCode = 1;
3755
3870
  if (flags.json) {
3756
- const files = await changedFiles(path7.join(tmp, "tree"), path7.join(tmp, "server"));
3871
+ const files = await changedFiles(path8.join(tmp, "tree"), path8.join(tmp, "server"));
3757
3872
  writeJson2({ clean, files, secretDrift, staleRevisions, notes: messages, patch: out });
3758
3873
  } else if (clean) {
3759
3874
  process.stdout.write("no differences \u2014 working tree matches the server.\n");
@@ -3774,7 +3889,7 @@ async function changedFiles(treeDir, serverDir) {
3774
3889
  const files = [];
3775
3890
  for (const p of local) {
3776
3891
  if (!remoteSet.has(p)) files.push({ path: p, change: "only-in-tree" });
3777
- else if (await readFile6(path7.join(treeDir, p), "utf8") !== await readFile6(path7.join(serverDir, p), "utf8")) files.push({ path: p, change: "modified" });
3892
+ else if (await readFile6(path8.join(treeDir, p), "utf8") !== await readFile6(path8.join(serverDir, p), "utf8")) files.push({ path: p, change: "modified" });
3778
3893
  }
3779
3894
  const localSet = new Set(local);
3780
3895
  for (const p of remote) if (!localSet.has(p)) files.push({ path: p, change: "only-on-server" });
@@ -3783,11 +3898,11 @@ async function changedFiles(treeDir, serverDir) {
3783
3898
  addJsonFlag(addEnvFlag(
3784
3899
  program.command("status").description("Summarize a working tree").argument("<dir>", "working-tree directory")
3785
3900
  )).action(async (dir, flags) => {
3786
- const root = path7.resolve(dir);
3901
+ const root = path8.resolve(dir);
3787
3902
  assertTree(root);
3788
3903
  const config = await engine.implode({ root });
3789
3904
  const s = summarize(config);
3790
- const metaPath = path7.join(root, "channelvault.json");
3905
+ const metaPath = path8.join(root, "channelvault.json");
3791
3906
  const meta = existsSync6(metaPath) ? await readJson(metaPath) : null;
3792
3907
  if (flags.json) {
3793
3908
  writeJson2({
@@ -3823,7 +3938,7 @@ program.hook("preAction", async (_program, command) => {
3823
3938
  const name = command.name();
3824
3939
  if (!["explode", "pull", "adopt", "push", "implode", "diff", "status"].includes(name)) return;
3825
3940
  if (name === "diff") errorExitCode = 2;
3826
- const root = path7.resolve(String(command.processedArgs[name === "explode" ? 1 : 0]));
3941
+ const root = path8.resolve(String(command.processedArgs[name === "explode" ? 1 : 0]));
3827
3942
  unlock = await lockTree(root);
3828
3943
  await recoverTree(root, envFilePath(root, command.opts()));
3829
3944
  });