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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -2,11 +2,11 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { spawnSync } from "child_process";
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";
5
+ import { cp, lstat as lstat3, mkdir as mkdir5, mkdtemp, readFile as readFile6, realpath as realpath4, rm as rm4, writeFile as writeFile6 } from "fs/promises";
6
6
  import { existsSync as existsSync6 } from "fs";
7
7
  import { tmpdir } from "os";
8
8
  import { createRequire } from "module";
9
- import * as path6 from "path";
9
+ import * as path7 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, path7, labels, section, cmKey) => {
1003
+ const walk = (node, key, path8, labels, section, cmKey) => {
1004
1004
  if (typeof node === "string") {
1005
- return visit(node, { location: path7.join("/"), key, labels, section, configMapKey: cmKey });
1005
+ return visit(node, { location: path8.join("/"), key, labels, section, configMapKey: cmKey });
1006
1006
  }
1007
1007
  if (Array.isArray(node)) {
1008
- return node.map((el, i) => walk(el, key, [...path7.slice(0, -1), `${path7[path7.length - 1]}${elementSegment(el, i)}`], labels, section, cmKey));
1008
+ return node.map((el, i) => walk(el, key, [...path8.slice(0, -1), `${path8[path8.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, [...path7, k], inner, section || k, mapKey);
1016
+ out[k] = walk(v, k, [...path8, k], inner, section || k, mapKey);
1017
1017
  }
1018
1018
  return out;
1019
1019
  }
@@ -1613,15 +1613,15 @@ var MirthClientImpl = class {
1613
1613
  await this.request("POST", `/channels/${encodeURIComponent(id)}/_deploy`, { query: { returnErrors: true } });
1614
1614
  }
1615
1615
  /** Send a JSON body; Mirth answers some updates with `{"boolean": false}` instead of an error status. */
1616
- async sendJson(method, path7, body, query) {
1617
- const response = await this.request(method, path7, {
1616
+ async sendJson(method, path8, body, query) {
1617
+ const response = await this.request(method, path8, {
1618
1618
  query,
1619
1619
  headers: { "Content-Type": "application/json", Accept: "application/json" },
1620
1620
  body: JSON.stringify(body)
1621
1621
  });
1622
1622
  const text = await response.text();
1623
1623
  if (/^\s*\{\s*"boolean"\s*:\s*false\s*\}\s*$/.test(text)) {
1624
- throw new Error(`${method} ${path7}: the server refused the update`);
1624
+ throw new Error(`${method} ${path8}: the server refused the update`);
1625
1625
  }
1626
1626
  }
1627
1627
  // --- internal transport ---------------------------------------------------
@@ -1630,11 +1630,11 @@ var MirthClientImpl = class {
1630
1630
  * on a 401 while authenticated resets auth, re-logs in once, and retries.
1631
1631
  * Throws an {@link ApiError}-shaped error on a non-2xx response.
1632
1632
  */
1633
- async request(method, path7, options = {}, isRetry = false) {
1633
+ async request(method, path8, options = {}, isRetry = false) {
1634
1634
  if (!this.authenticated) {
1635
1635
  await this.login();
1636
1636
  }
1637
- const url = this.buildUrl(path7, options.query);
1637
+ const url = this.buildUrl(path8, options.query);
1638
1638
  const headers = {
1639
1639
  "X-Requested-With": "XMLHttpRequest",
1640
1640
  ...options.headers
@@ -1648,7 +1648,7 @@ var MirthClientImpl = class {
1648
1648
  if (response.status === 401 && this.authenticated && !isRetry) {
1649
1649
  this.authenticated = false;
1650
1650
  await this.login();
1651
- return this.request(method, path7, options, true);
1651
+ return this.request(method, path8, options, true);
1652
1652
  }
1653
1653
  if (!response.ok) {
1654
1654
  throw await this.toApiError(response);
@@ -1668,8 +1668,8 @@ var MirthClientImpl = class {
1668
1668
  }
1669
1669
  }
1670
1670
  /** Build an absolute URL with an optional query string. */
1671
- buildUrl(path7, query) {
1672
- const url = `${this.baseUrl}${path7}`;
1671
+ buildUrl(path8, query) {
1672
+ const url = `${this.baseUrl}${path8}`;
1673
1673
  if (!query || Object.keys(query).length === 0) {
1674
1674
  return url;
1675
1675
  }
@@ -2559,14 +2559,28 @@ function compareVersions(a, b) {
2559
2559
  return 0;
2560
2560
  }
2561
2561
 
2562
+ // src/xml/chars.ts
2563
+ import { readFile as readFile5 } from "fs/promises";
2564
+ import * as path6 from "path";
2565
+
2562
2566
  // src/tree/transaction.ts
2563
2567
  import { randomUUID } from "crypto";
2564
2568
  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";
2569
+ 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";
2566
2570
  import { hostname } from "os";
2567
2571
  import * as path5 from "path";
2568
2572
  import { setTimeout as delay } from "timers/promises";
2569
2573
  var MANAGED_DIRS = ["server", "channels", "codeTemplates", "channelGroups"];
2574
+ async function treeFiles(base) {
2575
+ const out = [];
2576
+ 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("/"));
2580
+ }
2581
+ }
2582
+ return out;
2583
+ }
2570
2584
  var STAGING_DIR = ".channelvault-staging";
2571
2585
  var JOURNAL = ".channelvault-transaction.json";
2572
2586
  var ITEMS = [...MANAGED_DIRS, "channelvault.json", ".gitignore", ".secrets", "env"];
@@ -2755,6 +2769,46 @@ async function replaceTree(root, envFile, prepare) {
2755
2769
  await unlink(path5.join(root, JOURNAL));
2756
2770
  }
2757
2771
 
2772
+ // src/xml/chars.ts
2773
+ var FORBIDDEN = /[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff￾￿]/gu;
2774
+ var hex = (ch) => `U+${ch.codePointAt(0).toString(16).toUpperCase().padStart(4, "0")}`;
2775
+ function positions(text) {
2776
+ const out = [];
2777
+ text.split(/\r\n|\r|\n/).forEach((line, i) => {
2778
+ for (const m of line.matchAll(FORBIDDEN)) {
2779
+ out.push({ line: i + 1, column: [...line.slice(0, m.index)].length + 1, codePoint: hex(m[0]) });
2780
+ }
2781
+ });
2782
+ return out;
2783
+ }
2784
+ function forbiddenXmlChars(config) {
2785
+ const out = [];
2786
+ mapLeaves(config, (value, leaf) => {
2787
+ const owner = leaf.configMapKey !== void 0 ? [`configuration map ${leaf.configMapKey}`] : leaf.labels.length ? leaf.labels : [leaf.location];
2788
+ for (const p of positions(value)) out.push({ where: [...owner, leaf.key].join(" \u203A "), ...p });
2789
+ return value;
2790
+ });
2791
+ return out;
2792
+ }
2793
+ async function forbiddenInFiles(root) {
2794
+ const out = [];
2795
+ 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})`);
2797
+ }
2798
+ return out;
2799
+ }
2800
+ async function xmlSafetyProblem(config, treeRoot) {
2801
+ const found = forbiddenXmlChars(config);
2802
+ if (found.length === 0) return void 0;
2803
+ const files = treeRoot ? await forbiddenInFiles(treeRoot) : [];
2804
+ return [
2805
+ `${found.length} character(s) that XML 1.0 forbids; Mirth would save them and then fail to export its configuration (HTTP 500), breaking every later pull, push and restore:`,
2806
+ ...found.map((f) => ` ${f.where}: line ${f.line}, column ${f.column} of the value (${f.codePoint})`),
2807
+ ...files.length ? ["in the tree:", ...files.map((f) => ` ${f}`)] : [],
2808
+ "escape them in the script, for example \\uFFFE inside a regex or string"
2809
+ ].join("\n");
2810
+ }
2811
+
2758
2812
  // src/cli.ts
2759
2813
  var engine = createExplodeEngine();
2760
2814
  var xml = new XmlConfigAdapter();
@@ -2812,7 +2866,7 @@ function addBackupDirFlags(cmd) {
2812
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})`);
2813
2867
  }
2814
2868
  function backupDirOf(flags) {
2815
- return path6.resolve(flags.backupDir ?? DEFAULT_BACKUP_DIR);
2869
+ return path7.resolve(flags.backupDir ?? DEFAULT_BACKUP_DIR);
2816
2870
  }
2817
2871
  function keepOf(flags) {
2818
2872
  if (flags.keep === void 0) return DEFAULT_KEEP;
@@ -2926,12 +2980,12 @@ async function writeMeta(root, source, config, previous, serverId, resources = r
2926
2980
  resources,
2927
2981
  serverId
2928
2982
  };
2929
- const file = path6.join(root, "channelvault.json");
2983
+ const file = path7.join(root, "channelvault.json");
2930
2984
  if (previous && JSON.stringify({ ...previous, pulledAt: "" }) === JSON.stringify({ ...meta, pulledAt: "" })) meta.pulledAt = previous.pulledAt;
2931
2985
  await writeFile6(file, JSON.stringify(meta, null, 2) + "\n", "utf8");
2932
2986
  }
2933
2987
  function envFilePath(root, flags) {
2934
- return flags.dotenv ? path6.resolve(flags.dotenv) : path6.join(root, ".env");
2988
+ return flags.dotenv ? path7.resolve(flags.dotenv) : path7.join(root, ".env");
2935
2989
  }
2936
2990
  async function loadEnv(file) {
2937
2991
  return { ...await readEnvFile(file), ...process.env };
@@ -2943,7 +2997,7 @@ function addExtractFlag(cmd) {
2943
2997
  return cmd.option("--extract-secrets", "move secrets found inside values (URLs, scripts, headers) to the env file", false);
2944
2998
  }
2945
2999
  async function existingTree(root) {
2946
- return existsSync6(path6.join(root, "server", "configuration.json")) ? engine.implode({ root }) : null;
3000
+ return existsSync6(path7.join(root, "server", "configuration.json")) ? engine.implode({ root }) : null;
2947
3001
  }
2948
3002
  async function renderedTree(root, flags) {
2949
3003
  const tree = await engine.implode({ root });
@@ -2972,7 +3026,7 @@ function scrub(text) {
2972
3026
  }
2973
3027
  var ALLOW_FILE = "channelvault.allow.json";
2974
3028
  async function readAllow(root) {
2975
- const file = path6.join(root, ALLOW_FILE);
3029
+ const file = path7.join(root, ALLOW_FILE);
2976
3030
  if (!existsSync6(file)) return [];
2977
3031
  const parsed = await readJson(file);
2978
3032
  return parsed.ignore ?? [];
@@ -2998,27 +3052,27 @@ Rerun with --extract-secrets to move them to ${envFile}, or list false positives
2998
3052
  const envUpdates = { ...templated.envUpdates, ...scan.envUpdates };
2999
3053
  rememberSecrets(config, { ...env, ...envUpdates });
3000
3054
  const echoes = findEchoes(config, { ...await readEnvFile(envFile), ...envUpdates });
3001
- const rel = path6.relative(root, envFile);
3002
- const envInTree = !rel.startsWith("..") && !path6.isAbsolute(rel);
3055
+ const rel = path7.relative(root, envFile);
3056
+ const envInTree = !rel.startsWith("..") && !path7.isAbsolute(rel);
3003
3057
  let backup = null;
3004
3058
  await replaceTree(root, envFile, async (next) => {
3005
3059
  await engine.explode(config, { root: next });
3006
3060
  await writeMeta(next, source, fetched, previousMeta, serverId);
3007
3061
  if (Object.keys(envUpdates).length > 0) {
3008
- const history = path6.join(root, ".secrets");
3062
+ const history = path7.join(root, ".secrets");
3009
3063
  if (existsSync6(history)) {
3010
3064
  if ((await lstat3(history)).isSymbolicLink()) fail(`refusing a linked secret history directory: ${history}`);
3011
- await cp(history, path6.join(next, ".secrets"), { recursive: true });
3065
+ await cp(history, path7.join(next, ".secrets"), { recursive: true });
3012
3066
  }
3013
- const stagedBackup = await backupEnvFile(envFile, envUpdates, path6.join(next, ".secrets"));
3014
- if (stagedBackup) backup = path6.join(root, ".secrets", path6.basename(stagedBackup));
3067
+ const stagedBackup = await backupEnvFile(envFile, envUpdates, path7.join(next, ".secrets"));
3068
+ if (stagedBackup) backup = path7.join(root, ".secrets", path7.basename(stagedBackup));
3015
3069
  if (backup || envInTree) {
3016
- const ignore = path6.join(root, ".gitignore");
3017
- if (existsSync6(ignore)) await writeFile6(path6.join(next, ".gitignore"), await readFile5(ignore));
3070
+ const ignore = path7.join(root, ".gitignore");
3071
+ if (existsSync6(ignore)) await writeFile6(path7.join(next, ".gitignore"), await readFile6(ignore));
3018
3072
  await ensureEnvIgnored(next, envInTree ? envFile : void 0, root);
3019
3073
  }
3020
- const stagedEnv = path6.join(next, ".env");
3021
- if (existsSync6(envFile)) await writeFile6(stagedEnv, await readFile5(envFile), { mode: 384 });
3074
+ const stagedEnv = path7.join(next, ".env");
3075
+ if (existsSync6(envFile)) await writeFile6(stagedEnv, await readFile6(envFile), { mode: 384 });
3022
3076
  await updateEnvFile(stagedEnv, envUpdates);
3023
3077
  }
3024
3078
  });
@@ -3041,27 +3095,27 @@ Rerun with --extract-secrets to move them to ${envFile}, or list false positives
3041
3095
  }
3042
3096
  }
3043
3097
  function gitWouldCommit(file) {
3044
- const r = spawnSync("git", ["check-ignore", "-q", path6.basename(file)], { cwd: path6.dirname(file) });
3098
+ const r = spawnSync("git", ["check-ignore", "-q", path7.basename(file)], { cwd: path7.dirname(file) });
3045
3099
  return r.status === 1;
3046
3100
  }
3047
3101
  async function resolvedPath(p) {
3048
- const abs = path6.resolve(p);
3102
+ const abs = path7.resolve(p);
3049
3103
  let existing = abs;
3050
- while (!existsSync6(existing) && path6.dirname(existing) !== existing) existing = path6.dirname(existing);
3051
- return path6.join(await realpath4(existing), path6.relative(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));
3052
3106
  }
3053
3107
  function isWithin(child, parent) {
3054
3108
  const norm = (p) => process.platform === "win32" ? p.toLowerCase() : p;
3055
- const rel = path6.relative(norm(parent), norm(child));
3056
- return rel === "" || rel !== ".." && !rel.startsWith(`..${path6.sep}`) && !path6.isAbsolute(rel);
3109
+ const rel = path7.relative(norm(parent), norm(child));
3110
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${path7.sep}`) && !path7.isAbsolute(rel);
3057
3111
  }
3058
3112
  async function preflightTree(root, envFile) {
3059
3113
  const [realRoot, realEnv] = await Promise.all([resolvedPath(root), resolvedPath(envFile)]);
3060
3114
  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))
3115
+ (d) => isWithin(path7.resolve(envFile), path7.resolve(root, d)) || isWithin(realEnv, path7.join(realRoot, d))
3062
3116
  );
3063
3117
  if (doomed) fail(`the env file ${envFile} is inside ${doomed}/, which this command replaces; keep it elsewhere`);
3064
- const metaPath = path6.join(root, "channelvault.json");
3118
+ const metaPath = path7.join(root, "channelvault.json");
3065
3119
  if (existsSync6(metaPath)) {
3066
3120
  let meta;
3067
3121
  try {
@@ -3076,7 +3130,7 @@ async function preflightTree(root, envFile) {
3076
3130
  }
3077
3131
  return meta;
3078
3132
  }
3079
- const foreign = MANAGED_DIRS.filter((d) => existsSync6(path6.join(root, d)));
3133
+ const foreign = MANAGED_DIRS.filter((d) => existsSync6(path7.join(root, d)));
3080
3134
  if (foreign.length > 0) {
3081
3135
  fail(
3082
3136
  `${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).`
@@ -3085,12 +3139,12 @@ async function preflightTree(root, envFile) {
3085
3139
  return null;
3086
3140
  }
3087
3141
  function assertTree(root) {
3088
- if (!existsSync6(path6.join(root, "server", "configuration.json"))) {
3142
+ if (!existsSync6(path7.join(root, "server", "configuration.json"))) {
3089
3143
  fail(`${root} is not a channelvault tree (missing server/configuration.json). Run 'pull' or 'explode' first.`);
3090
3144
  }
3091
3145
  }
3092
3146
  async function readTreeOrigin(root) {
3093
- const metaPath = path6.join(root, "channelvault.json");
3147
+ const metaPath = path7.join(root, "channelvault.json");
3094
3148
  if (!existsSync6(metaPath)) return "unknown";
3095
3149
  try {
3096
3150
  const meta = await readJson(metaPath);
@@ -3119,22 +3173,26 @@ function collect(value, previous) {
3119
3173
  return [...previous ?? [], value];
3120
3174
  }
3121
3175
  async function bindingProblems(root, serverId) {
3122
- const file = path6.join(root, "channelvault.json");
3176
+ const file = path7.join(root, "channelvault.json");
3123
3177
  const meta = existsSync6(file) ? await readJson(file) : null;
3124
3178
  if (meta?.serverId === serverId) return [];
3125
3179
  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
3180
  }
3181
+ async function xmlProblems(root, config) {
3182
+ const problem = await xmlSafetyProblem(config, root);
3183
+ return problem ? [problem] : [];
3184
+ }
3127
3185
  async function assertBinding(client, root) {
3128
3186
  const problems = await bindingProblems(root, await client.getServerId());
3129
3187
  if (problems.length) fail(problems.join("\n"));
3130
3188
  }
3131
3189
  async function readKnown(root) {
3132
- const metaPath = path6.join(root, "channelvault.json");
3190
+ const metaPath = path7.join(root, "channelvault.json");
3133
3191
  if (!existsSync6(metaPath)) return void 0;
3134
3192
  return knownFrom((await readJson(metaPath)).resources);
3135
3193
  }
3136
3194
  async function writeKnown(root, known) {
3137
- const metaPath = path6.join(root, "channelvault.json");
3195
+ const metaPath = path7.join(root, "channelvault.json");
3138
3196
  if (!existsSync6(metaPath)) return;
3139
3197
  const meta = await readJson(metaPath);
3140
3198
  if (!meta.resources) return;
@@ -3199,7 +3257,7 @@ async function scopedPush(client, root, local, scope, target, flags) {
3199
3257
  const remote = await client.getServerConfiguration();
3200
3258
  const known = await readKnown(root);
3201
3259
  const plan = planPush(local, remote, scope, known);
3202
- const problems = [...await bindingProblems(root, await client.getServerId()), ...planProblems(plan, flags)];
3260
+ const problems = [...await bindingProblems(root, await client.getServerId()), ...planProblems(plan, flags), ...await xmlProblems(root, local)];
3203
3261
  const names = new Map(
3204
3262
  [...channelsOf(remote), ...channelsOf(local)].map((c) => [String(c["id"]), String(c["name"])])
3205
3263
  );
@@ -3259,23 +3317,43 @@ pull and try again, or pass --force`);
3259
3317
  }
3260
3318
  await assertBinding(client, root);
3261
3319
  const result = await applyPlan(client, plan, local, afterBackup, scope, { force: flags.force === true });
3320
+ let baselineError;
3321
+ let changedAgain = [];
3322
+ let unverified = [];
3323
+ let after;
3262
3324
  try {
3263
- const after = await client.getServerConfiguration();
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"]) }));
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));
3267
- if (changedAgain.length > 0) fail(`changed again after saving: ${[...new Set(changedAgain.map((c) => c.label))].join(", ")}; pull and review before retrying`);
3268
- if (result.touchedIds.size > 0) await refreshRevisions(root, after, result.touchedIds);
3269
- if (known) await writeKnown(root, knownAfterPush(known, result.applied, result.touchedIds, after));
3325
+ after = await client.getServerConfiguration();
3270
3326
  } catch (err) {
3271
- const message = err instanceof Error ? err.message : String(err);
3272
- if (!result.failed) fail(`applied ${result.applied.length} change(s), but could not refresh the local sync baseline: ${message}; inspect the server before retrying`);
3273
- process.stderr.write(`warning: could not refresh the local sync baseline: ${scrub(message)}
3274
- `);
3327
+ baselineError = `could not read the server configuration back: ${err instanceof Error ? err.message : String(err)}. ${exportBrokenHint(flags)}`;
3328
+ ({ changed: changedAgain, unverified } = await changedAgainSingly(client, result.applied, local));
3275
3329
  }
3330
+ if (after) {
3331
+ try {
3332
+ 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"]) }));
3333
+ const membershipSent = result.sentLibraries ? { ...local, codeTemplateLibraries: { codeTemplateLibrary: result.sentLibraries } } : local;
3334
+ const saved = after;
3335
+ changedAgain = [...new Set([...result.applied, ...refreshedLibraries].filter((c) => !savedChangeMatches(c, c.kind === "library" ? membershipSent : local, saved)).map((c) => c.label))];
3336
+ if (changedAgain.length === 0) {
3337
+ if (result.touchedIds.size > 0) await refreshRevisions(root, after, result.touchedIds);
3338
+ if (known) await writeKnown(root, knownAfterPush(known, result.applied, result.touchedIds, after));
3339
+ }
3340
+ } catch (err) {
3341
+ baselineError = err instanceof Error ? err.message : String(err);
3342
+ }
3343
+ }
3344
+ const notRedeployed = toDeploy.length > 0 ? `
3345
+ ${toDeploy.length} channel(s) NOT redeployed: ${toDeploy.map(nameOf2).join(", ")}; redeploy them from the Administrator once the server is as intended` : "";
3346
+ const againNote = changedAgain.length > 0 ? `
3347
+ changed again after saving (pull and review before retrying): ${changedAgain.join(", ")}` : "";
3276
3348
  if (result.failed) {
3349
+ if (baselineError) process.stderr.write(`warning: could not refresh the local sync baseline: ${scrub(baselineError)}
3350
+ `);
3277
3351
  const { change, error } = result.failed;
3278
- fail(`applied ${result.applied.length} of ${plan.changes.length}; ${change.op} ${change.label} failed: ${error}`);
3352
+ fail(`applied ${result.applied.length} of ${plan.changes.length}; ${change.op} ${change.label} failed: ${error}${againNote}${notRedeployed}`);
3353
+ }
3354
+ if (changedAgain.length > 0) {
3355
+ fail(`applied ${result.applied.length} change(s), but these changed again after saving: ${changedAgain.join(", ")}; pull and review before retrying${notRedeployed}${baselineError ? `
3356
+ ${baselineError}` : ""}`);
3279
3357
  }
3280
3358
  process.stdout.write(`pushed ${result.applied.length} change(s)
3281
3359
  `);
@@ -3289,12 +3367,40 @@ pull and try again, or pass --force`);
3289
3367
  `);
3290
3368
  if (failures.length > 0) process.exitCode = 1;
3291
3369
  }
3370
+ if (baselineError) {
3371
+ const note = unverified.length > 0 ? `
3372
+ not checked after saving (these cannot be read one at a time): ${unverified.join(", ")}` : "";
3373
+ fail(`pushed ${result.applied.length} change(s), but could not refresh the local sync baseline: ${baselineError}${note}`);
3374
+ }
3375
+ }
3376
+ function exportBrokenHint(flags) {
3377
+ const undo = flags.backup === false ? "" : " (including the undo command above)";
3378
+ 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
+ }
3380
+ async function changedAgainSingly(client, applied, local) {
3381
+ const changed = [];
3382
+ const unverified = [];
3383
+ for (const c of applied) {
3384
+ if (c.kind !== "channel" && c.kind !== "codeTemplate") {
3385
+ unverified.push(c.label);
3386
+ continue;
3387
+ }
3388
+ try {
3389
+ const current = c.kind === "channel" ? await client.getChannel(c.id) : await client.getCodeTemplate(c.id);
3390
+ const held = current ? [current] : [];
3391
+ const server = c.kind === "channel" ? { channels: { channel: held } } : { codeTemplateLibraries: { codeTemplateLibrary: [{ codeTemplates: { codeTemplate: held } }] } };
3392
+ if (!savedChangeMatches(c, local, server)) changed.push(c.label);
3393
+ } catch {
3394
+ changed.push(`${c.label} (could not be read)`);
3395
+ }
3396
+ }
3397
+ return { changed, unverified };
3292
3398
  }
3293
3399
  async function wholeServerPush(client, root, local, target, flags) {
3294
3400
  const remote = await client.getServerConfiguration();
3295
3401
  const known = await readKnown(root);
3296
3402
  const plan = planPush(local, remote, {}, known, { wholeReplace: true });
3297
- const problems = [...await bindingProblems(root, await client.getServerId()), ...wholeServerProblems(plan, flags)];
3403
+ const problems = [...await bindingProblems(root, await client.getServerId()), ...wholeServerProblems(plan, flags), ...await xmlProblems(root, local)];
3298
3404
  if (flags.planOnly && flags.json) {
3299
3405
  reportPlanOnly(flags, plan, problems, { target, mode: "whole-server" });
3300
3406
  return;
@@ -3345,7 +3451,12 @@ async function wholeServerPush(client, root, local, target, flags) {
3345
3451
  deploy: flags.deploy === true,
3346
3452
  overwriteConfigMap: flags.overwriteConfigMap === true
3347
3453
  });
3348
- const after = await client.getServerConfiguration();
3454
+ let after;
3455
+ try {
3456
+ after = await client.getServerConfiguration();
3457
+ } catch (err) {
3458
+ fail(`replaced the configuration at ${target}${flags.deploy ? " (Mirth redeploys as part of the replace)" : ""}, but could not read it back: ${err instanceof Error ? err.message : String(err)}. The tree's baseline was not refreshed. ${exportBrokenHint(flags)}`);
3459
+ }
3349
3460
  if (planPush(local, after, {}, void 0, { wholeReplace: true }).changes.length > 0) {
3350
3461
  fail("applied the whole-server replacement, but resources changed again after saving; pull and review before retrying");
3351
3462
  }
@@ -3360,9 +3471,9 @@ program.name("channelvault").description("Git-style pull/push/diff for Mirth Con
3360
3471
  addExtractFlag(addEnvFlag(
3361
3472
  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")
3362
3473
  )).action(async (backupPath, dir, flags) => {
3363
- const config = xml.parse(await readFile5(backupPath, "utf8"));
3364
- const root = path6.resolve(dir);
3365
- await writeTree(root, config, `file:${path6.resolve(backupPath)}`, flags);
3474
+ const config = xml.parse(await readFile6(backupPath, "utf8"));
3475
+ const root = path7.resolve(dir);
3476
+ await writeTree(root, config, `file:${path7.resolve(backupPath)}`, flags);
3366
3477
  const s = summarize(config);
3367
3478
  process.stdout.write(`exploded ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}
3368
3479
  `);
@@ -3370,19 +3481,19 @@ addExtractFlag(addEnvFlag(
3370
3481
  addEnvFlag(
3371
3482
  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)
3372
3483
  ).action(async (dir, outPath, flags) => {
3373
- const root = path6.resolve(dir);
3484
+ const root = path7.resolve(dir);
3374
3485
  assertTree(root);
3375
3486
  const config = await renderedTree(root, flags);
3376
3487
  await assertCompatibleOrigin(root, config, "xml", flags.force === true);
3377
3488
  const xmlStr = xml.build(config);
3378
3489
  await writeFile6(outPath, xmlStr, "utf8");
3379
- process.stdout.write(`imploded ${root} -> ${path6.resolve(outPath)}
3490
+ process.stdout.write(`imploded ${root} -> ${path7.resolve(outPath)}
3380
3491
  `);
3381
3492
  });
3382
3493
  addExtractFlag(addEnvFlag(addConnectionFlags(
3383
3494
  program.command("pull").description("Pull the live server configuration into a working tree").argument("<dir>", "working-tree directory")
3384
3495
  ))).action(async (dir, flags) => {
3385
- const root = path6.resolve(dir);
3496
+ const root = path7.resolve(dir);
3386
3497
  await preflightTree(root, envFilePath(root, flags));
3387
3498
  const { config, serverId } = await withClient(flags, async (client) => {
3388
3499
  const serverId2 = await client.getServerId();
@@ -3399,7 +3510,7 @@ addExtractFlag(addEnvFlag(addConnectionFlags(
3399
3510
  addJsonFlag(addEnvFlag(addConnectionFlags(
3400
3511
  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
3512
  ))).action(async (dir, flags) => {
3402
- const root = path6.resolve(dir);
3513
+ const root = path7.resolve(dir);
3403
3514
  assertTree(root);
3404
3515
  const previous = await preflightTree(root, envFilePath(root, flags));
3405
3516
  const stored = await engine.implode({ root });
@@ -3453,7 +3564,7 @@ addBackupDirFlags(addEnvFlag(addConnectionFlags(
3453
3564
  fail("--whole-server replaces everything; it cannot be combined with --channel, --library or --global-scripts");
3454
3565
  }
3455
3566
  if (flags.overwriteConfigMap && !flags.wholeServer) fail("--overwrite-config-map needs --whole-server");
3456
- const root = path6.resolve(dir);
3567
+ const root = path7.resolve(dir);
3457
3568
  assertTree(root);
3458
3569
  const config = await renderedTree(root, flags);
3459
3570
  await assertCompatibleOrigin(root, config, "live", flags.ignoreOrigin === true);
@@ -3479,10 +3590,10 @@ addBackupDirFlags(addConnectionFlags(
3479
3590
  const file = await withClient(flags, async (client) => {
3480
3591
  const text = await client.getServerConfigurationXml();
3481
3592
  if (!flags.out) return saveServerBackup(client, text, flags);
3482
- const out = path6.resolve(flags.out);
3593
+ const out = path7.resolve(flags.out);
3483
3594
  parseBackup(text, "the server configuration");
3484
3595
  if (existsSync6(out)) fail(`${out} already exists; choose another name`);
3485
- await mkdir5(path6.dirname(out), { recursive: true });
3596
+ await mkdir5(path7.dirname(out), { recursive: true });
3486
3597
  await writePrivate(out, text);
3487
3598
  if (gitWouldCommit(out)) {
3488
3599
  process.stderr.write(`warning: git does not ignore ${out}, which holds credentials in plain text; add it to .gitignore
@@ -3506,7 +3617,7 @@ addBackupDirFlags(addConnectionFlags(
3506
3617
  const serverId = await client.getServerId();
3507
3618
  let chosen;
3508
3619
  if (file) {
3509
- chosen = path6.resolve(file);
3620
+ chosen = path7.resolve(file);
3510
3621
  if (!existsSync6(chosen)) fail(`${chosen} does not exist`);
3511
3622
  } else {
3512
3623
  const mine = await backupsOf(dir, serverId);
@@ -3516,8 +3627,10 @@ addBackupDirFlags(addConnectionFlags(
3516
3627
  }
3517
3628
  chosen = mine[mine.length - 1].file;
3518
3629
  }
3519
- const text = await readFile5(chosen, "utf8");
3630
+ const text = await readFile6(chosen, "utf8");
3520
3631
  const backup = parseBackup(text, chosen);
3632
+ const unsafe = await xmlSafetyProblem(backup);
3633
+ if (unsafe) fail(`${chosen} holds ${unsafe}`);
3521
3634
  const origin = await originOf(dir, chosen);
3522
3635
  if (origin) {
3523
3636
  if (origin.serverId !== serverId && !flags.force) {
@@ -3528,7 +3641,7 @@ addBackupDirFlags(addConnectionFlags(
3528
3641
  if (fromContent !== "" && fromServer !== "" && fromContent !== fromServer && !flags.force) {
3529
3642
  fail(`${chosen} is a backup of ${fromContent}, not ${fromServer}; pass --force to restore it here anyway`);
3530
3643
  }
3531
- process.stderr.write(`warning: ${chosen} is not in ${path6.join(dir, MANIFEST)}, so which server it came from cannot be checked
3644
+ process.stderr.write(`warning: ${chosen} is not in ${path7.join(dir, MANIFEST)}, so which server it came from cannot be checked
3532
3645
  `);
3533
3646
  }
3534
3647
  const [bv, sv] = [backup["@_version"], current["@_version"]];
@@ -3587,14 +3700,15 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
3587
3700
  })
3588
3701
  ))).action(async (dir, flags) => {
3589
3702
  errorExitCode = 2;
3590
- const root = path6.resolve(dir);
3703
+ const root = path7.resolve(dir);
3591
3704
  assertTree(root);
3592
3705
  const fetched = await withClient(flags, (client) => client.getServerConfiguration());
3593
3706
  const tree = await engine.implode({ root });
3594
3707
  const { config: templatedRemote, envUpdates, notes } = templatize(fetched, tree, await loadEnv(envFilePath(root, flags)));
3595
3708
  const messages = [
3596
3709
  ...Object.keys(envUpdates).map((name) => `${name} differs between the server and the env file`),
3597
- ...notes
3710
+ ...notes,
3711
+ ...await xmlProblems(root, tree)
3598
3712
  ];
3599
3713
  const allow = await readAllow(root);
3600
3714
  const staleRevisions = newerOnServer(tree, templatedRemote);
@@ -3609,15 +3723,15 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
3609
3723
  if (serverView.findings.length > 0) messages.push(`${serverView.findings.length} possible secret(s) on the server are redacted below`);
3610
3724
  if (!flags.json) for (const m of messages) process.stderr.write(`note: ${m}
3611
3725
  `);
3612
- const tmp = await mkdtemp(path6.join(tmpdir(), "channelvault-diff-"));
3726
+ const tmp = await mkdtemp(path7.join(tmpdir(), "channelvault-diff-"));
3613
3727
  try {
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"));
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"));
3617
3731
  const chunks = [];
3618
3732
  for (const d of MANAGED_DIRS) {
3619
- const local = existsSync6(path6.join(tmp, "tree", d)) ? `tree/${d}` : ".empty";
3620
- const server = existsSync6(path6.join(tmp, "server", d)) ? `server/${d}` : ".empty";
3733
+ const local = existsSync6(path7.join(tmp, "tree", d)) ? `tree/${d}` : ".empty";
3734
+ const server = existsSync6(path7.join(tmp, "server", d)) ? `server/${d}` : ".empty";
3621
3735
  if (local === ".empty" && server === ".empty") continue;
3622
3736
  const result = spawnSync(
3623
3737
  "git",
@@ -3639,7 +3753,7 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
3639
3753
  const clean = out === "" && secretDrift.length === 0;
3640
3754
  if (!clean) process.exitCode = 1;
3641
3755
  if (flags.json) {
3642
- const files = await changedFiles(path6.join(tmp, "tree"), path6.join(tmp, "server"));
3756
+ const files = await changedFiles(path7.join(tmp, "tree"), path7.join(tmp, "server"));
3643
3757
  writeJson2({ clean, files, secretDrift, staleRevisions, notes: messages, patch: out });
3644
3758
  } else if (clean) {
3645
3759
  process.stdout.write("no differences \u2014 working tree matches the server.\n");
@@ -3655,22 +3769,12 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
3655
3769
  }
3656
3770
  });
3657
3771
  async function changedFiles(treeDir, serverDir) {
3658
- const list2 = async (base) => {
3659
- const out = [];
3660
- for (const d of MANAGED_DIRS) {
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("/"));
3664
- }
3665
- }
3666
- return out;
3667
- };
3668
- const [local, remote] = await Promise.all([list2(treeDir), list2(serverDir)]);
3772
+ const [local, remote] = await Promise.all([treeFiles(treeDir), treeFiles(serverDir)]);
3669
3773
  const remoteSet = new Set(remote);
3670
3774
  const files = [];
3671
3775
  for (const p of local) {
3672
3776
  if (!remoteSet.has(p)) files.push({ path: p, change: "only-in-tree" });
3673
- else if (await readFile5(path6.join(treeDir, p), "utf8") !== await readFile5(path6.join(serverDir, p), "utf8")) files.push({ path: p, change: "modified" });
3777
+ else if (await readFile6(path7.join(treeDir, p), "utf8") !== await readFile6(path7.join(serverDir, p), "utf8")) files.push({ path: p, change: "modified" });
3674
3778
  }
3675
3779
  const localSet = new Set(local);
3676
3780
  for (const p of remote) if (!localSet.has(p)) files.push({ path: p, change: "only-on-server" });
@@ -3679,16 +3783,25 @@ async function changedFiles(treeDir, serverDir) {
3679
3783
  addJsonFlag(addEnvFlag(
3680
3784
  program.command("status").description("Summarize a working tree").argument("<dir>", "working-tree directory")
3681
3785
  )).action(async (dir, flags) => {
3682
- const root = path6.resolve(dir);
3786
+ const root = path7.resolve(dir);
3683
3787
  assertTree(root);
3684
3788
  const config = await engine.implode({ root });
3685
3789
  const s = summarize(config);
3686
- const metaPath = path6.join(root, "channelvault.json");
3790
+ const metaPath = path7.join(root, "channelvault.json");
3687
3791
  const meta = existsSync6(metaPath) ? await readJson(metaPath) : null;
3688
3792
  if (flags.json) {
3689
- writeJson2({ root, source: meta?.source ?? null, pulledAt: meta?.pulledAt ?? null, engineVersion: meta?.engineVersion ?? null, counts: s });
3793
+ writeJson2({
3794
+ root,
3795
+ source: meta?.source ?? null,
3796
+ pulledAt: meta?.pulledAt ?? null,
3797
+ engineVersion: meta?.engineVersion ?? null,
3798
+ counts: s,
3799
+ xmlForbiddenChars: forbiddenXmlChars(config)
3800
+ });
3690
3801
  return;
3691
3802
  }
3803
+ for (const p of await xmlProblems(root, config)) process.stderr.write(`warning: ${p}
3804
+ `);
3692
3805
  if (meta) {
3693
3806
  process.stdout.write(`source: ${meta.source}
3694
3807
  `);
@@ -3710,7 +3823,7 @@ program.hook("preAction", async (_program, command) => {
3710
3823
  const name = command.name();
3711
3824
  if (!["explode", "pull", "adopt", "push", "implode", "diff", "status"].includes(name)) return;
3712
3825
  if (name === "diff") errorExitCode = 2;
3713
- const root = path6.resolve(String(command.processedArgs[name === "explode" ? 1 : 0]));
3826
+ const root = path7.resolve(String(command.processedArgs[name === "explode" ? 1 : 0]));
3714
3827
  unlock = await lockTree(root);
3715
3828
  await recoverTree(root, envFilePath(root, command.opts()));
3716
3829
  });