@ubercode/channelvault 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/LICENSE +21 -0
- package/README.md +175 -0
- package/dist/cli.js +3083 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +170 -0
- package/dist/index.js +1368 -0
- package/dist/index.js.map +1 -0
- package/docs/roadmap.md +142 -0
- package/package.json +80 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,3083 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { spawnSync } from "child_process";
|
|
5
|
+
import { mkdir as mkdir4, mkdtemp, readFile as readFile5, realpath as realpath3, rename as rename3, rm as rm3, writeFile as writeFile5 } from "fs/promises";
|
|
6
|
+
import { existsSync as existsSync5 } from "fs";
|
|
7
|
+
import { tmpdir } from "os";
|
|
8
|
+
import { createRequire } from "module";
|
|
9
|
+
import * as path5 from "path";
|
|
10
|
+
import { createInterface } from "readline/promises";
|
|
11
|
+
import { Command, CommanderError } from "commander";
|
|
12
|
+
|
|
13
|
+
// src/explode/index.ts
|
|
14
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
15
|
+
import { existsSync } from "fs";
|
|
16
|
+
import { lstat, mkdir, readFile as readFile2, realpath, writeFile } from "fs/promises";
|
|
17
|
+
import * as path from "path";
|
|
18
|
+
|
|
19
|
+
// src/types.ts
|
|
20
|
+
function isFileRef(v) {
|
|
21
|
+
return typeof v === "object" && v !== null && !Array.isArray(v) && Object.keys(v).length === 1 && typeof v["@file"] === "string";
|
|
22
|
+
}
|
|
23
|
+
var CODE_KEYS = ["script", "code"];
|
|
24
|
+
var CHANNEL_SCRIPT_KEYS = [
|
|
25
|
+
"preprocessingScript",
|
|
26
|
+
"postprocessingScript",
|
|
27
|
+
"deployScript",
|
|
28
|
+
"undeployScript"
|
|
29
|
+
];
|
|
30
|
+
|
|
31
|
+
// src/json.ts
|
|
32
|
+
import { readFile } from "fs/promises";
|
|
33
|
+
function parseJson(text, file) {
|
|
34
|
+
try {
|
|
35
|
+
return JSON.parse(text);
|
|
36
|
+
} catch (err) {
|
|
37
|
+
throw new Error(`${file}: ${err instanceof Error ? err.message : String(err)}`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
async function readJson(file) {
|
|
41
|
+
return parseJson(await readFile(file, "utf8"), file);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// src/explode/index.ts
|
|
45
|
+
function asArray(x) {
|
|
46
|
+
return Array.isArray(x) ? x : x == null ? [] : [x];
|
|
47
|
+
}
|
|
48
|
+
function isRefMarker(v) {
|
|
49
|
+
return typeof v === "object" && v !== null && !Array.isArray(v) && Object.keys(v).length === 1 && typeof v["@ref"] === "string";
|
|
50
|
+
}
|
|
51
|
+
var CODE_KEY_SET = /* @__PURE__ */ new Set([...CODE_KEYS, ...CHANNEL_SCRIPT_KEYS]);
|
|
52
|
+
var CHANNEL_SCRIPT_FRIENDLY = {
|
|
53
|
+
preprocessingScript: "preprocessor",
|
|
54
|
+
postprocessingScript: "postprocessor",
|
|
55
|
+
deployScript: "deploy",
|
|
56
|
+
undeployScript: "undeploy"
|
|
57
|
+
};
|
|
58
|
+
function isPlainObject(v) {
|
|
59
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
60
|
+
}
|
|
61
|
+
function deepClone(v) {
|
|
62
|
+
return structuredClone(v);
|
|
63
|
+
}
|
|
64
|
+
function slug(name) {
|
|
65
|
+
let s = typeof name === "string" ? name : name == null ? "" : String(name);
|
|
66
|
+
s = s.replace(/[/\\:*?"<>|]/g, " ");
|
|
67
|
+
s = s.replace(/[\x00-\x1f\x7f]/g, " ");
|
|
68
|
+
s = s.replace(/\s+/g, "-");
|
|
69
|
+
s = s.replace(/^[-.]+|[-.]+$/g, "");
|
|
70
|
+
if (s.length === 0) return "unnamed";
|
|
71
|
+
return /^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i.test(s) ? `${s}-` : s;
|
|
72
|
+
}
|
|
73
|
+
function uniqueSlug(base, used) {
|
|
74
|
+
let candidate = base;
|
|
75
|
+
for (let n = 2; used.has(candidate.toLowerCase()); n += 1) candidate = `${base}-${n}`;
|
|
76
|
+
used.add(candidate.toLowerCase());
|
|
77
|
+
return candidate;
|
|
78
|
+
}
|
|
79
|
+
function relPosix(fromDir, toFile) {
|
|
80
|
+
return path.relative(fromDir, toFile).split(path.sep).join("/");
|
|
81
|
+
}
|
|
82
|
+
var explodeRoot = new AsyncLocalStorage();
|
|
83
|
+
async function assertInsideTree(filePath) {
|
|
84
|
+
const root = explodeRoot.getStore();
|
|
85
|
+
if (root === void 0) return;
|
|
86
|
+
let dir = path.dirname(filePath);
|
|
87
|
+
while (!existsSync(dir) && path.dirname(dir) !== dir) dir = path.dirname(dir);
|
|
88
|
+
const real = await realpath(dir);
|
|
89
|
+
if (real !== root && !real.startsWith(root + path.sep)) {
|
|
90
|
+
throw new Error(`refusing to write outside the working tree: ${filePath}`);
|
|
91
|
+
}
|
|
92
|
+
const existing = await lstat(filePath).catch((err) => {
|
|
93
|
+
if (err.code !== "ENOENT") throw err;
|
|
94
|
+
return void 0;
|
|
95
|
+
});
|
|
96
|
+
if (existing?.isSymbolicLink()) throw new Error(`refusing to write through a file link: ${filePath}`);
|
|
97
|
+
}
|
|
98
|
+
async function writeFileMkdir(filePath, data) {
|
|
99
|
+
await assertInsideTree(filePath);
|
|
100
|
+
await mkdir(path.dirname(filePath), { recursive: true });
|
|
101
|
+
await writeFile(filePath, data);
|
|
102
|
+
}
|
|
103
|
+
async function writeJson(filePath, value) {
|
|
104
|
+
await assertInsideTree(filePath);
|
|
105
|
+
await mkdir(path.dirname(filePath), { recursive: true });
|
|
106
|
+
await writeFile(filePath, JSON.stringify(value, null, 2));
|
|
107
|
+
}
|
|
108
|
+
async function extractCode(value, ctx) {
|
|
109
|
+
if (Array.isArray(value)) {
|
|
110
|
+
const out = [];
|
|
111
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
112
|
+
out.push(
|
|
113
|
+
await extractCode(value[i], {
|
|
114
|
+
...ctx,
|
|
115
|
+
friendly: null,
|
|
116
|
+
prefixParts: [...ctx.prefixParts, String(i)]
|
|
117
|
+
})
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
if (!isPlainObject(value)) {
|
|
123
|
+
return value;
|
|
124
|
+
}
|
|
125
|
+
return extractFromObject(value, ctx);
|
|
126
|
+
}
|
|
127
|
+
async function extractFromObject(obj, ctx) {
|
|
128
|
+
const out = {};
|
|
129
|
+
for (const [key, raw] of Object.entries(obj)) {
|
|
130
|
+
if (CODE_KEY_SET.has(key) && typeof raw === "string") {
|
|
131
|
+
if (raw.trim().length === 0) {
|
|
132
|
+
out[key] = raw;
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
const friendlyBase = key in CHANNEL_SCRIPT_FRIENDLY ? `scripts/${CHANNEL_SCRIPT_FRIENDLY[key]}` : (
|
|
136
|
+
// One filename segment: config keys are untrusted and may hold '/' or '..'.
|
|
137
|
+
ctx.friendly ?? `_code/${slug([...ctx.prefixParts, key].join("."))}`
|
|
138
|
+
);
|
|
139
|
+
const filePath = resolveUnique(ctx.codeDir, `${friendlyBase}.js`, ctx.usedPaths);
|
|
140
|
+
await writeFileMkdir(filePath, raw);
|
|
141
|
+
out[key] = { "@file": relPosix(ctx.jsonDir, filePath) };
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
out[key] = await extractCode(raw, {
|
|
145
|
+
...ctx,
|
|
146
|
+
friendly: null,
|
|
147
|
+
prefixParts: [...ctx.prefixParts, key]
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
return out;
|
|
151
|
+
}
|
|
152
|
+
function resolveUnique(baseDir, relName, used) {
|
|
153
|
+
const ext = path.extname(relName);
|
|
154
|
+
const dir = path.dirname(relName);
|
|
155
|
+
const stem = path.basename(relName, ext);
|
|
156
|
+
const dirSlug = dir === "." ? "" : dir;
|
|
157
|
+
const segs = dirSlug.split("/").filter(Boolean);
|
|
158
|
+
let rel = [...segs, `${stem}${ext}`].join("/");
|
|
159
|
+
for (let n = 2; used.has(rel.toLowerCase()); n += 1) rel = [...segs, `${stem}-${n}${ext}`].join("/");
|
|
160
|
+
used.add(rel.toLowerCase());
|
|
161
|
+
const full = path.resolve(baseDir, ...rel.split("/"));
|
|
162
|
+
if (!full.startsWith(path.resolve(baseDir) + path.sep)) throw new Error(`script path escapes its directory: ${relName}`);
|
|
163
|
+
return full;
|
|
164
|
+
}
|
|
165
|
+
async function explodeChannelTree(channel, dir, usedPaths) {
|
|
166
|
+
const out = {};
|
|
167
|
+
for (const [key, raw] of Object.entries(channel)) {
|
|
168
|
+
if (key in CHANNEL_SCRIPT_FRIENDLY && typeof raw === "string") {
|
|
169
|
+
if (raw.trim().length === 0) {
|
|
170
|
+
out[key] = raw;
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
const filePath = resolveUnique(dir, `scripts/${CHANNEL_SCRIPT_FRIENDLY[key]}.js`, usedPaths);
|
|
174
|
+
await writeFileMkdir(filePath, raw);
|
|
175
|
+
out[key] = { "@file": relPosix(dir, filePath) };
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
if (key === "sourceConnector" && isPlainObject(raw)) {
|
|
179
|
+
out[key] = await explodeConnector(raw, dir, "source", "source/receiver", usedPaths);
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
if (key === "destinationConnectors" && isPlainObject(raw)) {
|
|
183
|
+
out[key] = await explodeDestinationConnectors(raw, dir, usedPaths);
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
out[key] = await extractCode(raw, {
|
|
187
|
+
jsonDir: dir,
|
|
188
|
+
codeDir: dir,
|
|
189
|
+
friendly: null,
|
|
190
|
+
prefixParts: [key],
|
|
191
|
+
usedPaths
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
return out;
|
|
195
|
+
}
|
|
196
|
+
async function explodeConnector(connector, channelDir, baseRel, scriptFileBase, usedPaths) {
|
|
197
|
+
const out = {};
|
|
198
|
+
for (const [key, raw] of Object.entries(connector)) {
|
|
199
|
+
if (key === "transformer" && isPlainObject(raw)) {
|
|
200
|
+
out[key] = await explodeStepContainer(raw, channelDir, `${baseRel}/transformer`, usedPaths);
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
if (key === "responseTransformer" && isPlainObject(raw)) {
|
|
204
|
+
out[key] = await explodeStepContainer(
|
|
205
|
+
raw,
|
|
206
|
+
channelDir,
|
|
207
|
+
`${baseRel}/responseTransformer`,
|
|
208
|
+
usedPaths
|
|
209
|
+
);
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
if (key === "filter" && isPlainObject(raw)) {
|
|
213
|
+
out[key] = await explodeStepContainer(raw, channelDir, `${baseRel}/filter`, usedPaths);
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
if (key === "properties" && isPlainObject(raw)) {
|
|
217
|
+
out[key] = await explodeConnectorProperties(raw, channelDir, scriptFileBase, usedPaths);
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
out[key] = await extractCode(raw, {
|
|
221
|
+
jsonDir: channelDir,
|
|
222
|
+
codeDir: channelDir,
|
|
223
|
+
friendly: null,
|
|
224
|
+
prefixParts: [baseRel, key],
|
|
225
|
+
usedPaths
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
return out;
|
|
229
|
+
}
|
|
230
|
+
async function explodeConnectorProperties(properties, channelDir, scriptFileBase, usedPaths) {
|
|
231
|
+
const out = {};
|
|
232
|
+
for (const [key, raw] of Object.entries(properties)) {
|
|
233
|
+
if (key === "script" && typeof raw === "string") {
|
|
234
|
+
if (raw.trim().length === 0) {
|
|
235
|
+
out[key] = raw;
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
const filePath = resolveUnique(channelDir, `${scriptFileBase}.js`, usedPaths);
|
|
239
|
+
await writeFileMkdir(filePath, raw);
|
|
240
|
+
out[key] = { "@file": relPosix(channelDir, filePath) };
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
out[key] = await extractCode(raw, {
|
|
244
|
+
jsonDir: channelDir,
|
|
245
|
+
codeDir: channelDir,
|
|
246
|
+
friendly: null,
|
|
247
|
+
prefixParts: ["properties", key],
|
|
248
|
+
usedPaths
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
return out;
|
|
252
|
+
}
|
|
253
|
+
async function explodeDestinationConnectors(container, channelDir, usedPaths) {
|
|
254
|
+
const out = {};
|
|
255
|
+
const usedDestSlugs = /* @__PURE__ */ new Set();
|
|
256
|
+
for (const [key, raw] of Object.entries(container)) {
|
|
257
|
+
if (key === "connector") {
|
|
258
|
+
const connectors = asArray(raw);
|
|
259
|
+
const wasArray = Array.isArray(raw);
|
|
260
|
+
const transformed = [];
|
|
261
|
+
for (const conn of connectors) {
|
|
262
|
+
const name = isPlainObject(conn) ? conn["name"] : void 0;
|
|
263
|
+
const destSlug = uniqueSlug(slug(name), usedDestSlugs);
|
|
264
|
+
transformed.push(
|
|
265
|
+
isPlainObject(conn) ? await explodeConnector(
|
|
266
|
+
conn,
|
|
267
|
+
channelDir,
|
|
268
|
+
`destinations/${destSlug}`,
|
|
269
|
+
`destinations/${destSlug}/writer`,
|
|
270
|
+
usedPaths
|
|
271
|
+
) : conn
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
out[key] = wasArray ? transformed : transformed[0];
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
out[key] = await extractCode(raw, {
|
|
278
|
+
jsonDir: channelDir,
|
|
279
|
+
codeDir: channelDir,
|
|
280
|
+
friendly: null,
|
|
281
|
+
prefixParts: ["destinationConnectors", key],
|
|
282
|
+
usedPaths
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
return out;
|
|
286
|
+
}
|
|
287
|
+
async function explodeStepContainer(container, channelDir, baseRel, usedPaths) {
|
|
288
|
+
const out = {};
|
|
289
|
+
for (const [key, raw] of Object.entries(container)) {
|
|
290
|
+
if (key === "elements" && (Array.isArray(raw) || isPlainObject(raw))) {
|
|
291
|
+
out[key] = await explodeElementsContainer(
|
|
292
|
+
raw,
|
|
293
|
+
channelDir,
|
|
294
|
+
baseRel,
|
|
295
|
+
usedPaths
|
|
296
|
+
);
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
299
|
+
out[key] = await extractCode(raw, {
|
|
300
|
+
jsonDir: channelDir,
|
|
301
|
+
codeDir: channelDir,
|
|
302
|
+
friendly: null,
|
|
303
|
+
prefixParts: [baseRel, key],
|
|
304
|
+
usedPaths
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
return out;
|
|
308
|
+
}
|
|
309
|
+
function isStepLike(obj) {
|
|
310
|
+
return typeof obj["script"] === "string" || typeof obj["code"] === "string" || "sequenceNumber" in obj || "name" in obj;
|
|
311
|
+
}
|
|
312
|
+
async function explodeElementsContainer(elements, channelDir, baseRel, usedPaths) {
|
|
313
|
+
const counter = { i: 0 };
|
|
314
|
+
if (Array.isArray(elements)) {
|
|
315
|
+
return explodeStepArray(elements, channelDir, baseRel, usedPaths, counter);
|
|
316
|
+
}
|
|
317
|
+
if (isStepLike(elements)) {
|
|
318
|
+
return explodeStep(elements, channelDir, baseRel, counter.i++, usedPaths);
|
|
319
|
+
}
|
|
320
|
+
const out = {};
|
|
321
|
+
for (const [className, raw] of Object.entries(elements)) {
|
|
322
|
+
if (className.startsWith("@_") || className.startsWith("#") || raw == null) {
|
|
323
|
+
out[className] = await extractCode(raw, {
|
|
324
|
+
jsonDir: channelDir,
|
|
325
|
+
codeDir: channelDir,
|
|
326
|
+
friendly: null,
|
|
327
|
+
prefixParts: [baseRel, "elements", className],
|
|
328
|
+
usedPaths
|
|
329
|
+
});
|
|
330
|
+
continue;
|
|
331
|
+
}
|
|
332
|
+
if (Array.isArray(raw)) {
|
|
333
|
+
out[className] = await explodeStepArray(raw, channelDir, baseRel, usedPaths, counter);
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
if (isPlainObject(raw) && isStepLike(raw)) {
|
|
337
|
+
out[className] = await explodeStep(raw, channelDir, baseRel, counter.i++, usedPaths);
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
out[className] = await extractCode(raw, {
|
|
341
|
+
jsonDir: channelDir,
|
|
342
|
+
codeDir: channelDir,
|
|
343
|
+
friendly: null,
|
|
344
|
+
prefixParts: [baseRel, "elements", className],
|
|
345
|
+
usedPaths
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
return out;
|
|
349
|
+
}
|
|
350
|
+
async function explodeStepArray(steps, channelDir, baseRel, usedPaths, counter) {
|
|
351
|
+
const transformed = [];
|
|
352
|
+
for (const step of steps) {
|
|
353
|
+
transformed.push(await explodeStep(step, channelDir, baseRel, counter.i++, usedPaths));
|
|
354
|
+
}
|
|
355
|
+
return transformed;
|
|
356
|
+
}
|
|
357
|
+
async function explodeStep(step, channelDir, baseRel, index, usedPaths) {
|
|
358
|
+
if (!isPlainObject(step)) {
|
|
359
|
+
return step;
|
|
360
|
+
}
|
|
361
|
+
const seqRaw = step["sequenceNumber"];
|
|
362
|
+
let seq = index;
|
|
363
|
+
if (typeof seqRaw === "number") seq = seqRaw;
|
|
364
|
+
else if (typeof seqRaw === "string" && seqRaw.trim() !== "" && !Number.isNaN(Number(seqRaw))) {
|
|
365
|
+
seq = Number(seqRaw);
|
|
366
|
+
}
|
|
367
|
+
const n = seq + 1;
|
|
368
|
+
const stepName = step["name"];
|
|
369
|
+
const hasName = typeof stepName === "string" && stepName.trim().length > 0;
|
|
370
|
+
const friendlyBase = hasName ? `${baseRel}/${n}.${slug(stepName)}` : `${baseRel}/${n}`;
|
|
371
|
+
const out = {};
|
|
372
|
+
for (const [key, raw] of Object.entries(step)) {
|
|
373
|
+
if (CODE_KEY_SET.has(key) && typeof raw === "string") {
|
|
374
|
+
if (raw.trim().length === 0) {
|
|
375
|
+
out[key] = raw;
|
|
376
|
+
continue;
|
|
377
|
+
}
|
|
378
|
+
const filePath = resolveUnique(channelDir, `${friendlyBase}.js`, usedPaths);
|
|
379
|
+
await writeFileMkdir(filePath, raw);
|
|
380
|
+
out[key] = { "@file": relPosix(channelDir, filePath) };
|
|
381
|
+
continue;
|
|
382
|
+
}
|
|
383
|
+
out[key] = await extractCode(raw, {
|
|
384
|
+
jsonDir: channelDir,
|
|
385
|
+
codeDir: channelDir,
|
|
386
|
+
friendly: null,
|
|
387
|
+
prefixParts: [baseRel, String(index), key],
|
|
388
|
+
usedPaths
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
return out;
|
|
392
|
+
}
|
|
393
|
+
async function splitCollection(parent, containerKey, elementKey, root, serverDir, targetFor, usedSlugs, explodeResource) {
|
|
394
|
+
const container = parent[containerKey];
|
|
395
|
+
if (!isPlainObject(container)) return;
|
|
396
|
+
const raw = container[elementKey];
|
|
397
|
+
if (raw == null) return;
|
|
398
|
+
const wasArray = Array.isArray(raw);
|
|
399
|
+
const elements = asArray(raw);
|
|
400
|
+
const refs = [];
|
|
401
|
+
for (const el of elements) {
|
|
402
|
+
if (!isPlainObject(el)) {
|
|
403
|
+
refs.push(el);
|
|
404
|
+
continue;
|
|
405
|
+
}
|
|
406
|
+
const slugName = uniqueSlug(slug(el["name"]), usedSlugs);
|
|
407
|
+
const { jsonFile, resourceDir } = targetFor(el["name"], slugName);
|
|
408
|
+
const transformed = await explodeResource(el, resourceDir);
|
|
409
|
+
await writeJson(jsonFile, transformed);
|
|
410
|
+
refs.push({ "@ref": relPosix(serverDir, jsonFile) });
|
|
411
|
+
}
|
|
412
|
+
container[elementKey] = wasArray ? refs : refs[0];
|
|
413
|
+
}
|
|
414
|
+
async function explode(config, opts) {
|
|
415
|
+
await mkdir(opts.root, { recursive: true });
|
|
416
|
+
await explodeRoot.run(await realpath(opts.root), () => explodeInto(config, opts));
|
|
417
|
+
}
|
|
418
|
+
async function explodeInto(config, opts) {
|
|
419
|
+
const root = opts.root;
|
|
420
|
+
const serverDir = path.join(root, "server");
|
|
421
|
+
const skeleton = deepClone(config);
|
|
422
|
+
if (isPlainObject(skeleton["channels"])) {
|
|
423
|
+
const channelSlugs = /* @__PURE__ */ new Set();
|
|
424
|
+
await splitCollection(
|
|
425
|
+
skeleton,
|
|
426
|
+
"channels",
|
|
427
|
+
"channel",
|
|
428
|
+
root,
|
|
429
|
+
serverDir,
|
|
430
|
+
(_name, slugName) => {
|
|
431
|
+
const resourceDir = path.join(root, "channels", slugName);
|
|
432
|
+
return { jsonFile: path.join(resourceDir, "channel.json"), resourceDir };
|
|
433
|
+
},
|
|
434
|
+
channelSlugs,
|
|
435
|
+
async (el, resourceDir) => explodeChannelTree(el, resourceDir, /* @__PURE__ */ new Set())
|
|
436
|
+
);
|
|
437
|
+
}
|
|
438
|
+
if (isPlainObject(skeleton["codeTemplateLibraries"])) {
|
|
439
|
+
const libSlugs = /* @__PURE__ */ new Set();
|
|
440
|
+
await splitCollection(
|
|
441
|
+
skeleton,
|
|
442
|
+
"codeTemplateLibraries",
|
|
443
|
+
"codeTemplateLibrary",
|
|
444
|
+
root,
|
|
445
|
+
serverDir,
|
|
446
|
+
(_name, slugName) => {
|
|
447
|
+
const resourceDir = path.join(root, "codeTemplates", slugName);
|
|
448
|
+
return { jsonFile: path.join(resourceDir, "library.json"), resourceDir };
|
|
449
|
+
},
|
|
450
|
+
libSlugs,
|
|
451
|
+
async (el, resourceDir) => explodeLibrary(el, resourceDir)
|
|
452
|
+
);
|
|
453
|
+
}
|
|
454
|
+
if (isPlainObject(skeleton["channelGroups"])) {
|
|
455
|
+
const groupSlugs = /* @__PURE__ */ new Set();
|
|
456
|
+
await splitCollection(
|
|
457
|
+
skeleton,
|
|
458
|
+
"channelGroups",
|
|
459
|
+
"channelGroup",
|
|
460
|
+
root,
|
|
461
|
+
serverDir,
|
|
462
|
+
(_name, slugName) => {
|
|
463
|
+
const resourceDir = path.join(root, "channelGroups");
|
|
464
|
+
return { jsonFile: path.join(resourceDir, `${slugName}.json`), resourceDir };
|
|
465
|
+
},
|
|
466
|
+
groupSlugs,
|
|
467
|
+
async (el, resourceDir) => (
|
|
468
|
+
// group json lives in channelGroups/; sidecar code (rare) under same dir
|
|
469
|
+
extractCode(el, {
|
|
470
|
+
jsonDir: resourceDir,
|
|
471
|
+
codeDir: resourceDir,
|
|
472
|
+
friendly: null,
|
|
473
|
+
prefixParts: ["channelGroup"],
|
|
474
|
+
usedPaths: /* @__PURE__ */ new Set()
|
|
475
|
+
})
|
|
476
|
+
)
|
|
477
|
+
);
|
|
478
|
+
}
|
|
479
|
+
const finalSkeleton = await extractCode(skeleton, {
|
|
480
|
+
jsonDir: serverDir,
|
|
481
|
+
codeDir: serverDir,
|
|
482
|
+
friendly: null,
|
|
483
|
+
prefixParts: [],
|
|
484
|
+
usedPaths: /* @__PURE__ */ new Set()
|
|
485
|
+
});
|
|
486
|
+
await writeJson(path.join(serverDir, "configuration.json"), finalSkeleton);
|
|
487
|
+
}
|
|
488
|
+
async function explodeLibrary(library, resourceDir) {
|
|
489
|
+
const used = /* @__PURE__ */ new Set();
|
|
490
|
+
const usedTemplateSlugs = /* @__PURE__ */ new Set();
|
|
491
|
+
const out = {};
|
|
492
|
+
for (const [key, raw] of Object.entries(library)) {
|
|
493
|
+
if (key === "codeTemplates" && isPlainObject(raw)) {
|
|
494
|
+
out[key] = await explodeLibraryTemplates(raw, resourceDir, usedTemplateSlugs, used);
|
|
495
|
+
continue;
|
|
496
|
+
}
|
|
497
|
+
out[key] = await extractCode(raw, {
|
|
498
|
+
jsonDir: resourceDir,
|
|
499
|
+
codeDir: resourceDir,
|
|
500
|
+
friendly: null,
|
|
501
|
+
prefixParts: [key],
|
|
502
|
+
usedPaths: used
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
return out;
|
|
506
|
+
}
|
|
507
|
+
async function explodeLibraryTemplates(container, resourceDir, usedTemplateSlugs, usedPaths) {
|
|
508
|
+
const out = {};
|
|
509
|
+
for (const [key, raw] of Object.entries(container)) {
|
|
510
|
+
if (key === "codeTemplate" && raw != null) {
|
|
511
|
+
const wasArray = Array.isArray(raw);
|
|
512
|
+
const templates = asArray(raw);
|
|
513
|
+
const transformed = [];
|
|
514
|
+
for (const t of templates) {
|
|
515
|
+
transformed.push(
|
|
516
|
+
await explodeCodeTemplate(t, resourceDir, usedTemplateSlugs, usedPaths)
|
|
517
|
+
);
|
|
518
|
+
}
|
|
519
|
+
out[key] = wasArray ? transformed : transformed[0];
|
|
520
|
+
continue;
|
|
521
|
+
}
|
|
522
|
+
out[key] = await extractCode(raw, {
|
|
523
|
+
jsonDir: resourceDir,
|
|
524
|
+
codeDir: resourceDir,
|
|
525
|
+
friendly: null,
|
|
526
|
+
prefixParts: ["codeTemplates", key],
|
|
527
|
+
usedPaths
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
return out;
|
|
531
|
+
}
|
|
532
|
+
async function explodeCodeTemplate(template, resourceDir, usedTemplateSlugs, usedPaths) {
|
|
533
|
+
if (!isPlainObject(template)) return template;
|
|
534
|
+
const friendlyBase = uniqueSlug(slug(template["name"]), usedTemplateSlugs);
|
|
535
|
+
const out = {};
|
|
536
|
+
for (const [key, raw] of Object.entries(template)) {
|
|
537
|
+
if (key === "properties" && isPlainObject(raw)) {
|
|
538
|
+
out[key] = await explodeTemplateProperties(raw, resourceDir, friendlyBase, usedPaths);
|
|
539
|
+
continue;
|
|
540
|
+
}
|
|
541
|
+
if (CODE_KEY_SET.has(key) && typeof raw === "string") {
|
|
542
|
+
if (raw.trim().length === 0) {
|
|
543
|
+
out[key] = raw;
|
|
544
|
+
continue;
|
|
545
|
+
}
|
|
546
|
+
const filePath = resolveUnique(resourceDir, `${friendlyBase}.js`, usedPaths);
|
|
547
|
+
await writeFileMkdir(filePath, raw);
|
|
548
|
+
out[key] = { "@file": relPosix(resourceDir, filePath) };
|
|
549
|
+
continue;
|
|
550
|
+
}
|
|
551
|
+
out[key] = await extractCode(raw, {
|
|
552
|
+
jsonDir: resourceDir,
|
|
553
|
+
codeDir: resourceDir,
|
|
554
|
+
friendly: null,
|
|
555
|
+
prefixParts: ["codeTemplate", key],
|
|
556
|
+
usedPaths
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
return out;
|
|
560
|
+
}
|
|
561
|
+
async function explodeTemplateProperties(properties, resourceDir, friendlyBase, usedPaths) {
|
|
562
|
+
const out = {};
|
|
563
|
+
for (const [key, raw] of Object.entries(properties)) {
|
|
564
|
+
if (CODE_KEY_SET.has(key) && typeof raw === "string") {
|
|
565
|
+
if (raw.trim().length === 0) {
|
|
566
|
+
out[key] = raw;
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
const filePath = resolveUnique(resourceDir, `${friendlyBase}.js`, usedPaths);
|
|
570
|
+
await writeFileMkdir(filePath, raw);
|
|
571
|
+
out[key] = { "@file": relPosix(resourceDir, filePath) };
|
|
572
|
+
continue;
|
|
573
|
+
}
|
|
574
|
+
out[key] = await extractCode(raw, {
|
|
575
|
+
jsonDir: resourceDir,
|
|
576
|
+
codeDir: resourceDir,
|
|
577
|
+
friendly: null,
|
|
578
|
+
prefixParts: ["codeTemplate", "properties", key],
|
|
579
|
+
usedPaths
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
return out;
|
|
583
|
+
}
|
|
584
|
+
function resolveWithinRoot(root, jsonDir, rel) {
|
|
585
|
+
const target = path.resolve(jsonDir, rel);
|
|
586
|
+
if (target !== root && !target.startsWith(root + path.sep)) {
|
|
587
|
+
throw new Error(`marker path escapes the working tree: ${rel}`);
|
|
588
|
+
}
|
|
589
|
+
return target;
|
|
590
|
+
}
|
|
591
|
+
async function readWithinRoot(root, target, rel) {
|
|
592
|
+
const [realRoot, realTarget] = await Promise.all([realpath(root), realpath(target)]);
|
|
593
|
+
if (realTarget !== realRoot && !realTarget.startsWith(realRoot + path.sep)) {
|
|
594
|
+
throw new Error(`marker path escapes the working tree through a link: ${rel}`);
|
|
595
|
+
}
|
|
596
|
+
return readFile2(realTarget, "utf8");
|
|
597
|
+
}
|
|
598
|
+
async function resolveMarkers(value, jsonDir, root) {
|
|
599
|
+
if (Array.isArray(value)) {
|
|
600
|
+
const out = [];
|
|
601
|
+
for (const item of value) {
|
|
602
|
+
if (isRefMarker(item) && !existsSync(resolveWithinRoot(root, jsonDir, item["@ref"]))) continue;
|
|
603
|
+
out.push(await resolveMarkers(item, jsonDir, root));
|
|
604
|
+
}
|
|
605
|
+
return out;
|
|
606
|
+
}
|
|
607
|
+
if (isFileRef(value)) {
|
|
608
|
+
const target = resolveWithinRoot(root, jsonDir, value["@file"]);
|
|
609
|
+
return readWithinRoot(root, target, value["@file"]);
|
|
610
|
+
}
|
|
611
|
+
if (isRefMarker(value)) {
|
|
612
|
+
const target = resolveWithinRoot(root, jsonDir, value["@ref"]);
|
|
613
|
+
const text = await readWithinRoot(root, target, value["@ref"]);
|
|
614
|
+
const parsed = parseJson(text, target);
|
|
615
|
+
return resolveMarkers(parsed, path.dirname(target), root);
|
|
616
|
+
}
|
|
617
|
+
if (isPlainObject(value)) {
|
|
618
|
+
const out = {};
|
|
619
|
+
for (const [k, v] of Object.entries(value)) {
|
|
620
|
+
if (isRefMarker(v) && !existsSync(resolveWithinRoot(root, jsonDir, v["@ref"]))) continue;
|
|
621
|
+
out[k] = await resolveMarkers(v, jsonDir, root);
|
|
622
|
+
}
|
|
623
|
+
return out;
|
|
624
|
+
}
|
|
625
|
+
return value;
|
|
626
|
+
}
|
|
627
|
+
async function implode(opts) {
|
|
628
|
+
const root = path.resolve(opts.root);
|
|
629
|
+
const serverDir = path.join(root, "server");
|
|
630
|
+
const configPath = path.join(serverDir, "configuration.json");
|
|
631
|
+
const parsed = await readJson(configPath);
|
|
632
|
+
const resolved = await resolveMarkers(parsed, serverDir, root);
|
|
633
|
+
return resolved;
|
|
634
|
+
}
|
|
635
|
+
function createExplodeEngine() {
|
|
636
|
+
return { explode, implode };
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// src/xml/index.ts
|
|
640
|
+
import { XMLParser, XMLValidator } from "fast-xml-parser";
|
|
641
|
+
var ALWAYS_ARRAY_TAGS = /* @__PURE__ */ new Set([
|
|
642
|
+
"channel",
|
|
643
|
+
"connector",
|
|
644
|
+
"codeTemplate",
|
|
645
|
+
"codeTemplateLibrary",
|
|
646
|
+
"channelGroup",
|
|
647
|
+
"alert",
|
|
648
|
+
"rule",
|
|
649
|
+
"entry",
|
|
650
|
+
"string",
|
|
651
|
+
// Fully-qualified JavaScript step / rule element names (live under <elements>).
|
|
652
|
+
"com.mirth.connect.plugins.javascriptstep.JavaScriptStep",
|
|
653
|
+
"com.mirth.connect.plugins.javascriptrule.JavaScriptRule",
|
|
654
|
+
"com.mirth.connect.plugins.mapper.MapperStep",
|
|
655
|
+
"com.mirth.connect.plugins.messagebuilder.MessageBuilderStep"
|
|
656
|
+
]);
|
|
657
|
+
var ROOT_KEY = "serverConfiguration";
|
|
658
|
+
var TEXT_KEY = "#text";
|
|
659
|
+
var COMMENT_KEY = "#comment";
|
|
660
|
+
var CDATA_KEY = "#cdata";
|
|
661
|
+
var ORDER_KEY = "#order";
|
|
662
|
+
var ATTR_PREFIX = "@_";
|
|
663
|
+
var ORDERED_ATTRS = ":@";
|
|
664
|
+
var INDENT = " ";
|
|
665
|
+
function isWhitespaceOnly(s) {
|
|
666
|
+
return /^\s*$/.test(s);
|
|
667
|
+
}
|
|
668
|
+
var NAMED_DECODE = {
|
|
669
|
+
amp: "&",
|
|
670
|
+
lt: "<",
|
|
671
|
+
gt: ">",
|
|
672
|
+
quot: '"',
|
|
673
|
+
apos: "'"
|
|
674
|
+
};
|
|
675
|
+
function decodeEntities(value) {
|
|
676
|
+
if (!value.includes("&")) return value;
|
|
677
|
+
return value.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g, (whole, body) => {
|
|
678
|
+
if (body[0] !== "#") return NAMED_DECODE[body] ?? whole;
|
|
679
|
+
const code = body[1] === "x" || body[1] === "X" ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
|
|
680
|
+
if (!(code <= 1114111)) {
|
|
681
|
+
throw new Error(`XmlConfigAdapter.parse: invalid character reference ${whole}`);
|
|
682
|
+
}
|
|
683
|
+
return String.fromCodePoint(code);
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
function charRef(ch) {
|
|
687
|
+
return `&#x${ch.charCodeAt(0).toString(16)};`;
|
|
688
|
+
}
|
|
689
|
+
var ESCAPE = {
|
|
690
|
+
"&": "&",
|
|
691
|
+
"<": "<",
|
|
692
|
+
">": ">",
|
|
693
|
+
'"': """,
|
|
694
|
+
"'": "'"
|
|
695
|
+
};
|
|
696
|
+
function encodeText(value) {
|
|
697
|
+
return value.replace(/[&<>"'\x00-\x08\x0b-\x1f]/g, (ch) => ESCAPE[ch] ?? charRef(ch));
|
|
698
|
+
}
|
|
699
|
+
function encodeAttr(value) {
|
|
700
|
+
return value.replace(/[&<>"'\x00-\x1f]/g, (ch) => ESCAPE[ch] ?? charRef(ch));
|
|
701
|
+
}
|
|
702
|
+
function nodeName(node) {
|
|
703
|
+
const name = Object.keys(node).find((k) => k !== ORDERED_ATTRS);
|
|
704
|
+
if (name === void 0) throw new Error("XmlConfigAdapter.parse: empty node");
|
|
705
|
+
return name;
|
|
706
|
+
}
|
|
707
|
+
function rawInnerText(children) {
|
|
708
|
+
return children.map((c) => String(c[TEXT_KEY] ?? "")).join("");
|
|
709
|
+
}
|
|
710
|
+
function defaultOrder(obj) {
|
|
711
|
+
const seq = [];
|
|
712
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
713
|
+
if (key.startsWith(ATTR_PREFIX) || key === ORDER_KEY) continue;
|
|
714
|
+
const count = Array.isArray(value) ? value.length : 1;
|
|
715
|
+
for (let i = 0; i < count; i += 1) seq.push(key);
|
|
716
|
+
}
|
|
717
|
+
return seq;
|
|
718
|
+
}
|
|
719
|
+
function convertElement(children, attrs) {
|
|
720
|
+
const hasElementChild = children.some((c) => {
|
|
721
|
+
const n = nodeName(c);
|
|
722
|
+
return n !== TEXT_KEY && n !== CDATA_KEY;
|
|
723
|
+
});
|
|
724
|
+
const groups = /* @__PURE__ */ new Map();
|
|
725
|
+
const order = [];
|
|
726
|
+
const segments = [];
|
|
727
|
+
let pending = null;
|
|
728
|
+
const flushText = () => {
|
|
729
|
+
if (pending === null) return;
|
|
730
|
+
if (!hasElementChild || !isWhitespaceOnly(pending)) {
|
|
731
|
+
segments.push(pending);
|
|
732
|
+
order.push(TEXT_KEY);
|
|
733
|
+
}
|
|
734
|
+
pending = null;
|
|
735
|
+
};
|
|
736
|
+
for (const child of children) {
|
|
737
|
+
const name = nodeName(child);
|
|
738
|
+
if (name === TEXT_KEY) {
|
|
739
|
+
pending = (pending ?? "") + decodeEntities(String(child[TEXT_KEY]));
|
|
740
|
+
continue;
|
|
741
|
+
}
|
|
742
|
+
if (name === CDATA_KEY) {
|
|
743
|
+
pending = (pending ?? "") + rawInnerText(child[CDATA_KEY]);
|
|
744
|
+
continue;
|
|
745
|
+
}
|
|
746
|
+
flushText();
|
|
747
|
+
if (name === "#__proto__") {
|
|
748
|
+
throw new Error("XmlConfigAdapter.parse: unsupported element name <__proto__>");
|
|
749
|
+
}
|
|
750
|
+
const value = name === COMMENT_KEY ? rawInnerText(child[COMMENT_KEY]) : convertElement(child[name], child[ORDERED_ATTRS]);
|
|
751
|
+
const group = groups.get(name);
|
|
752
|
+
if (group) group.push(value);
|
|
753
|
+
else groups.set(name, [value]);
|
|
754
|
+
order.push(name);
|
|
755
|
+
}
|
|
756
|
+
flushText();
|
|
757
|
+
const attrEntries = Object.entries(attrs ?? {});
|
|
758
|
+
if (!hasElementChild && attrEntries.length === 0) {
|
|
759
|
+
return segments.join("");
|
|
760
|
+
}
|
|
761
|
+
const obj = {};
|
|
762
|
+
for (const [name, values] of groups) {
|
|
763
|
+
obj[name] = values.length > 1 || ALWAYS_ARRAY_TAGS.has(name) ? values : values[0];
|
|
764
|
+
}
|
|
765
|
+
if (segments.length === 1) obj[TEXT_KEY] = segments[0];
|
|
766
|
+
else if (segments.length > 1) obj[TEXT_KEY] = segments;
|
|
767
|
+
for (const [key, raw] of attrEntries) {
|
|
768
|
+
if (key === `${ATTR_PREFIX}__proto__`) {
|
|
769
|
+
throw new Error("XmlConfigAdapter.parse: unsupported attribute name __proto__");
|
|
770
|
+
}
|
|
771
|
+
obj[key] = decodeEntities(String(raw).replace(/[\t\n]/g, " "));
|
|
772
|
+
}
|
|
773
|
+
const def = defaultOrder(obj);
|
|
774
|
+
if (def.length !== order.length || def.some((k, i) => k !== order[i])) {
|
|
775
|
+
obj[ORDER_KEY] = order;
|
|
776
|
+
}
|
|
777
|
+
return obj;
|
|
778
|
+
}
|
|
779
|
+
var parser = new XMLParser({
|
|
780
|
+
preserveOrder: true,
|
|
781
|
+
ignoreAttributes: false,
|
|
782
|
+
attributeNamePrefix: ATTR_PREFIX,
|
|
783
|
+
parseTagValue: false,
|
|
784
|
+
parseAttributeValue: false,
|
|
785
|
+
trimValues: false,
|
|
786
|
+
processEntities: false,
|
|
787
|
+
commentPropName: COMMENT_KEY,
|
|
788
|
+
cdataPropName: CDATA_KEY
|
|
789
|
+
});
|
|
790
|
+
function orderedChildren(obj, where) {
|
|
791
|
+
const queues = /* @__PURE__ */ new Map();
|
|
792
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
793
|
+
if (key.startsWith(ATTR_PREFIX) || key === ORDER_KEY) continue;
|
|
794
|
+
queues.set(key, Array.isArray(value) ? [...value] : [value]);
|
|
795
|
+
}
|
|
796
|
+
const out = [];
|
|
797
|
+
const hint = obj[ORDER_KEY];
|
|
798
|
+
if (hint !== void 0) {
|
|
799
|
+
if (!Array.isArray(hint) || !hint.every((h) => typeof h === "string")) {
|
|
800
|
+
throw new Error(`XmlConfigAdapter.build: ${ORDER_KEY} under <${where}> must be an array of names`);
|
|
801
|
+
}
|
|
802
|
+
for (const name of hint) {
|
|
803
|
+
const next = queues.get(name)?.shift();
|
|
804
|
+
if (next !== void 0) out.push([name, next]);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
for (const [key, rest] of queues) {
|
|
808
|
+
for (const value of rest) out.push([key, value]);
|
|
809
|
+
}
|
|
810
|
+
return out;
|
|
811
|
+
}
|
|
812
|
+
function scalar(value) {
|
|
813
|
+
return value === null ? "" : String(value);
|
|
814
|
+
}
|
|
815
|
+
function serialize(name, value, depth, pretty, out) {
|
|
816
|
+
const pad = pretty ? INDENT.repeat(depth) : "";
|
|
817
|
+
const nl = pretty ? "\n" : "";
|
|
818
|
+
if (name === COMMENT_KEY) {
|
|
819
|
+
const text = scalar(value);
|
|
820
|
+
if (text.includes("--") || text.endsWith("-")) {
|
|
821
|
+
throw new Error(`XmlConfigAdapter.build: comment text cannot contain "--": ${text}`);
|
|
822
|
+
}
|
|
823
|
+
out.push(`${pad}<!--${text}-->${nl}`);
|
|
824
|
+
return;
|
|
825
|
+
}
|
|
826
|
+
if (name === TEXT_KEY) {
|
|
827
|
+
out.push(encodeText(scalar(value)));
|
|
828
|
+
return;
|
|
829
|
+
}
|
|
830
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
831
|
+
out.push(`${pad}<${name}>${encodeText(scalar(value))}</${name}>${nl}`);
|
|
832
|
+
return;
|
|
833
|
+
}
|
|
834
|
+
const attrs = Object.entries(value).filter(([k]) => k.startsWith(ATTR_PREFIX)).map(([k, v]) => ` ${k.slice(ATTR_PREFIX.length)}="${encodeAttr(scalar(v))}"`).join("");
|
|
835
|
+
const children = orderedChildren(value, name);
|
|
836
|
+
const hasElementChild = children.some(([k]) => k !== TEXT_KEY);
|
|
837
|
+
if (!hasElementChild) {
|
|
838
|
+
const text = children.map(([, v]) => encodeText(scalar(v))).join("");
|
|
839
|
+
out.push(`${pad}<${name}${attrs}>${text}</${name}>${nl}`);
|
|
840
|
+
return;
|
|
841
|
+
}
|
|
842
|
+
const mixed = children.some(([k]) => k === TEXT_KEY);
|
|
843
|
+
const childPretty = pretty && !mixed;
|
|
844
|
+
out.push(`${pad}<${name}${attrs}>${childPretty ? "\n" : ""}`);
|
|
845
|
+
for (const [key, child] of children) {
|
|
846
|
+
serialize(key, child, depth + 1, childPretty, out);
|
|
847
|
+
}
|
|
848
|
+
out.push(`${childPretty ? pad : ""}</${name}>${nl}`);
|
|
849
|
+
}
|
|
850
|
+
var XmlConfigAdapter = class {
|
|
851
|
+
/** Parse a Mirth backup XML string into a canonical config. */
|
|
852
|
+
parse(xml2) {
|
|
853
|
+
const normalized = xml2.replace(/\r\n?/g, "\n");
|
|
854
|
+
if (/<!DOCTYPE/i.test(normalized.slice(0, normalized.search(/<[A-Za-z_]/)))) {
|
|
855
|
+
throw new Error("XmlConfigAdapter.parse: DOCTYPE declarations are not supported");
|
|
856
|
+
}
|
|
857
|
+
const valid = XMLValidator.validate(normalized);
|
|
858
|
+
if (valid !== true) {
|
|
859
|
+
const { line, col, msg } = valid.err;
|
|
860
|
+
throw new Error(`XmlConfigAdapter.parse: not well-formed XML at line ${line}, column ${col}: ${msg}`);
|
|
861
|
+
}
|
|
862
|
+
const nodes = parser.parse(normalized);
|
|
863
|
+
const root = nodes.find((n) => nodeName(n) === ROOT_KEY);
|
|
864
|
+
if (root === void 0) {
|
|
865
|
+
throw new Error(`XmlConfigAdapter.parse: expected a top-level <${ROOT_KEY}> element`);
|
|
866
|
+
}
|
|
867
|
+
const value = convertElement(root[ROOT_KEY], root[ORDERED_ATTRS]);
|
|
868
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
|
869
|
+
}
|
|
870
|
+
/** Serialize a canonical config back to Mirth backup XML. */
|
|
871
|
+
build(config) {
|
|
872
|
+
const out = [];
|
|
873
|
+
serialize(ROOT_KEY, config, 0, true, out);
|
|
874
|
+
return out.join("");
|
|
875
|
+
}
|
|
876
|
+
};
|
|
877
|
+
|
|
878
|
+
// src/client/index.ts
|
|
879
|
+
import { CookieJar } from "tough-cookie";
|
|
880
|
+
import { Agent } from "undici";
|
|
881
|
+
|
|
882
|
+
// src/secrets/detect.ts
|
|
883
|
+
import { createHash } from "crypto";
|
|
884
|
+
|
|
885
|
+
// src/secrets/index.ts
|
|
886
|
+
var PLACEHOLDER = /\{\{env:([A-Za-z_][A-Za-z0-9_]*)\}\}/g;
|
|
887
|
+
var SECRET_KEY = /(password|passwd|passphrase|passcode|secret|token|pw|pwd|(?:api|access|secret|private)[_-]?key)$/i;
|
|
888
|
+
var CONFIG_PROPERTY = "com.mirth.connect.util.ConfigurationProperty";
|
|
889
|
+
function placeholder(name) {
|
|
890
|
+
return `{{env:${name}}}`;
|
|
891
|
+
}
|
|
892
|
+
function hasPlaceholder(value) {
|
|
893
|
+
PLACEHOLDER.lastIndex = 0;
|
|
894
|
+
return PLACEHOLDER.test(value);
|
|
895
|
+
}
|
|
896
|
+
function fill(value, env, missing) {
|
|
897
|
+
return value.replace(PLACEHOLDER, (whole, name) => {
|
|
898
|
+
const v = env[name];
|
|
899
|
+
if (v === void 0) {
|
|
900
|
+
missing.add(name);
|
|
901
|
+
return whole;
|
|
902
|
+
}
|
|
903
|
+
return v;
|
|
904
|
+
});
|
|
905
|
+
}
|
|
906
|
+
function render(config, env) {
|
|
907
|
+
const missing = /* @__PURE__ */ new Set();
|
|
908
|
+
const walk = (node) => {
|
|
909
|
+
if (typeof node === "string") return fill(node, env, missing);
|
|
910
|
+
if (Array.isArray(node)) return node.map(walk);
|
|
911
|
+
if (node && typeof node === "object") {
|
|
912
|
+
const out2 = {};
|
|
913
|
+
for (const [k, v] of Object.entries(node)) out2[k] = walk(v);
|
|
914
|
+
return out2;
|
|
915
|
+
}
|
|
916
|
+
return node;
|
|
917
|
+
};
|
|
918
|
+
const out = walk(config);
|
|
919
|
+
if (missing.size > 0) {
|
|
920
|
+
throw new Error(
|
|
921
|
+
`missing values for ${[...missing].sort().join(", ")} (set them in the env file or the environment)`
|
|
922
|
+
);
|
|
923
|
+
}
|
|
924
|
+
return out;
|
|
925
|
+
}
|
|
926
|
+
function elementSegment(el, index) {
|
|
927
|
+
if (el && typeof el === "object" && !Array.isArray(el)) {
|
|
928
|
+
const id = el["id"] ?? el["metaDataId"];
|
|
929
|
+
if (typeof id === "string" || typeof id === "number") return `[${String(id)}]`;
|
|
930
|
+
}
|
|
931
|
+
return `[${index}]`;
|
|
932
|
+
}
|
|
933
|
+
function mapLeaves(config, visit) {
|
|
934
|
+
const walk = (node, key, path6, labels, section, cmKey) => {
|
|
935
|
+
if (typeof node === "string") {
|
|
936
|
+
return visit(node, { location: path6.join("/"), key, labels, section, configMapKey: cmKey });
|
|
937
|
+
}
|
|
938
|
+
if (Array.isArray(node)) {
|
|
939
|
+
return node.map((el, i) => walk(el, key, [...path6.slice(0, -1), `${path6[path6.length - 1]}${elementSegment(el, i)}`], labels, section, cmKey));
|
|
940
|
+
}
|
|
941
|
+
if (node && typeof node === "object") {
|
|
942
|
+
const name = node["name"];
|
|
943
|
+
const inner = typeof name === "string" && name.trim() !== "" ? [...labels, name] : labels;
|
|
944
|
+
const entryKey = node["string"];
|
|
945
|
+
const mapKey = section === "configurationMap" && CONFIG_PROPERTY in node ? typeof entryKey === "string" ? entryKey : Array.isArray(entryKey) && typeof entryKey[0] === "string" ? entryKey[0] : void 0 : cmKey;
|
|
946
|
+
const out = {};
|
|
947
|
+
for (const [k, v] of Object.entries(node)) {
|
|
948
|
+
out[k] = walk(v, k, [...path6, k], inner, section || k, mapKey);
|
|
949
|
+
}
|
|
950
|
+
return out;
|
|
951
|
+
}
|
|
952
|
+
return node;
|
|
953
|
+
};
|
|
954
|
+
return walk(config, "", [], [], "");
|
|
955
|
+
}
|
|
956
|
+
function isSecretKey(key) {
|
|
957
|
+
return SECRET_KEY.test(key);
|
|
958
|
+
}
|
|
959
|
+
function isSecret(leaf) {
|
|
960
|
+
if (leaf.section === "configurationMap") return leaf.configMapKey !== void 0 && leaf.key === "value";
|
|
961
|
+
return SECRET_KEY.test(leaf.key);
|
|
962
|
+
}
|
|
963
|
+
function envName(parts) {
|
|
964
|
+
return parts.map((p) => p.toUpperCase().replace(/[^A-Z0-9]+/g, "_").replace(/^_+|_+$/g, "")).filter(Boolean).join("__").replace(/^(?=[0-9])/, "_");
|
|
965
|
+
}
|
|
966
|
+
function derivedName(leaf) {
|
|
967
|
+
if (leaf.configMapKey !== void 0) return envName(["CONFIG_MAP", leaf.configMapKey]);
|
|
968
|
+
const context = leaf.labels.length > 0 ? leaf.labels : [leaf.section];
|
|
969
|
+
return envName([...context, leaf.key]);
|
|
970
|
+
}
|
|
971
|
+
function redactKnownSecrets(config) {
|
|
972
|
+
return mapLeaves(config, (value, leaf) => isSecret(leaf) && value !== "" && !hasPlaceholder(value) ? "<redacted>" : value);
|
|
973
|
+
}
|
|
974
|
+
function templatesOf(config) {
|
|
975
|
+
const out = /* @__PURE__ */ new Map();
|
|
976
|
+
if (config) {
|
|
977
|
+
mapLeaves(config, (value, leaf) => {
|
|
978
|
+
if (hasPlaceholder(value)) out.set(leaf.location, value);
|
|
979
|
+
return value;
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
return out;
|
|
983
|
+
}
|
|
984
|
+
function matchTemplate(template, value) {
|
|
985
|
+
const names = [];
|
|
986
|
+
let pattern = "^";
|
|
987
|
+
let at = 0;
|
|
988
|
+
for (const m of template.matchAll(PLACEHOLDER)) {
|
|
989
|
+
pattern += template.slice(at, m.index).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
990
|
+
const seen = names.indexOf(m[1]);
|
|
991
|
+
if (seen >= 0) {
|
|
992
|
+
pattern += `\\${seen + 1}`;
|
|
993
|
+
} else {
|
|
994
|
+
names.push(m[1]);
|
|
995
|
+
pattern += "([\\s\\S]*?)";
|
|
996
|
+
}
|
|
997
|
+
at = m.index + m[0].length;
|
|
998
|
+
}
|
|
999
|
+
pattern += `${template.slice(at).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`;
|
|
1000
|
+
const match = new RegExp(pattern).exec(value);
|
|
1001
|
+
return match ? new Map(names.map((n, i) => [n, match[i + 1]])) : null;
|
|
1002
|
+
}
|
|
1003
|
+
function templatize(remote, previous, env) {
|
|
1004
|
+
const templates = templatesOf(previous);
|
|
1005
|
+
const envUpdates = {};
|
|
1006
|
+
const notes = [];
|
|
1007
|
+
const assigned = /* @__PURE__ */ new Map();
|
|
1008
|
+
const reserved = /* @__PURE__ */ new Set();
|
|
1009
|
+
for (const t of templates.values()) {
|
|
1010
|
+
for (const m of t.matchAll(PLACEHOLDER)) reserved.add(m[1]);
|
|
1011
|
+
}
|
|
1012
|
+
const fresh = (base, value) => {
|
|
1013
|
+
let name = base;
|
|
1014
|
+
for (let n = 2; assigned.has(name) || reserved.has(name); n += 1) name = `${base}_${n}`;
|
|
1015
|
+
assigned.set(name, value);
|
|
1016
|
+
if (env[name] !== value) envUpdates[name] = value;
|
|
1017
|
+
return name;
|
|
1018
|
+
};
|
|
1019
|
+
const bind = (template, values, rotated) => {
|
|
1020
|
+
let out = template;
|
|
1021
|
+
for (const [name, value] of values) {
|
|
1022
|
+
const bound = assigned.get(name);
|
|
1023
|
+
if (bound !== void 0 && bound !== value) {
|
|
1024
|
+
reserved.delete(name);
|
|
1025
|
+
const renamed = fresh(name, value);
|
|
1026
|
+
out = out.split(placeholder(name)).join(placeholder(renamed));
|
|
1027
|
+
notes.push(`${renamed}: split from ${name}, which another location holds with a different value`);
|
|
1028
|
+
continue;
|
|
1029
|
+
}
|
|
1030
|
+
assigned.set(name, value);
|
|
1031
|
+
if (env[name] !== value) {
|
|
1032
|
+
envUpdates[name] = value;
|
|
1033
|
+
if (rotated) notes.push(`${name}: server value differs from the env file; env file updated`);
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
return out;
|
|
1037
|
+
};
|
|
1038
|
+
const envValues = (template) => new Map([...template.matchAll(PLACEHOLDER)].map((m) => [m[1], env[m[1]]]));
|
|
1039
|
+
const config = mapLeaves(remote, (value, leaf) => {
|
|
1040
|
+
const template = templates.get(leaf.location);
|
|
1041
|
+
if (template !== void 0) {
|
|
1042
|
+
const missing = /* @__PURE__ */ new Set();
|
|
1043
|
+
if (fill(template, env, missing) === value && missing.size === 0) return bind(template, envValues(template), false);
|
|
1044
|
+
const captured = matchTemplate(template, value);
|
|
1045
|
+
if (captured) return bind(template, captured, true);
|
|
1046
|
+
let restored = value;
|
|
1047
|
+
for (const m of template.matchAll(PLACEHOLDER)) {
|
|
1048
|
+
const v = env[m[1]];
|
|
1049
|
+
if (v !== void 0 && v.length >= 4) restored = restored.split(v).join(placeholder(m[1]));
|
|
1050
|
+
}
|
|
1051
|
+
if (restored !== value) return bind(restored, envValues(restored), false);
|
|
1052
|
+
notes.push(`${leaf.location}: placeholder no longer matches the server; replaced with the server value`);
|
|
1053
|
+
return value;
|
|
1054
|
+
}
|
|
1055
|
+
if (isSecret(leaf) && value !== "" && !hasPlaceholder(value)) {
|
|
1056
|
+
return placeholder(fresh(derivedName(leaf), value));
|
|
1057
|
+
}
|
|
1058
|
+
return value;
|
|
1059
|
+
});
|
|
1060
|
+
return { config, envUpdates, notes };
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
// src/secrets/detect.ts
|
|
1064
|
+
function regexSpans(re, group) {
|
|
1065
|
+
return (value) => {
|
|
1066
|
+
const out = [];
|
|
1067
|
+
for (const m of value.matchAll(re)) {
|
|
1068
|
+
const secret = m[group];
|
|
1069
|
+
if (secret === void 0) continue;
|
|
1070
|
+
const start = m.index + m[0].lastIndexOf(secret);
|
|
1071
|
+
out.push({ start, end: start + secret.length });
|
|
1072
|
+
}
|
|
1073
|
+
return out;
|
|
1074
|
+
};
|
|
1075
|
+
}
|
|
1076
|
+
function dbConnectionSpans(value) {
|
|
1077
|
+
const out = [];
|
|
1078
|
+
for (const m of value.matchAll(/createDatabaseConnection\s*\(/g)) {
|
|
1079
|
+
let depth = 0;
|
|
1080
|
+
let quote = null;
|
|
1081
|
+
let argStart = m.index + m[0].length;
|
|
1082
|
+
const args = [];
|
|
1083
|
+
for (let i = argStart; i < value.length; i += 1) {
|
|
1084
|
+
const c = value[i];
|
|
1085
|
+
if (quote) {
|
|
1086
|
+
if (c === "\\") i += 1;
|
|
1087
|
+
else if (c === quote) quote = null;
|
|
1088
|
+
continue;
|
|
1089
|
+
}
|
|
1090
|
+
if (c === '"' || c === "'") quote = c;
|
|
1091
|
+
else if (c === "(" || c === "[" || c === "{") depth += 1;
|
|
1092
|
+
else if ((c === ")" || c === "]" || c === "}") && depth > 0) depth -= 1;
|
|
1093
|
+
else if (c === "," && depth === 0 || c === ")") {
|
|
1094
|
+
args.push({ start: argStart, end: i });
|
|
1095
|
+
argStart = i + 1;
|
|
1096
|
+
if (c === ")") break;
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
const pw = args[3];
|
|
1100
|
+
if (!pw) continue;
|
|
1101
|
+
const literal = /^\s*(["'])(.+)\1\s*$/s.exec(value.slice(pw.start, pw.end));
|
|
1102
|
+
if (literal) {
|
|
1103
|
+
const start = value.indexOf(literal[2], pw.start);
|
|
1104
|
+
out.push({ start, end: start + literal[2].length });
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
return out;
|
|
1108
|
+
}
|
|
1109
|
+
var ASSIGNED = String.raw`["']?\s*[:=]\s*(?:[\w$.[\]'"]+\s*(?:\|\||\?\?)\s*)?(["'])((?=\S)(?:[^"'{}\s]{4,}|(?=[^"'{}\n]*[0-9@#$%^&*+=~|\\/<>_])[^"'{}\n]{4,}))\1`;
|
|
1110
|
+
var CONN_VALUE = String.raw`([^;&'"\s](?:[^;&'"\n]*[^;&'"\s])?)`;
|
|
1111
|
+
function textSpans(code) {
|
|
1112
|
+
const out = [];
|
|
1113
|
+
let i = 0;
|
|
1114
|
+
while (i < code.length) {
|
|
1115
|
+
const c = code[i];
|
|
1116
|
+
const next = code[i + 1];
|
|
1117
|
+
if (c === "/" && (next === "/" || next === "*")) {
|
|
1118
|
+
const close = next === "/" ? code.indexOf("\n", i) : code.indexOf("*/", i + 2);
|
|
1119
|
+
const end = close < 0 ? code.length : close;
|
|
1120
|
+
out.push({ start: i + 2, end });
|
|
1121
|
+
i = end + 2;
|
|
1122
|
+
} else if (c === '"' || c === "'" || c === "`") {
|
|
1123
|
+
let j = i + 1;
|
|
1124
|
+
while (j < code.length && code[j] !== c && (c === "`" || code[j] !== "\n")) j += code[j] === "\\" ? 2 : 1;
|
|
1125
|
+
out.push({ start: i + 1, end: Math.min(j, code.length) });
|
|
1126
|
+
i = j + 1;
|
|
1127
|
+
} else {
|
|
1128
|
+
i += 1;
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
return out;
|
|
1132
|
+
}
|
|
1133
|
+
function outsideCode(spans) {
|
|
1134
|
+
return (value, script) => script ? textSpans(value).flatMap((t) => spans(value.slice(t.start, t.end)).map((s) => ({ start: s.start + t.start, end: s.end + t.start }))) : spans(value);
|
|
1135
|
+
}
|
|
1136
|
+
var RULES = [
|
|
1137
|
+
{
|
|
1138
|
+
kind: "private-key",
|
|
1139
|
+
suffix: "PRIVATE_KEY",
|
|
1140
|
+
spans: regexSpans(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, 0)
|
|
1141
|
+
},
|
|
1142
|
+
{ kind: "aws-access-key", suffix: "AWS_ACCESS_KEY", spans: regexSpans(/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, 0) },
|
|
1143
|
+
{ kind: "jwt", suffix: "TOKEN", spans: regexSpans(/\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, 0) },
|
|
1144
|
+
{ kind: "github-token", suffix: "TOKEN", spans: regexSpans(/\b(?:ghp|gho|ghs|ghu|github_pat)_[A-Za-z0-9_]{20,}/g, 0) },
|
|
1145
|
+
{ kind: "slack-token", suffix: "TOKEN", spans: regexSpans(/\bxox[abprs]-[A-Za-z0-9-]{10,}/g, 0) },
|
|
1146
|
+
// user:password@host. The user part stops at ';', '?' and '&' so a JDBC
|
|
1147
|
+
// parameter like `user=svc@srv` is not mistaken for credentials.
|
|
1148
|
+
{ kind: "url-credentials", suffix: "PASSWORD", spans: regexSpans(/\b[a-z][a-z0-9+.-]*:\/\/[^\s:/@'";?&]+:([^\s@'"/;?&]+)@/gi, 1) },
|
|
1149
|
+
// Drivers trim around `=` and the value, so spaces are allowed there. In a
|
|
1150
|
+
// script only string literals and comments are searched: `pwd=$('x')` is code.
|
|
1151
|
+
{
|
|
1152
|
+
kind: "connection-string",
|
|
1153
|
+
suffix: "PASSWORD",
|
|
1154
|
+
spans: outsideCode(regexSpans(new RegExp(String.raw`[;?&]\s*(?:password|pwd)\s*=\s*${CONN_VALUE}`, "gi"), 1))
|
|
1155
|
+
},
|
|
1156
|
+
// Leading the whole value (`Password=…;Server=…`), when another key=value follows.
|
|
1157
|
+
{
|
|
1158
|
+
kind: "connection-string",
|
|
1159
|
+
suffix: "PASSWORD",
|
|
1160
|
+
spans: outsideCode(regexSpans(new RegExp(String.raw`^\s*(?:password|pwd)\s*=\s*${CONN_VALUE}(?=\s*;\s*[\w ]+=)`, "gi"), 1))
|
|
1161
|
+
},
|
|
1162
|
+
// Case-sensitive, and the credential must contain a digit or a base64/token
|
|
1163
|
+
// symbol, so prose like "Basic authentication" does not match.
|
|
1164
|
+
{
|
|
1165
|
+
kind: "authorization-header",
|
|
1166
|
+
suffix: "TOKEN",
|
|
1167
|
+
spans: regexSpans(/\b(?:Basic|Bearer)\s+((?=[A-Za-z0-9+/=._~-]*[0-9+/=])[A-Za-z0-9+/=._~-]{12,})/g, 1)
|
|
1168
|
+
},
|
|
1169
|
+
{ kind: "db-connection-call", suffix: "DB_PASSWORD", spans: dbConnectionSpans },
|
|
1170
|
+
// name = 'literal' where the name ends in a secret word: password, dbPassword,
|
|
1171
|
+
// db_password, DB_PASSWORD, apiKey, authToken… (not tokenizer, not ==).
|
|
1172
|
+
// Also the default-value idiom: apiKey = apiKey || 'literal' (or ??).
|
|
1173
|
+
{
|
|
1174
|
+
kind: "assignment",
|
|
1175
|
+
suffix: "PASSWORD",
|
|
1176
|
+
spans: regexSpans(new RegExp(`(?<![\\w$])[\\w$]*?(?:password|passwd|pwd|secret|api[_-]?key|access[_-]?key|token)${ASSIGNED}`, "gi"), 2)
|
|
1177
|
+
},
|
|
1178
|
+
// `pass` as a whole name or a word boundary within one (pass, dbPass,
|
|
1179
|
+
// DB_PASS, sftp_pass), case-sensitive so bypass and compass don't match,
|
|
1180
|
+
// and not after words that make it an ordinary noun (byPass, firstPass).
|
|
1181
|
+
{
|
|
1182
|
+
kind: "assignment",
|
|
1183
|
+
suffix: "PASSWORD",
|
|
1184
|
+
spans: regexSpans(new RegExp(`(?<![\\w$])(?:pass|PASS|[\\w$]*[a-z0-9](?<!(?:[bB]y|[fF]irst|[sS]econd|[tT]hird|[lL]ast|[nN]ext|[oO]ne|[sS]ingle|[mM]ulti|[eE]very|[cC]om|[sS]ur|[oO]ver|[uU]nder))(?:Pass|PASS)|[\\w$]*_(?:pass|PASS))${ASSIGNED}`, "g"), 2)
|
|
1185
|
+
},
|
|
1186
|
+
// conn.setPassword('literal'), props.setApiKey("literal")…
|
|
1187
|
+
{
|
|
1188
|
+
kind: "setter-call",
|
|
1189
|
+
suffix: "PASSWORD",
|
|
1190
|
+
spans: regexSpans(/\bset[A-Za-z]*(?:Password|Passwd|Passphrase|Secret|Token|ApiKey)\s*\(\s*(["'])([^"'\n]{4,})\1\s*\)/g, 2)
|
|
1191
|
+
}
|
|
1192
|
+
];
|
|
1193
|
+
function isReference(secret) {
|
|
1194
|
+
return secret.includes("${") || hasPlaceholder(secret);
|
|
1195
|
+
}
|
|
1196
|
+
function hitsIn(value, script = false) {
|
|
1197
|
+
const taken = [];
|
|
1198
|
+
for (const rule of RULES) {
|
|
1199
|
+
for (const span of rule.spans(value, script)) {
|
|
1200
|
+
if (span.end <= span.start || isReference(value.slice(span.start, span.end))) continue;
|
|
1201
|
+
if (taken.some((t) => span.start < t.end && t.start < span.end)) continue;
|
|
1202
|
+
taken.push({ ...span, rule });
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
return taken.sort((a, b) => a.start - b.start);
|
|
1206
|
+
}
|
|
1207
|
+
var SCRIPT_KEYS = /* @__PURE__ */ new Set([...CODE_KEYS, ...CHANNEL_SCRIPT_KEYS]);
|
|
1208
|
+
function isScript(leaf) {
|
|
1209
|
+
return SCRIPT_KEYS.has(leaf.key) || leaf.section === "globalScripts";
|
|
1210
|
+
}
|
|
1211
|
+
function redactSecretsInText(text) {
|
|
1212
|
+
const value = text.replace(/("([\w.-]+)"\s*:\s*")((?:[^"\\]|\\.)+)"/g, (whole, head, key) => isSecretKey(key) ? `${head}<redacted>"` : whole).replace(/<([\w.:-]+)>([^<]+)<\/\1>/g, (whole, key) => isSecretKey(key) ? `<${key}><redacted></${key}>` : whole);
|
|
1213
|
+
let out = "";
|
|
1214
|
+
let at = 0;
|
|
1215
|
+
for (const h of hitsIn(value)) {
|
|
1216
|
+
out += `${value.slice(at, h.start)}<redacted ${h.rule.kind}>`;
|
|
1217
|
+
at = h.end;
|
|
1218
|
+
}
|
|
1219
|
+
return out + value.slice(at);
|
|
1220
|
+
}
|
|
1221
|
+
function contextOf(value, hits) {
|
|
1222
|
+
let redacted = "";
|
|
1223
|
+
let at = 0;
|
|
1224
|
+
for (const h of hits) {
|
|
1225
|
+
redacted += `${value.slice(at, h.start)}\0${h.rule.kind}\0`;
|
|
1226
|
+
at = h.end;
|
|
1227
|
+
}
|
|
1228
|
+
redacted += value.slice(at);
|
|
1229
|
+
return createHash("sha256").update(redacted).digest("hex").slice(0, 16);
|
|
1230
|
+
}
|
|
1231
|
+
function scanSecrets(config, opts) {
|
|
1232
|
+
const allowed = new Set((opts.allow ?? []).map((a) => `${a.location}#${a.kind}#${a.context}`));
|
|
1233
|
+
const env = opts.env ?? {};
|
|
1234
|
+
const findings = [];
|
|
1235
|
+
const envUpdates = {};
|
|
1236
|
+
const assigned = /* @__PURE__ */ new Map();
|
|
1237
|
+
const inUse = /* @__PURE__ */ new Set();
|
|
1238
|
+
mapLeaves(config, (value) => {
|
|
1239
|
+
for (const m of value.matchAll(/\{\{env:([A-Za-z_][A-Za-z0-9_]*)\}\}/g)) inUse.add(m[1]);
|
|
1240
|
+
return value;
|
|
1241
|
+
});
|
|
1242
|
+
const nameFor = (leaf, rule, value) => {
|
|
1243
|
+
const base = `${derivedName(leaf)}__${rule.suffix}`;
|
|
1244
|
+
for (let n = 1; ; n += 1) {
|
|
1245
|
+
const name = n === 1 ? base : `${base}_${n}`;
|
|
1246
|
+
if (assigned.has(name) || inUse.has(name)) continue;
|
|
1247
|
+
if (env[name] === void 0 || env[name] === value) {
|
|
1248
|
+
assigned.set(name, value);
|
|
1249
|
+
if (env[name] !== value) envUpdates[name] = value;
|
|
1250
|
+
return name;
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
};
|
|
1254
|
+
const out = mapLeaves(config, (value, leaf) => {
|
|
1255
|
+
const hits = hitsIn(value, isScript(leaf));
|
|
1256
|
+
if (hits.length === 0) return value;
|
|
1257
|
+
const context = contextOf(value, hits);
|
|
1258
|
+
let result = "";
|
|
1259
|
+
let at = 0;
|
|
1260
|
+
for (const h of hits) {
|
|
1261
|
+
if (allowed.has(`${leaf.location}#${h.rule.kind}#${context}`)) continue;
|
|
1262
|
+
findings.push({ location: leaf.location, kind: h.rule.kind, where: [...leaf.labels, leaf.key].join(" \u203A "), context });
|
|
1263
|
+
if (opts.mode === "find") continue;
|
|
1264
|
+
const secret = value.slice(h.start, h.end);
|
|
1265
|
+
const replacement = opts.mode === "extract" ? placeholder(nameFor(leaf, h.rule, secret)) : `<redacted ${h.rule.kind}>`;
|
|
1266
|
+
result += value.slice(at, h.start) + replacement;
|
|
1267
|
+
at = h.end;
|
|
1268
|
+
}
|
|
1269
|
+
return opts.mode === "find" ? value : result + value.slice(at);
|
|
1270
|
+
});
|
|
1271
|
+
return { config: out, findings, envUpdates };
|
|
1272
|
+
}
|
|
1273
|
+
function findEchoes(config, secrets) {
|
|
1274
|
+
const values = Object.entries(secrets).filter((e) => typeof e[1] === "string" && e[1].length >= 8);
|
|
1275
|
+
const out = [];
|
|
1276
|
+
if (values.length === 0) return out;
|
|
1277
|
+
mapLeaves(config, (value, leaf) => {
|
|
1278
|
+
for (const [name, secret] of values) {
|
|
1279
|
+
if (value.includes(secret)) out.push({ name, where: [...leaf.labels, leaf.key].join(" \u203A ") });
|
|
1280
|
+
}
|
|
1281
|
+
return value;
|
|
1282
|
+
});
|
|
1283
|
+
return out;
|
|
1284
|
+
}
|
|
1285
|
+
function formatFindings(findings) {
|
|
1286
|
+
return findings.map((f) => ` ${f.kind.padEnd(20)} ${f.where}
|
|
1287
|
+
${"".padEnd(20)} at ${f.location} context ${f.context}`).join("\n");
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
// src/client/index.ts
|
|
1291
|
+
var UNTRUSTED_CERT_CODES = /* @__PURE__ */ new Set([
|
|
1292
|
+
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
1293
|
+
"SELF_SIGNED_CERT_IN_CHAIN",
|
|
1294
|
+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
|
|
1295
|
+
"UNABLE_TO_GET_ISSUER_CERT_LOCALLY"
|
|
1296
|
+
// Not an expired certificate or a host-name mismatch: turning verification
|
|
1297
|
+
// off is the wrong advice for those, and their messages already say why.
|
|
1298
|
+
]);
|
|
1299
|
+
function connectionError(url, err) {
|
|
1300
|
+
let cause = err instanceof Error ? err.cause : void 0;
|
|
1301
|
+
if (cause instanceof AggregateError && cause.errors[0] instanceof Error) cause = cause.errors[0];
|
|
1302
|
+
const detail = cause?.message || (err instanceof Error ? err.message : String(err));
|
|
1303
|
+
const code = cause?.code;
|
|
1304
|
+
const error = new Error(
|
|
1305
|
+
`cannot reach ${new URL(url).origin}: ${detail}${code && !detail.includes(code) ? ` (${code})` : ""}`,
|
|
1306
|
+
{ cause: err }
|
|
1307
|
+
);
|
|
1308
|
+
error.code = code;
|
|
1309
|
+
return error;
|
|
1310
|
+
}
|
|
1311
|
+
var SERVER_CONFIG_KEY = "serverConfiguration";
|
|
1312
|
+
function unwrapSingleKey(value) {
|
|
1313
|
+
const keys = Object.keys(value);
|
|
1314
|
+
if (keys.length === 1) {
|
|
1315
|
+
return value[keys[0]];
|
|
1316
|
+
}
|
|
1317
|
+
return value;
|
|
1318
|
+
}
|
|
1319
|
+
var MirthClientImpl = class {
|
|
1320
|
+
config;
|
|
1321
|
+
baseUrl;
|
|
1322
|
+
cookieJar;
|
|
1323
|
+
/** Our own pool (not the global one) so `close()` can release it. */
|
|
1324
|
+
dispatcher;
|
|
1325
|
+
authenticated = false;
|
|
1326
|
+
/** Single in-flight login promise (concurrency guard). */
|
|
1327
|
+
loginPromise = null;
|
|
1328
|
+
constructor(config) {
|
|
1329
|
+
this.config = config;
|
|
1330
|
+
const protocol = config.https !== false ? "https" : "http";
|
|
1331
|
+
this.baseUrl = `${protocol}://${config.host}:${config.port}/api`;
|
|
1332
|
+
this.cookieJar = new CookieJar();
|
|
1333
|
+
this.dispatcher = new Agent(config.disableTlsCheck ? { connect: { rejectUnauthorized: false } } : {});
|
|
1334
|
+
}
|
|
1335
|
+
isAuthenticated() {
|
|
1336
|
+
return this.authenticated;
|
|
1337
|
+
}
|
|
1338
|
+
/**
|
|
1339
|
+
* Establish a session. Concurrent calls share a single in-flight login.
|
|
1340
|
+
*/
|
|
1341
|
+
async login() {
|
|
1342
|
+
if (this.loginPromise) {
|
|
1343
|
+
return this.loginPromise;
|
|
1344
|
+
}
|
|
1345
|
+
this.loginPromise = (async () => {
|
|
1346
|
+
try {
|
|
1347
|
+
const loginUrl = `${this.baseUrl}/users/_login`;
|
|
1348
|
+
const body = new URLSearchParams({
|
|
1349
|
+
username: this.config.username,
|
|
1350
|
+
password: this.config.password
|
|
1351
|
+
});
|
|
1352
|
+
const response = await this.send(loginUrl, {
|
|
1353
|
+
method: "POST",
|
|
1354
|
+
headers: {
|
|
1355
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
1356
|
+
"X-Requested-With": "XMLHttpRequest",
|
|
1357
|
+
Accept: "application/json"
|
|
1358
|
+
},
|
|
1359
|
+
body: body.toString()
|
|
1360
|
+
});
|
|
1361
|
+
await this.storeCookies(response, this.baseUrl);
|
|
1362
|
+
if (!response.ok) {
|
|
1363
|
+
await response.body?.cancel();
|
|
1364
|
+
throw new Error(`Login failed: HTTP ${response.status} ${response.statusText}`.trimEnd());
|
|
1365
|
+
}
|
|
1366
|
+
const result = await response.json();
|
|
1367
|
+
const payload = unwrapSingleKey(result);
|
|
1368
|
+
if (payload.status !== "SUCCESS") {
|
|
1369
|
+
throw new Error(`Login failed: ${payload.status} - ${payload.message ?? "Unknown error"}`);
|
|
1370
|
+
}
|
|
1371
|
+
this.authenticated = true;
|
|
1372
|
+
} finally {
|
|
1373
|
+
this.loginPromise = null;
|
|
1374
|
+
}
|
|
1375
|
+
})();
|
|
1376
|
+
return this.loginPromise;
|
|
1377
|
+
}
|
|
1378
|
+
/**
|
|
1379
|
+
* End the session and clear local auth state + cookies.
|
|
1380
|
+
*/
|
|
1381
|
+
async logout() {
|
|
1382
|
+
if (!this.authenticated) {
|
|
1383
|
+
return;
|
|
1384
|
+
}
|
|
1385
|
+
try {
|
|
1386
|
+
const logoutUrl = `${this.baseUrl}/users/_logout`;
|
|
1387
|
+
const cookieString = await this.cookieJar.getCookieString(logoutUrl);
|
|
1388
|
+
await this.send(logoutUrl, {
|
|
1389
|
+
method: "POST",
|
|
1390
|
+
headers: {
|
|
1391
|
+
"X-Requested-With": "XMLHttpRequest",
|
|
1392
|
+
...cookieString ? { Cookie: cookieString } : {}
|
|
1393
|
+
}
|
|
1394
|
+
});
|
|
1395
|
+
} finally {
|
|
1396
|
+
this.authenticated = false;
|
|
1397
|
+
await this.cookieJar.removeAllCookies();
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
/**
|
|
1401
|
+
* GET /server/configuration -> canonical config.
|
|
1402
|
+
*
|
|
1403
|
+
* Requests JSON, parses it, and unwraps the single top-level
|
|
1404
|
+
* `serverConfiguration` key (defensively: any single-key wrapper is unwrapped;
|
|
1405
|
+
* a multi-key object is returned as-is).
|
|
1406
|
+
*/
|
|
1407
|
+
async getServerConfiguration() {
|
|
1408
|
+
const response = await this.request("GET", "/server/configuration", {
|
|
1409
|
+
headers: { Accept: "application/json" }
|
|
1410
|
+
});
|
|
1411
|
+
const json = await response.json();
|
|
1412
|
+
return unwrapSingleKey(json);
|
|
1413
|
+
}
|
|
1414
|
+
/**
|
|
1415
|
+
* PUT /server/configuration <- canonical config.
|
|
1416
|
+
*
|
|
1417
|
+
* Re-wraps the canonical config as `{ serverConfiguration: config }` and
|
|
1418
|
+
* forwards the optional `deploy` / `overwriteConfigMap` flags as query params.
|
|
1419
|
+
*/
|
|
1420
|
+
async putServerConfiguration(config, options = {}) {
|
|
1421
|
+
const query = {};
|
|
1422
|
+
if (options.deploy !== void 0) {
|
|
1423
|
+
query.deploy = options.deploy;
|
|
1424
|
+
}
|
|
1425
|
+
if (options.overwriteConfigMap !== void 0) {
|
|
1426
|
+
query.overwriteConfigMap = options.overwriteConfigMap;
|
|
1427
|
+
}
|
|
1428
|
+
const wrapped = { [SERVER_CONFIG_KEY]: config };
|
|
1429
|
+
await this.request("PUT", "/server/configuration", {
|
|
1430
|
+
query,
|
|
1431
|
+
headers: {
|
|
1432
|
+
"Content-Type": "application/json",
|
|
1433
|
+
Accept: "application/json"
|
|
1434
|
+
},
|
|
1435
|
+
body: JSON.stringify(wrapped)
|
|
1436
|
+
});
|
|
1437
|
+
}
|
|
1438
|
+
async getServerId() {
|
|
1439
|
+
const response = await this.request("GET", "/server/id", { headers: { Accept: "text/plain" } });
|
|
1440
|
+
return (await response.text()).trim();
|
|
1441
|
+
}
|
|
1442
|
+
async getServerConfigurationXml() {
|
|
1443
|
+
const response = await this.request("GET", "/server/configuration", { headers: { Accept: "application/xml" } });
|
|
1444
|
+
return response.text();
|
|
1445
|
+
}
|
|
1446
|
+
async putServerConfigurationXml(xml2, options = {}) {
|
|
1447
|
+
await this.request("PUT", "/server/configuration", {
|
|
1448
|
+
query: { deploy: options.deploy, overwriteConfigMap: options.overwriteConfigMap },
|
|
1449
|
+
headers: { "Content-Type": "application/xml", Accept: "application/json" },
|
|
1450
|
+
body: xml2
|
|
1451
|
+
});
|
|
1452
|
+
}
|
|
1453
|
+
// --- per-resource ---------------------------------------------------------
|
|
1454
|
+
// Override is on: Mirth does not reject a stale revision anyway (verified on
|
|
1455
|
+
// 4.5.2), so conflict detection happens in the push planner instead.
|
|
1456
|
+
async getChannel(id) {
|
|
1457
|
+
const response = await this.request("GET", `/channels/${encodeURIComponent(id)}`, {
|
|
1458
|
+
headers: { Accept: "application/json" }
|
|
1459
|
+
});
|
|
1460
|
+
const text = await response.text();
|
|
1461
|
+
if (text.trim() === "") return null;
|
|
1462
|
+
return unwrapSingleKey(JSON.parse(text));
|
|
1463
|
+
}
|
|
1464
|
+
async close() {
|
|
1465
|
+
await this.dispatcher.close();
|
|
1466
|
+
}
|
|
1467
|
+
async putChannel(channel) {
|
|
1468
|
+
await this.sendJson("PUT", `/channels/${encodeURIComponent(String(channel.id))}`, { channel }, { override: true });
|
|
1469
|
+
}
|
|
1470
|
+
async deleteChannel(id) {
|
|
1471
|
+
await this.request("DELETE", `/channels/${encodeURIComponent(id)}`);
|
|
1472
|
+
}
|
|
1473
|
+
async putCodeTemplate(template) {
|
|
1474
|
+
await this.sendJson("PUT", `/codeTemplates/${encodeURIComponent(String(template.id))}`, { codeTemplate: template }, { override: true });
|
|
1475
|
+
}
|
|
1476
|
+
async deleteCodeTemplate(id) {
|
|
1477
|
+
await this.request("DELETE", `/codeTemplates/${encodeURIComponent(id)}`);
|
|
1478
|
+
}
|
|
1479
|
+
async putCodeTemplateLibraries(libraries) {
|
|
1480
|
+
await this.sendJson("PUT", "/codeTemplateLibraries", { list: { codeTemplateLibrary: libraries } }, { override: true });
|
|
1481
|
+
}
|
|
1482
|
+
async putGlobalScripts(globalScripts) {
|
|
1483
|
+
await this.sendJson("PUT", "/server/globalScripts", { map: globalScripts });
|
|
1484
|
+
}
|
|
1485
|
+
async getDeployedChannelIds() {
|
|
1486
|
+
const response = await this.request("GET", "/channels/statuses", { headers: { Accept: "application/json" } });
|
|
1487
|
+
const text = await response.text();
|
|
1488
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1489
|
+
for (const m of text.matchAll(/"channelId"\s*:\s*"([^"]+)"/g)) ids.add(m[1]);
|
|
1490
|
+
return ids;
|
|
1491
|
+
}
|
|
1492
|
+
async deployChannel(id) {
|
|
1493
|
+
await this.request("POST", `/channels/${encodeURIComponent(id)}/_deploy`, { query: { returnErrors: true } });
|
|
1494
|
+
}
|
|
1495
|
+
/** Send a JSON body; Mirth answers some updates with `{"boolean": false}` instead of an error status. */
|
|
1496
|
+
async sendJson(method, path6, body, query) {
|
|
1497
|
+
const response = await this.request(method, path6, {
|
|
1498
|
+
query,
|
|
1499
|
+
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
1500
|
+
body: JSON.stringify(body)
|
|
1501
|
+
});
|
|
1502
|
+
const text = await response.text();
|
|
1503
|
+
if (/^\s*\{\s*"boolean"\s*:\s*false\s*\}\s*$/.test(text)) {
|
|
1504
|
+
throw new Error(`${method} ${path6}: the server refused the update`);
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
// --- internal transport ---------------------------------------------------
|
|
1508
|
+
/**
|
|
1509
|
+
* Make an authenticated request. Ensures login, attaches/stores cookies, and
|
|
1510
|
+
* on a 401 while authenticated resets auth, re-logs in once, and retries.
|
|
1511
|
+
* Throws an {@link ApiError}-shaped error on a non-2xx response.
|
|
1512
|
+
*/
|
|
1513
|
+
async request(method, path6, options = {}, isRetry = false) {
|
|
1514
|
+
if (!this.authenticated) {
|
|
1515
|
+
await this.login();
|
|
1516
|
+
}
|
|
1517
|
+
const url = this.buildUrl(path6, options.query);
|
|
1518
|
+
const headers = {
|
|
1519
|
+
"X-Requested-With": "XMLHttpRequest",
|
|
1520
|
+
...options.headers
|
|
1521
|
+
};
|
|
1522
|
+
const cookieString = await this.cookieJar.getCookieString(url);
|
|
1523
|
+
if (cookieString) {
|
|
1524
|
+
headers.Cookie = cookieString;
|
|
1525
|
+
}
|
|
1526
|
+
const response = await this.send(url, { method, headers, body: options.body });
|
|
1527
|
+
await this.storeCookies(response, url);
|
|
1528
|
+
if (response.status === 401 && this.authenticated && !isRetry) {
|
|
1529
|
+
this.authenticated = false;
|
|
1530
|
+
await this.login();
|
|
1531
|
+
return this.request(method, path6, options, true);
|
|
1532
|
+
}
|
|
1533
|
+
if (!response.ok) {
|
|
1534
|
+
throw await this.toApiError(response);
|
|
1535
|
+
}
|
|
1536
|
+
return response;
|
|
1537
|
+
}
|
|
1538
|
+
/** fetch through this client's pool, with network failures explained. */
|
|
1539
|
+
async send(url, init) {
|
|
1540
|
+
try {
|
|
1541
|
+
return await fetch(url, {
|
|
1542
|
+
...init,
|
|
1543
|
+
// @ts-expect-error - dispatcher is a Node.js/undici specific option
|
|
1544
|
+
dispatcher: this.dispatcher
|
|
1545
|
+
});
|
|
1546
|
+
} catch (err) {
|
|
1547
|
+
throw connectionError(url, err);
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1550
|
+
/** Build an absolute URL with an optional query string. */
|
|
1551
|
+
buildUrl(path6, query) {
|
|
1552
|
+
const url = `${this.baseUrl}${path6}`;
|
|
1553
|
+
if (!query || Object.keys(query).length === 0) {
|
|
1554
|
+
return url;
|
|
1555
|
+
}
|
|
1556
|
+
const searchParams = new URLSearchParams();
|
|
1557
|
+
for (const [key, value] of Object.entries(query)) {
|
|
1558
|
+
if (value === void 0 || value === null) {
|
|
1559
|
+
continue;
|
|
1560
|
+
}
|
|
1561
|
+
searchParams.append(key, String(value));
|
|
1562
|
+
}
|
|
1563
|
+
const qs = searchParams.toString();
|
|
1564
|
+
return qs ? `${url}?${qs}` : url;
|
|
1565
|
+
}
|
|
1566
|
+
/** Persist any `set-cookie` from a response into the jar. */
|
|
1567
|
+
async storeCookies(response, url) {
|
|
1568
|
+
for (const cookie of response.headers.getSetCookie()) {
|
|
1569
|
+
await this.cookieJar.setCookie(cookie, url);
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
/** Build an ApiError-shaped Error from a non-2xx response. */
|
|
1573
|
+
async toApiError(response) {
|
|
1574
|
+
let body;
|
|
1575
|
+
try {
|
|
1576
|
+
body = await response.text();
|
|
1577
|
+
} catch {
|
|
1578
|
+
}
|
|
1579
|
+
const text = typeof body === "string" ? redactSecretsInText(readableBody(body)).trim() : "";
|
|
1580
|
+
const reason = text === "" ? "" : this.config.includeResponseBodies ? `: ${text}` : " (server response withheld; it may echo credentials)";
|
|
1581
|
+
const message = `HTTP ${response.status}: ${response.statusText}${reason}`;
|
|
1582
|
+
const error = new Error(message);
|
|
1583
|
+
error.status = response.status;
|
|
1584
|
+
error.statusText = response.statusText;
|
|
1585
|
+
error.message = message;
|
|
1586
|
+
error.body = text;
|
|
1587
|
+
return error;
|
|
1588
|
+
}
|
|
1589
|
+
};
|
|
1590
|
+
var XML_ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
|
|
1591
|
+
function readableBody(body) {
|
|
1592
|
+
const trimmed = body.trim();
|
|
1593
|
+
if (/^[[{"]/.test(trimmed)) {
|
|
1594
|
+
try {
|
|
1595
|
+
return flattenJson(JSON.parse(trimmed));
|
|
1596
|
+
} catch {
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1599
|
+
if (!trimmed.startsWith("<")) return trimmed;
|
|
1600
|
+
if (/^<(!doctype|html)/i.test(trimmed)) return "";
|
|
1601
|
+
const REDACTED = "\0redacted\0";
|
|
1602
|
+
return trimmed.replace(/<([\w.:-]+)>[^<]*<\/\1>/g, (whole, key) => isSecretKey(key) ? ` ${key}: ${REDACTED} ` : whole).replace(/<[^>]*>/g, " ").split(REDACTED).join("<redacted>").replace(
|
|
1603
|
+
/&(#x[0-9a-f]+|#[0-9]+|amp|lt|gt|quot|apos);/gi,
|
|
1604
|
+
(whole, e) => e[0] === "#" ? String.fromCodePoint(e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10)) : XML_ENTITIES[e.toLowerCase()] ?? whole
|
|
1605
|
+
);
|
|
1606
|
+
}
|
|
1607
|
+
function flattenJson(value, key = "") {
|
|
1608
|
+
if (typeof value === "string") return key !== "" && isSecretKey(key) && value !== "" ? "<redacted>" : value;
|
|
1609
|
+
if (Array.isArray(value)) return value.map((v) => flattenJson(v, key)).join("; ");
|
|
1610
|
+
if (value !== null && typeof value === "object") {
|
|
1611
|
+
return Object.entries(value).map(([k, v]) => `${k}: ${flattenJson(v, k)}`).join(", ");
|
|
1612
|
+
}
|
|
1613
|
+
return String(value);
|
|
1614
|
+
}
|
|
1615
|
+
function createMirthClient(config) {
|
|
1616
|
+
return new MirthClientImpl(config);
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
// src/push/index.ts
|
|
1620
|
+
import { createHash as createHash2 } from "crypto";
|
|
1621
|
+
var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
1622
|
+
function list(v) {
|
|
1623
|
+
if (v == null || v === "") return [];
|
|
1624
|
+
return (Array.isArray(v) ? v : [v]).filter(isObj);
|
|
1625
|
+
}
|
|
1626
|
+
function channelsOf(c) {
|
|
1627
|
+
return isObj(c["channels"]) ? list(c["channels"]["channel"]) : [];
|
|
1628
|
+
}
|
|
1629
|
+
function librariesOf(c) {
|
|
1630
|
+
return isObj(c["codeTemplateLibraries"]) ? list(c["codeTemplateLibraries"]["codeTemplateLibrary"]) : [];
|
|
1631
|
+
}
|
|
1632
|
+
function templatesOf2(library) {
|
|
1633
|
+
return isObj(library["codeTemplates"]) ? list(library["codeTemplates"]["codeTemplate"]) : [];
|
|
1634
|
+
}
|
|
1635
|
+
var idOf = (o) => String(o["id"]);
|
|
1636
|
+
var nameOf = (o) => String(o["name"] ?? o["id"]);
|
|
1637
|
+
var revisionOf = (o) => Number(o["revision"] ?? 0);
|
|
1638
|
+
function normalizeEol(s) {
|
|
1639
|
+
return s.replace(/\r\n?/g, "\n");
|
|
1640
|
+
}
|
|
1641
|
+
function normalizeEolDeep(value) {
|
|
1642
|
+
if (typeof value === "string") return normalizeEol(value);
|
|
1643
|
+
if (Array.isArray(value)) return value.map((v) => normalizeEolDeep(v));
|
|
1644
|
+
if (isObj(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, normalizeEolDeep(v)]));
|
|
1645
|
+
return value;
|
|
1646
|
+
}
|
|
1647
|
+
function same(a, b) {
|
|
1648
|
+
if (a === b) return true;
|
|
1649
|
+
if (typeof a === "string" && typeof b === "string") return normalizeEol(a) === normalizeEol(b);
|
|
1650
|
+
if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((x, i) => same(x, b[i]));
|
|
1651
|
+
if (isObj(a) && isObj(b)) {
|
|
1652
|
+
const ka = Object.keys(a);
|
|
1653
|
+
return ka.length === Object.keys(b).length && ka.every((k) => k in b && same(a[k], b[k]));
|
|
1654
|
+
}
|
|
1655
|
+
return false;
|
|
1656
|
+
}
|
|
1657
|
+
function stripVolatile(o) {
|
|
1658
|
+
const out = { ...o };
|
|
1659
|
+
delete out["revision"];
|
|
1660
|
+
delete out["lastModified"];
|
|
1661
|
+
const exportData = out["exportData"];
|
|
1662
|
+
if (isObj(exportData)) {
|
|
1663
|
+
const metadata = isObj(exportData["metadata"]) ? { ...exportData["metadata"] } : void 0;
|
|
1664
|
+
if (metadata) {
|
|
1665
|
+
delete metadata["lastModified"];
|
|
1666
|
+
delete metadata["userId"];
|
|
1667
|
+
}
|
|
1668
|
+
out["exportData"] = metadata ? { metadata } : {};
|
|
1669
|
+
}
|
|
1670
|
+
return out;
|
|
1671
|
+
}
|
|
1672
|
+
function libraryShape(lib) {
|
|
1673
|
+
const out = stripVolatile(lib);
|
|
1674
|
+
out["codeTemplates"] = templatesOf2(lib).map(idOf);
|
|
1675
|
+
return out;
|
|
1676
|
+
}
|
|
1677
|
+
function hashGlobalScripts(c) {
|
|
1678
|
+
return createHash2("sha256").update(JSON.stringify(normalizeEolDeep(c["globalScripts"] ?? null))).digest("hex");
|
|
1679
|
+
}
|
|
1680
|
+
function resourceIds(c) {
|
|
1681
|
+
const libs = librariesOf(c);
|
|
1682
|
+
const revs = (items) => Object.fromEntries(items.map((o) => [idOf(o), revisionOf(o)]));
|
|
1683
|
+
return {
|
|
1684
|
+
channels: revs(channelsOf(c)),
|
|
1685
|
+
libraries: revs(libs),
|
|
1686
|
+
codeTemplates: revs(libs.flatMap(templatesOf2)),
|
|
1687
|
+
globalScripts: hashGlobalScripts(c)
|
|
1688
|
+
};
|
|
1689
|
+
}
|
|
1690
|
+
function knownFrom(raw) {
|
|
1691
|
+
if (!isObj(raw)) return void 0;
|
|
1692
|
+
const r = raw;
|
|
1693
|
+
const map = (v) => Array.isArray(v) ? Object.fromEntries(v.map((id) => [String(id), null])) : v ?? {};
|
|
1694
|
+
return {
|
|
1695
|
+
channels: map(r["channels"]),
|
|
1696
|
+
libraries: map(r["libraries"]),
|
|
1697
|
+
codeTemplates: map(r["codeTemplates"]),
|
|
1698
|
+
globalScripts: typeof r["globalScripts"] === "string" ? r["globalScripts"] : void 0
|
|
1699
|
+
};
|
|
1700
|
+
}
|
|
1701
|
+
function knownAfterPush(known, applied, touched, fresh) {
|
|
1702
|
+
const now = resourceIds(fresh);
|
|
1703
|
+
const next = {
|
|
1704
|
+
channels: { ...known.channels },
|
|
1705
|
+
libraries: { ...known.libraries },
|
|
1706
|
+
codeTemplates: { ...known.codeTemplates },
|
|
1707
|
+
globalScripts: known.globalScripts
|
|
1708
|
+
};
|
|
1709
|
+
const key = { channel: "channels", library: "libraries", codeTemplate: "codeTemplates" };
|
|
1710
|
+
for (const c of applied) {
|
|
1711
|
+
if (c.kind === "globalScripts") {
|
|
1712
|
+
next.globalScripts = now.globalScripts;
|
|
1713
|
+
} else if (c.op === "delete") {
|
|
1714
|
+
delete next[key[c.kind]][c.id];
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
for (const k of ["channels", "libraries", "codeTemplates"]) {
|
|
1718
|
+
for (const id of touched) if (id in now[k]) next[k][id] = now[k][id];
|
|
1719
|
+
}
|
|
1720
|
+
return next;
|
|
1721
|
+
}
|
|
1722
|
+
var HANDLED = /* @__PURE__ */ new Set(["channels", "codeTemplateLibraries", "globalScripts", "date"]);
|
|
1723
|
+
function selectedBy(names, what, local, remote) {
|
|
1724
|
+
if (names === void 0) return () => true;
|
|
1725
|
+
const known = [...local, ...remote];
|
|
1726
|
+
for (const n of names) {
|
|
1727
|
+
if (!known.some((o) => nameOf(o) === n || idOf(o) === n)) throw new Error(`no ${what} named "${n}" in the tree or on the server`);
|
|
1728
|
+
}
|
|
1729
|
+
return (o) => names.includes(nameOf(o)) || names.includes(idOf(o));
|
|
1730
|
+
}
|
|
1731
|
+
function assertNoMovesAcrossScope(ll, rl, inScope) {
|
|
1732
|
+
const owner = (libs) => new Map(libs.flatMap((l) => templatesOf2(l).map((t) => [idOf(t), l])));
|
|
1733
|
+
const localOwner = owner(ll);
|
|
1734
|
+
for (const [id, r] of owner(rl)) {
|
|
1735
|
+
const l = localOwner.get(id);
|
|
1736
|
+
if (l && idOf(l) !== idOf(r) && inScope(l) !== inScope(r)) {
|
|
1737
|
+
throw new Error(
|
|
1738
|
+
`code template "${nameOf(templatesOf2(l).find((t) => idOf(t) === id))}" moved from "${nameOf(r)}" to "${nameOf(l)}"; include both with --library`
|
|
1739
|
+
);
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
function librariesInSync(local, remote) {
|
|
1744
|
+
const rl = new Map(librariesOf(remote).map((l) => [idOf(l), l]));
|
|
1745
|
+
return librariesOf(local).filter((l) => {
|
|
1746
|
+
const r = rl.get(idOf(l));
|
|
1747
|
+
return r !== void 0 && revisionOf(r) === revisionOf(l) && same(libraryShape(l), libraryShape(r));
|
|
1748
|
+
}).map(idOf);
|
|
1749
|
+
}
|
|
1750
|
+
function channelsUsing(lib, allChannelIds) {
|
|
1751
|
+
const ids = (v) => isObj(v) ? (Array.isArray(v["string"]) ? v["string"] : v["string"] != null ? [v["string"]] : []).map(String) : [];
|
|
1752
|
+
if (lib["includeNewChannels"] === true) {
|
|
1753
|
+
const disabled = new Set(ids(lib["disabledChannelIds"]));
|
|
1754
|
+
return allChannelIds.filter((id) => !disabled.has(id));
|
|
1755
|
+
}
|
|
1756
|
+
const enabled = new Set(ids(lib["enabledChannelIds"]));
|
|
1757
|
+
return allChannelIds.filter((id) => enabled.has(id));
|
|
1758
|
+
}
|
|
1759
|
+
function duplicates(items, key) {
|
|
1760
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1761
|
+
for (const o of items) groups.set(key(o), [...groups.get(key(o)) ?? [], o]);
|
|
1762
|
+
return [...groups].filter(([, group]) => group.length > 1);
|
|
1763
|
+
}
|
|
1764
|
+
function assertUniqueIds(local) {
|
|
1765
|
+
const libs = librariesOf(local);
|
|
1766
|
+
const problems = [
|
|
1767
|
+
...duplicates(channelsOf(local), idOf).map(([id, g]) => `channels ${g.map((o) => `"${nameOf(o)}"`).join(", ")} share id ${id}`),
|
|
1768
|
+
...duplicates(libs, idOf).map(([id, g]) => `libraries ${g.map((o) => `"${nameOf(o)}"`).join(", ")} share id ${id}`),
|
|
1769
|
+
...duplicates(libs.flatMap(templatesOf2), idOf).map(([id, g]) => `code templates ${g.map((o) => `"${nameOf(o)}"`).join(", ")} share id ${id}`)
|
|
1770
|
+
];
|
|
1771
|
+
if (problems.length > 0) {
|
|
1772
|
+
throw new Error(`the tree holds duplicate ids (a copied directory keeps its source's id):
|
|
1773
|
+
${problems.join("\n ")}
|
|
1774
|
+
give each copy a new id (a UUID) before pushing`);
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
function planPush(local, remote, scope = {}, known, opts = {}) {
|
|
1778
|
+
assertUniqueIds(local);
|
|
1779
|
+
const everything = scope.channels === void 0 && scope.libraries === void 0 && scope.globalScripts === void 0;
|
|
1780
|
+
const channelScope = everything || scope.channels !== void 0;
|
|
1781
|
+
const libraryScope = everything || scope.libraries !== void 0;
|
|
1782
|
+
const changes = [];
|
|
1783
|
+
const conflicts = [];
|
|
1784
|
+
const deploy = /* @__PURE__ */ new Set();
|
|
1785
|
+
const serverOnly = [];
|
|
1786
|
+
const missingLocally = (kind, r, label, baseline) => {
|
|
1787
|
+
const what = `${kind === "codeTemplate" ? "code template" : kind} "${label}"`;
|
|
1788
|
+
if (baseline && !(idOf(r) in baseline)) {
|
|
1789
|
+
serverOnly.push(what);
|
|
1790
|
+
return;
|
|
1791
|
+
}
|
|
1792
|
+
const pulled = baseline?.[idOf(r)];
|
|
1793
|
+
if (pulled != null && revisionOf(r) > pulled) {
|
|
1794
|
+
conflicts.push(`${what} changed on the server since the last pull (revision ${revisionOf(r)}, pulled ${pulled}); deleting it would discard that`);
|
|
1795
|
+
}
|
|
1796
|
+
changes.push({ kind, op: "delete", id: idOf(r), label });
|
|
1797
|
+
};
|
|
1798
|
+
if (channelScope) {
|
|
1799
|
+
const lc = channelsOf(local);
|
|
1800
|
+
const rc = channelsOf(remote);
|
|
1801
|
+
const inScope = selectedBy(scope.channels, "channel", lc, rc);
|
|
1802
|
+
const remoteById = new Map(rc.map((c) => [idOf(c), c]));
|
|
1803
|
+
const localIds = new Set(lc.map(idOf));
|
|
1804
|
+
for (const c of lc.filter(inScope)) {
|
|
1805
|
+
const r = remoteById.get(idOf(c));
|
|
1806
|
+
if (!r) {
|
|
1807
|
+
changes.push({ kind: "channel", op: "create", id: idOf(c), label: nameOf(c) });
|
|
1808
|
+
} else if (!same(stripVolatile(c), stripVolatile(r))) {
|
|
1809
|
+
changes.push({ kind: "channel", op: "update", id: idOf(c), label: nameOf(c) });
|
|
1810
|
+
if (revisionOf(r) > revisionOf(c)) conflicts.push(`channel "${nameOf(c)}" (server revision ${revisionOf(r)}, tree ${revisionOf(c)})`);
|
|
1811
|
+
} else {
|
|
1812
|
+
continue;
|
|
1813
|
+
}
|
|
1814
|
+
deploy.add(idOf(c));
|
|
1815
|
+
}
|
|
1816
|
+
for (const r of rc.filter(inScope)) {
|
|
1817
|
+
if (!localIds.has(idOf(r))) missingLocally("channel", r, nameOf(r), known?.channels);
|
|
1818
|
+
}
|
|
1819
|
+
}
|
|
1820
|
+
const deletedChannels = new Set(changes.filter((c) => c.kind === "channel" && c.op === "delete").map((c) => c.id));
|
|
1821
|
+
const writtenChannels = new Set(changes.filter((c) => c.kind === "channel" && c.op !== "delete").map((c) => c.id));
|
|
1822
|
+
const effective = /* @__PURE__ */ new Map();
|
|
1823
|
+
for (const r of channelsOf(remote)) if (!deletedChannels.has(idOf(r))) effective.set(idOf(r), r);
|
|
1824
|
+
for (const l of channelsOf(local)) if (writtenChannels.has(idOf(l))) effective.set(idOf(l), l);
|
|
1825
|
+
const nameKey = (c) => nameOf(c).toLowerCase();
|
|
1826
|
+
const during = opts.wholeReplace ? [] : channelsOf(remote);
|
|
1827
|
+
const holders = [...new Map([...during, ...effective.values()].map((c) => [`${idOf(c)}
|
|
1828
|
+
${nameKey(c)}`, c])).values()];
|
|
1829
|
+
const clashes = duplicates(holders, nameKey).filter(([, g]) => g.some((c) => writtenChannels.has(idOf(c))));
|
|
1830
|
+
if (clashes.length > 0) {
|
|
1831
|
+
throw new Error(
|
|
1832
|
+
`the push would save a channel under a name another channel holds:
|
|
1833
|
+
` + clashes.map(([, g]) => `"${nameOf(g[0])}": ids ${[...new Set(g.map(idOf))].join(", ")}`).join("\n ") + `
|
|
1834
|
+
rename one of them, or delete or rename the other in a push of its own first`
|
|
1835
|
+
);
|
|
1836
|
+
}
|
|
1837
|
+
if (libraryScope) {
|
|
1838
|
+
const ll = librariesOf(local);
|
|
1839
|
+
const rl = librariesOf(remote);
|
|
1840
|
+
const inScope = selectedBy(scope.libraries, "library", ll, rl);
|
|
1841
|
+
if (scope.libraries !== void 0) assertNoMovesAcrossScope(ll, rl, inScope);
|
|
1842
|
+
const remoteLibById = new Map(rl.map((l) => [idOf(l), l]));
|
|
1843
|
+
const remoteTemplates = new Map(rl.flatMap((l) => templatesOf2(l).map((t) => [idOf(t), t])));
|
|
1844
|
+
const localTemplateIds = new Set(ll.flatMap((l) => templatesOf2(l).map(idOf)));
|
|
1845
|
+
const allChannelIds = [...effective.keys()];
|
|
1846
|
+
for (const lib of ll.filter(inScope)) {
|
|
1847
|
+
const r = remoteLibById.get(idOf(lib));
|
|
1848
|
+
let touched = false;
|
|
1849
|
+
if (!r || !same(libraryShape(lib), libraryShape(r))) {
|
|
1850
|
+
changes.push({ kind: "library", op: r ? "update" : "create", id: idOf(lib), label: nameOf(lib) });
|
|
1851
|
+
touched = true;
|
|
1852
|
+
if (r && revisionOf(r) > revisionOf(lib)) conflicts.push(`library "${nameOf(lib)}" (server revision ${revisionOf(r)}, tree ${revisionOf(lib)})`);
|
|
1853
|
+
}
|
|
1854
|
+
for (const t of templatesOf2(lib)) {
|
|
1855
|
+
const rt = remoteTemplates.get(idOf(t));
|
|
1856
|
+
const label = `${nameOf(lib)}/${nameOf(t)}`;
|
|
1857
|
+
if (!rt) {
|
|
1858
|
+
changes.push({ kind: "codeTemplate", op: "create", id: idOf(t), label });
|
|
1859
|
+
} else if (!same(stripVolatile(t), stripVolatile(rt))) {
|
|
1860
|
+
changes.push({ kind: "codeTemplate", op: "update", id: idOf(t), label });
|
|
1861
|
+
if (revisionOf(rt) > revisionOf(t)) conflicts.push(`code template "${label}" (server revision ${revisionOf(rt)}, tree ${revisionOf(t)})`);
|
|
1862
|
+
} else {
|
|
1863
|
+
continue;
|
|
1864
|
+
}
|
|
1865
|
+
touched = true;
|
|
1866
|
+
}
|
|
1867
|
+
if (touched) {
|
|
1868
|
+
for (const id of channelsUsing(lib, allChannelIds)) deploy.add(id);
|
|
1869
|
+
if (r) for (const id of channelsUsing(r, allChannelIds)) deploy.add(id);
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
for (const r of rl.filter(inScope)) {
|
|
1873
|
+
if (!ll.some((l) => idOf(l) === idOf(r))) {
|
|
1874
|
+
const before = changes.length;
|
|
1875
|
+
missingLocally("library", r, nameOf(r), known?.libraries);
|
|
1876
|
+
if (changes.length > before) for (const id of channelsUsing(r, allChannelIds)) deploy.add(id);
|
|
1877
|
+
}
|
|
1878
|
+
for (const t of templatesOf2(r)) {
|
|
1879
|
+
if (!localTemplateIds.has(idOf(t))) missingLocally("codeTemplate", t, `${nameOf(r)}/${nameOf(t)}`, known?.codeTemplates);
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
}
|
|
1883
|
+
if ((everything || scope.globalScripts === true) && !same(local["globalScripts"], remote["globalScripts"])) {
|
|
1884
|
+
changes.push({ kind: "globalScripts", op: "update", id: "globalScripts", label: "global scripts" });
|
|
1885
|
+
if (known?.globalScripts && hashGlobalScripts(remote) !== known.globalScripts) {
|
|
1886
|
+
conflicts.push("global scripts changed on the server since the last pull");
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
const notPushed = everything ? [.../* @__PURE__ */ new Set([...Object.keys(local), ...Object.keys(remote)])].filter((k) => !HANDLED.has(k) && !k.startsWith("@") && !same(local[k], remote[k])).sort() : [];
|
|
1890
|
+
const enabled = new Set(
|
|
1891
|
+
[...effective.values()].filter((c) => {
|
|
1892
|
+
const md = isObj(c["exportData"]) ? c["exportData"]["metadata"] : void 0;
|
|
1893
|
+
return !(isObj(md) && md["enabled"] === false);
|
|
1894
|
+
}).map(idOf)
|
|
1895
|
+
);
|
|
1896
|
+
return {
|
|
1897
|
+
changes,
|
|
1898
|
+
conflicts,
|
|
1899
|
+
serverOnly,
|
|
1900
|
+
notPushed,
|
|
1901
|
+
deployIds: [...deploy].filter((id) => enabled.has(id))
|
|
1902
|
+
};
|
|
1903
|
+
}
|
|
1904
|
+
function librariesToSend(local, remote, scope, plan) {
|
|
1905
|
+
const ll = librariesOf(local);
|
|
1906
|
+
const rl = librariesOf(remote);
|
|
1907
|
+
const inScope = scope.libraries === void 0 ? () => true : (o) => scope.libraries.includes(nameOf(o)) || scope.libraries.includes(idOf(o));
|
|
1908
|
+
const deleted = new Set(plan.changes.filter((c) => c.kind === "library" && c.op === "delete").map((c) => c.id));
|
|
1909
|
+
const localById = new Map(ll.map((l) => [idOf(l), l]));
|
|
1910
|
+
const out = [];
|
|
1911
|
+
for (const r of rl) {
|
|
1912
|
+
if (deleted.has(idOf(r))) continue;
|
|
1913
|
+
const l = localById.get(idOf(r));
|
|
1914
|
+
out.push(l && inScope(l) ? l : r);
|
|
1915
|
+
}
|
|
1916
|
+
for (const l of ll) if (inScope(l) && !rl.some((r) => idOf(r) === idOf(l))) out.push(l);
|
|
1917
|
+
return out;
|
|
1918
|
+
}
|
|
1919
|
+
function changedSince(plan, before, after) {
|
|
1920
|
+
const out = [];
|
|
1921
|
+
const libs = (c) => new Map(librariesOf(c).map((l) => [idOf(l), l]));
|
|
1922
|
+
const [lb, la] = [libs(before), libs(after)];
|
|
1923
|
+
for (const c of plan.changes) {
|
|
1924
|
+
let a;
|
|
1925
|
+
let b;
|
|
1926
|
+
if (c.kind === "channel") [b, a] = [findChannel(before, c.id), findChannel(after, c.id)];
|
|
1927
|
+
else if (c.kind === "codeTemplate") [b, a] = [findTemplate(before, c.id), findTemplate(after, c.id)];
|
|
1928
|
+
else if (c.kind === "library") [b, a] = [lb.get(c.id), la.get(c.id)];
|
|
1929
|
+
else if (!same(before["globalScripts"], after["globalScripts"])) out.push("global scripts");
|
|
1930
|
+
if (c.kind === "globalScripts") continue;
|
|
1931
|
+
const existed = b !== void 0;
|
|
1932
|
+
const exists = a !== void 0;
|
|
1933
|
+
if (existed !== exists || a && b && revisionOf(a) !== revisionOf(b)) out.push(`${c.kind} "${c.label}"`);
|
|
1934
|
+
}
|
|
1935
|
+
if (plan.changes.some((c) => c.kind === "library")) {
|
|
1936
|
+
const shape = (m) => [...m].map(([id, l]) => `${id}@${revisionOf(l)}`).sort().join(",");
|
|
1937
|
+
if (shape(lb) !== shape(la)) out.push("code template libraries (the library list is saved as a whole)");
|
|
1938
|
+
}
|
|
1939
|
+
return [...new Set(out)];
|
|
1940
|
+
}
|
|
1941
|
+
function sameServerConfig(a, b) {
|
|
1942
|
+
const { date: _a, ...ra } = a;
|
|
1943
|
+
const { date: _b, ...rb } = b;
|
|
1944
|
+
return same(ra, rb);
|
|
1945
|
+
}
|
|
1946
|
+
function savedChangeMatches(change, local, remote) {
|
|
1947
|
+
if (change.kind === "globalScripts") return same(local["globalScripts"], remote["globalScripts"]);
|
|
1948
|
+
const find = (config) => change.kind === "channel" ? findChannel(config, change.id) : change.kind === "codeTemplate" ? findTemplate(config, change.id) : librariesOf(config).find((l) => idOf(l) === change.id);
|
|
1949
|
+
const after = find(remote);
|
|
1950
|
+
if (change.op === "delete") return after === void 0;
|
|
1951
|
+
const sent = find(local);
|
|
1952
|
+
if (!sent || !after) return false;
|
|
1953
|
+
const shape = change.kind === "library" ? libraryShape : stripVolatile;
|
|
1954
|
+
return same(shape(sent), shape(after));
|
|
1955
|
+
}
|
|
1956
|
+
function findTemplate(c, id) {
|
|
1957
|
+
for (const lib of librariesOf(c)) for (const t of templatesOf2(lib)) if (idOf(t) === id) return t;
|
|
1958
|
+
return void 0;
|
|
1959
|
+
}
|
|
1960
|
+
function findChannel(c, id) {
|
|
1961
|
+
return channelsOf(c).find((ch) => idOf(ch) === id);
|
|
1962
|
+
}
|
|
1963
|
+
|
|
1964
|
+
// src/push/apply.ts
|
|
1965
|
+
import { readdir, writeFile as writeFile2 } from "fs/promises";
|
|
1966
|
+
import { existsSync as existsSync2 } from "fs";
|
|
1967
|
+
import * as path2 from "path";
|
|
1968
|
+
var ORDER = [
|
|
1969
|
+
["codeTemplate", ["create", "update"]],
|
|
1970
|
+
["library", ["create", "update", "delete"]],
|
|
1971
|
+
["codeTemplate", ["delete"]],
|
|
1972
|
+
["channel", ["create", "update"]],
|
|
1973
|
+
["channel", ["delete"]],
|
|
1974
|
+
["globalScripts", ["update"]]
|
|
1975
|
+
];
|
|
1976
|
+
async function applyPlan(client, plan, local, remote, scope, opts = {}) {
|
|
1977
|
+
const applied = [];
|
|
1978
|
+
const touchedIds = /* @__PURE__ */ new Set();
|
|
1979
|
+
let librariesSent = false;
|
|
1980
|
+
for (const [kind, ops] of ORDER) {
|
|
1981
|
+
for (const change of plan.changes.filter((c) => c.kind === kind && ops.includes(c.op))) {
|
|
1982
|
+
try {
|
|
1983
|
+
if (kind === "library") {
|
|
1984
|
+
if (!librariesSent) {
|
|
1985
|
+
const inSync = librariesInSync(local, remote);
|
|
1986
|
+
await client.putCodeTemplateLibraries(librariesToSend(local, remote, scope, plan));
|
|
1987
|
+
librariesSent = true;
|
|
1988
|
+
const sentFromTree = librariesOf(local).filter(
|
|
1989
|
+
(l) => scope.libraries === void 0 || scope.libraries.includes(String(l["name"])) || scope.libraries.includes(String(l["id"]))
|
|
1990
|
+
);
|
|
1991
|
+
for (const l of sentFromTree) touchedIds.add(String(l["id"]));
|
|
1992
|
+
for (const id of inSync) touchedIds.add(id);
|
|
1993
|
+
}
|
|
1994
|
+
} else if (kind === "codeTemplate" && change.op === "delete") {
|
|
1995
|
+
await client.deleteCodeTemplate(change.id);
|
|
1996
|
+
} else if (kind === "codeTemplate") {
|
|
1997
|
+
await client.putCodeTemplate(findTemplate(local, change.id));
|
|
1998
|
+
} else if (kind === "channel" && change.op === "delete") {
|
|
1999
|
+
await client.deleteChannel(change.id);
|
|
2000
|
+
} else if (kind === "channel") {
|
|
2001
|
+
await client.putChannel(
|
|
2002
|
+
await withServerAssociations(client, findChannel(local, change.id), change.op, findChannel(remote, change.id), opts.force === true)
|
|
2003
|
+
);
|
|
2004
|
+
} else {
|
|
2005
|
+
await client.putGlobalScripts(local["globalScripts"]);
|
|
2006
|
+
}
|
|
2007
|
+
} catch (err) {
|
|
2008
|
+
return { applied, failed: { change, error: err instanceof Error ? err.message : String(err) }, touchedIds };
|
|
2009
|
+
}
|
|
2010
|
+
applied.push(change);
|
|
2011
|
+
touchedIds.add(change.id);
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
return { applied, touchedIds };
|
|
2015
|
+
}
|
|
2016
|
+
var ASSOCIATIONS = ["channelTags", "dependentIds", "dependencyIds"];
|
|
2017
|
+
async function withServerAssociations(client, channel, op, planned, force) {
|
|
2018
|
+
if (op !== "update") return channel;
|
|
2019
|
+
const server = await client.getChannel(String(channel["id"]));
|
|
2020
|
+
const [now, then] = [Number(server?.["revision"] ?? 0), Number(planned?.["revision"] ?? 0)];
|
|
2021
|
+
if (!force && now > then) {
|
|
2022
|
+
throw new Error(`changed on the server during the push (revision ${now}, planned against ${then}); pull and try again`);
|
|
2023
|
+
}
|
|
2024
|
+
const serverExport = server?.["exportData"];
|
|
2025
|
+
if (!serverExport) return channel;
|
|
2026
|
+
const exportData = { ...channel["exportData"] ?? {} };
|
|
2027
|
+
for (const key of ASSOCIATIONS) if (key in serverExport) exportData[key] = serverExport[key];
|
|
2028
|
+
return { ...channel, exportData };
|
|
2029
|
+
}
|
|
2030
|
+
async function deployChannels(client, ids, nameOf2) {
|
|
2031
|
+
const failures = [];
|
|
2032
|
+
for (const id of ids) {
|
|
2033
|
+
try {
|
|
2034
|
+
await client.deployChannel(id);
|
|
2035
|
+
} catch (err) {
|
|
2036
|
+
failures.push({ name: nameOf2(id), error: err instanceof Error ? err.message : String(err) });
|
|
2037
|
+
}
|
|
2038
|
+
}
|
|
2039
|
+
return failures;
|
|
2040
|
+
}
|
|
2041
|
+
function copyVersionFields(target, source) {
|
|
2042
|
+
if (!source) return false;
|
|
2043
|
+
let changed = false;
|
|
2044
|
+
for (const key of ["revision", "lastModified"]) {
|
|
2045
|
+
if (key in source && JSON.stringify(target[key]) !== JSON.stringify(source[key])) {
|
|
2046
|
+
target[key] = source[key];
|
|
2047
|
+
changed = true;
|
|
2048
|
+
}
|
|
2049
|
+
}
|
|
2050
|
+
const tm = target["exportData"]?.["metadata"];
|
|
2051
|
+
const sm = source["exportData"]?.["metadata"];
|
|
2052
|
+
if (tm && sm && "lastModified" in sm && JSON.stringify(tm["lastModified"]) !== JSON.stringify(sm["lastModified"])) {
|
|
2053
|
+
tm["lastModified"] = sm["lastModified"];
|
|
2054
|
+
changed = true;
|
|
2055
|
+
}
|
|
2056
|
+
return changed;
|
|
2057
|
+
}
|
|
2058
|
+
async function jsonFiles(dir, name) {
|
|
2059
|
+
if (!existsSync2(dir)) return [];
|
|
2060
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
2061
|
+
return entries.filter((e) => e.isDirectory()).map((e) => path2.join(dir, e.name, name)).filter((f) => existsSync2(f));
|
|
2062
|
+
}
|
|
2063
|
+
async function refreshRevisions(root, server, ids) {
|
|
2064
|
+
for (const file of await jsonFiles(path2.join(root, "channels"), "channel.json")) {
|
|
2065
|
+
const json = await readJson(file);
|
|
2066
|
+
if (ids.has(String(json["id"])) && copyVersionFields(json, findChannel(server, String(json["id"])))) {
|
|
2067
|
+
await writeFile2(file, JSON.stringify(json, null, 2));
|
|
2068
|
+
}
|
|
2069
|
+
}
|
|
2070
|
+
const serverLibs = new Map(librariesOf(server).map((l) => [String(l["id"]), l]));
|
|
2071
|
+
for (const file of await jsonFiles(path2.join(root, "codeTemplates"), "library.json")) {
|
|
2072
|
+
const json = await readJson(file);
|
|
2073
|
+
let changed = ids.has(String(json["id"])) && copyVersionFields(json, serverLibs.get(String(json["id"])));
|
|
2074
|
+
const container = json["codeTemplates"];
|
|
2075
|
+
for (const t of list(container?.["codeTemplate"])) {
|
|
2076
|
+
if (ids.has(String(t["id"])) && copyVersionFields(t, findTemplate(server, String(t["id"])))) changed = true;
|
|
2077
|
+
}
|
|
2078
|
+
if (changed) await writeFile2(file, JSON.stringify(json, null, 2));
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
|
|
2082
|
+
// src/secrets/envfile.ts
|
|
2083
|
+
import { randomBytes } from "crypto";
|
|
2084
|
+
import { existsSync as existsSync3 } from "fs";
|
|
2085
|
+
import { appendFile, chmod, copyFile, mkdir as mkdir2, readFile as readFile3, readdir as readdir2, realpath as realpath2, rename, rm, writeFile as writeFile3 } from "fs/promises";
|
|
2086
|
+
import * as path3 from "path";
|
|
2087
|
+
import { parse } from "dotenv";
|
|
2088
|
+
var BASE64_PREFIX = "cv-base64:";
|
|
2089
|
+
function parseEnv(text) {
|
|
2090
|
+
const out = parse(text);
|
|
2091
|
+
for (const [k, v] of Object.entries(out)) {
|
|
2092
|
+
if (v.startsWith(BASE64_PREFIX)) out[k] = Buffer.from(v.slice(BASE64_PREFIX.length), "base64").toString("utf8");
|
|
2093
|
+
}
|
|
2094
|
+
return out;
|
|
2095
|
+
}
|
|
2096
|
+
async function readEnvFile(file) {
|
|
2097
|
+
if (!existsSync3(file)) return {};
|
|
2098
|
+
return parseEnv(await readFile3(file, "utf8"));
|
|
2099
|
+
}
|
|
2100
|
+
function formatValue(value) {
|
|
2101
|
+
const candidates = [
|
|
2102
|
+
/^[\w@%+=:,./-]*$/.test(value) && !value.startsWith(BASE64_PREFIX) ? value : null,
|
|
2103
|
+
value.includes("'") ? null : `'${value}'`,
|
|
2104
|
+
value.includes("`") ? null : `\`${value}\``,
|
|
2105
|
+
value.includes('"') ? null : `"${value.replace(/\n/g, "\\n").replace(/\r/g, "\\r")}"`
|
|
2106
|
+
];
|
|
2107
|
+
for (const c of candidates) {
|
|
2108
|
+
if (c !== null && parseEnv(`K=${c}`)["K"] === value) return c;
|
|
2109
|
+
}
|
|
2110
|
+
return `${BASE64_PREFIX}${Buffer.from(value, "utf8").toString("base64")}`;
|
|
2111
|
+
}
|
|
2112
|
+
async function updateEnvFile(file, updates) {
|
|
2113
|
+
const names = Object.keys(updates);
|
|
2114
|
+
if (names.length === 0) return;
|
|
2115
|
+
const existing = existsSync3(file) ? await readFile3(file, "utf8") : "";
|
|
2116
|
+
const lines = existing === "" ? [] : existing.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");
|
|
2117
|
+
const written = /* @__PURE__ */ new Set();
|
|
2118
|
+
const out = [];
|
|
2119
|
+
let inQuote = null;
|
|
2120
|
+
let dropping = false;
|
|
2121
|
+
for (const line of lines) {
|
|
2122
|
+
if (inQuote !== null) {
|
|
2123
|
+
if (!dropping) out.push(line);
|
|
2124
|
+
if (line.includes(inQuote)) [inQuote, dropping] = [null, false];
|
|
2125
|
+
continue;
|
|
2126
|
+
}
|
|
2127
|
+
const m = /^\s*(?:export\s+)?([\w.-]+)\s*=\s*(.*)$/.exec(line);
|
|
2128
|
+
const q = m?.[2][0];
|
|
2129
|
+
const opens = (q === '"' || q === "'" || q === "`") && m[2].lastIndexOf(q) === 0 ? q : null;
|
|
2130
|
+
if (m && Object.prototype.hasOwnProperty.call(updates, m[1])) {
|
|
2131
|
+
if (!written.has(m[1])) {
|
|
2132
|
+
out.push(`${m[1]}=${formatValue(updates[m[1]])}`);
|
|
2133
|
+
written.add(m[1]);
|
|
2134
|
+
}
|
|
2135
|
+
if (opens) [inQuote, dropping] = [opens, true];
|
|
2136
|
+
continue;
|
|
2137
|
+
}
|
|
2138
|
+
out.push(line);
|
|
2139
|
+
if (opens) inQuote = opens;
|
|
2140
|
+
}
|
|
2141
|
+
for (const name of names) {
|
|
2142
|
+
if (!written.has(name)) out.push(`${name}=${formatValue(updates[name])}`);
|
|
2143
|
+
}
|
|
2144
|
+
const text = `${out.join("\n")}
|
|
2145
|
+
`;
|
|
2146
|
+
const readBack = parseEnv(text);
|
|
2147
|
+
const wrong = names.filter((n) => readBack[n] !== updates[n]);
|
|
2148
|
+
if (wrong.length > 0) throw new Error(`env file update would not read back correctly for ${wrong.join(", ")}; nothing written`);
|
|
2149
|
+
const target = existsSync3(file) ? await realpath2(file) : file;
|
|
2150
|
+
const temp = `${target}.${process.pid}-${randomBytes(4).toString("hex")}.tmp`;
|
|
2151
|
+
try {
|
|
2152
|
+
await writeFile3(temp, text, { encoding: "utf8", mode: 384 });
|
|
2153
|
+
await rename(temp, target);
|
|
2154
|
+
} catch (err) {
|
|
2155
|
+
await rm(temp, { force: true });
|
|
2156
|
+
throw err;
|
|
2157
|
+
}
|
|
2158
|
+
}
|
|
2159
|
+
var ENV_BACKUPS_KEPT = 5;
|
|
2160
|
+
async function backupEnvFile(file, updates, dir) {
|
|
2161
|
+
if (!existsSync3(file)) return null;
|
|
2162
|
+
const current = parseEnv(await readFile3(file, "utf8"));
|
|
2163
|
+
if (!Object.entries(updates).some(([k, v]) => current[k] !== void 0 && current[k] !== v)) return null;
|
|
2164
|
+
await mkdir2(dir, { recursive: true });
|
|
2165
|
+
const prefix = `${path3.basename(file)}-`;
|
|
2166
|
+
const stamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "");
|
|
2167
|
+
let target = path3.join(dir, `${prefix}${stamp2}`);
|
|
2168
|
+
for (let n = 2; existsSync3(target); n += 1) target = path3.join(dir, `${prefix}${stamp2}-${String(n).padStart(2, "0")}`);
|
|
2169
|
+
await copyFile(file, target);
|
|
2170
|
+
await chmod(target, 384);
|
|
2171
|
+
const others = (await readdir2(dir)).filter((f) => f.startsWith(prefix) && f !== path3.basename(target)).sort();
|
|
2172
|
+
for (const old of others.slice(0, Math.max(0, others.length - (ENV_BACKUPS_KEPT - 1)))) {
|
|
2173
|
+
await rm(path3.join(dir, old));
|
|
2174
|
+
}
|
|
2175
|
+
return target;
|
|
2176
|
+
}
|
|
2177
|
+
var IGNORE_LINES = [".env", ".env.*", "!.env.example", ".secrets/"];
|
|
2178
|
+
async function ensureEnvIgnored(dir, envFile) {
|
|
2179
|
+
const file = path3.join(dir, ".gitignore");
|
|
2180
|
+
const text = existsSync3(file) ? await readFile3(file, "utf8") : "";
|
|
2181
|
+
const present = new Set(text.split(/\r?\n/).map((l) => l.trim()));
|
|
2182
|
+
const wanted = [...IGNORE_LINES];
|
|
2183
|
+
if (envFile) {
|
|
2184
|
+
const rel = path3.relative(dir, envFile).split(path3.sep).join("/");
|
|
2185
|
+
const base = path3.basename(envFile);
|
|
2186
|
+
const covered = !rel.includes("/") && (base === ".env" || base.startsWith(".env.") && base !== ".env.example");
|
|
2187
|
+
if (!covered && !rel.startsWith("..") && !path3.isAbsolute(rel)) wanted.push(`/${rel}`);
|
|
2188
|
+
}
|
|
2189
|
+
const missing = wanted.filter((l) => !present.has(l));
|
|
2190
|
+
if (missing.length === 0) return false;
|
|
2191
|
+
const prefix = text === "" || text.endsWith("\n") ? "" : "\n";
|
|
2192
|
+
await appendFile(file, `${prefix}# channelvault: secrets and per-environment values
|
|
2193
|
+
${missing.join("\n")}
|
|
2194
|
+
`);
|
|
2195
|
+
return true;
|
|
2196
|
+
}
|
|
2197
|
+
|
|
2198
|
+
// src/backup/index.ts
|
|
2199
|
+
import { randomBytes as randomBytes2 } from "crypto";
|
|
2200
|
+
import { existsSync as existsSync4, realpathSync } from "fs";
|
|
2201
|
+
import { mkdir as mkdir3, readdir as readdir3, readFile as readFile4, rename as rename2, rm as rm2, writeFile as writeFile4 } from "fs/promises";
|
|
2202
|
+
import * as path4 from "path";
|
|
2203
|
+
var DEFAULT_BACKUP_DIR = ".backup";
|
|
2204
|
+
var DEFAULT_KEEP = 10;
|
|
2205
|
+
var FILE_NAME = /^(.+)-(\d{8}T\d{6}Z)(?:-(\d+))?\.xml$/;
|
|
2206
|
+
function serverSlug(name) {
|
|
2207
|
+
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
2208
|
+
}
|
|
2209
|
+
function backupName(config, fallback) {
|
|
2210
|
+
return configuredName(config) || serverSlug(fallback) || "mirth";
|
|
2211
|
+
}
|
|
2212
|
+
function configuredName(config) {
|
|
2213
|
+
const settings = config["serverSettings"];
|
|
2214
|
+
const field = (key) => {
|
|
2215
|
+
const v = settings !== null && typeof settings === "object" && !Array.isArray(settings) ? settings[key] : void 0;
|
|
2216
|
+
return typeof v === "string" ? serverSlug(v) : "";
|
|
2217
|
+
};
|
|
2218
|
+
return field("serverName") || field("environmentName");
|
|
2219
|
+
}
|
|
2220
|
+
function stamp(date) {
|
|
2221
|
+
return date.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
|
|
2222
|
+
}
|
|
2223
|
+
async function listBackups(dir) {
|
|
2224
|
+
if (!existsSync4(dir)) return [];
|
|
2225
|
+
const out = [];
|
|
2226
|
+
for (const name of await readdir3(dir)) {
|
|
2227
|
+
const m = FILE_NAME.exec(name);
|
|
2228
|
+
if (m) out.push({ file: path4.join(dir, name), server: m[1], stamp: m[2], seq: m[3] ? Number(m[3]) : 1 });
|
|
2229
|
+
}
|
|
2230
|
+
return out.sort((a, b) => a.stamp.localeCompare(b.stamp) || a.seq - b.seq);
|
|
2231
|
+
}
|
|
2232
|
+
var MANIFEST = "channelvault-backups.json";
|
|
2233
|
+
async function readManifest(dir) {
|
|
2234
|
+
const file = path4.join(dir, MANIFEST);
|
|
2235
|
+
if (!existsSync4(file)) return {};
|
|
2236
|
+
try {
|
|
2237
|
+
const parsed = JSON.parse(await readFile4(file, "utf8"));
|
|
2238
|
+
return parsed.files ?? {};
|
|
2239
|
+
} catch (err) {
|
|
2240
|
+
throw new Error(`${file}: ${err instanceof Error ? err.message : String(err)}; restore it from a copy or delete it`);
|
|
2241
|
+
}
|
|
2242
|
+
}
|
|
2243
|
+
async function writeManifest(dir, files) {
|
|
2244
|
+
const present = Object.fromEntries(Object.entries(files).filter(([name]) => existsSync4(path4.join(dir, name))));
|
|
2245
|
+
await writePrivate(path4.join(dir, MANIFEST), `${JSON.stringify({ version: 1, files: present }, null, 2)}
|
|
2246
|
+
`);
|
|
2247
|
+
}
|
|
2248
|
+
async function backupsOf(dir, serverId) {
|
|
2249
|
+
const manifest = await readManifest(dir);
|
|
2250
|
+
return (await listBackups(dir)).filter((b) => manifest[path4.basename(b.file)]?.serverId === serverId);
|
|
2251
|
+
}
|
|
2252
|
+
async function originOf(dir, file) {
|
|
2253
|
+
if (!existsSync4(dir) || !sameFile(path4.dirname(file), dir)) return null;
|
|
2254
|
+
return (await readManifest(dir))[path4.basename(file)] ?? null;
|
|
2255
|
+
}
|
|
2256
|
+
async function originsIn(dir) {
|
|
2257
|
+
if (!existsSync4(dir)) return [];
|
|
2258
|
+
const seen = /* @__PURE__ */ new Map();
|
|
2259
|
+
for (const o of Object.values(await readManifest(dir))) seen.set(o.serverId, o);
|
|
2260
|
+
return [...seen.values()];
|
|
2261
|
+
}
|
|
2262
|
+
async function saveBackup(dir, name, xml2, opts) {
|
|
2263
|
+
await ensureBackupDir(dir);
|
|
2264
|
+
const manifest = await readManifest(dir);
|
|
2265
|
+
const base = `${name}-${stamp(opts.now ?? /* @__PURE__ */ new Date())}`;
|
|
2266
|
+
let file = path4.join(dir, `${base}.xml`);
|
|
2267
|
+
for (let n = 2; existsSync4(file); n += 1) file = path4.join(dir, `${base}-${n}.xml`);
|
|
2268
|
+
await writePrivate(file, xml2);
|
|
2269
|
+
manifest[path4.basename(file)] = opts.origin;
|
|
2270
|
+
await writeManifest(dir, manifest);
|
|
2271
|
+
const mine = (await listBackups(dir)).filter((b) => manifest[path4.basename(b.file)]?.serverId === opts.origin.serverId);
|
|
2272
|
+
for (const old of mine.slice(0, Math.max(0, mine.length - opts.keep))) {
|
|
2273
|
+
if (sameFile(old.file, file) || opts.protect !== void 0 && sameFile(old.file, opts.protect)) continue;
|
|
2274
|
+
await rm2(old.file);
|
|
2275
|
+
}
|
|
2276
|
+
await writeManifest(dir, manifest);
|
|
2277
|
+
return file;
|
|
2278
|
+
}
|
|
2279
|
+
function sameFile(a, b) {
|
|
2280
|
+
const real = (p) => {
|
|
2281
|
+
const resolved = existsSync4(p) ? realpathSync.native(p) : path4.resolve(p);
|
|
2282
|
+
return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
|
|
2283
|
+
};
|
|
2284
|
+
return real(a) === real(b);
|
|
2285
|
+
}
|
|
2286
|
+
async function ensureBackupDir(dir) {
|
|
2287
|
+
if (existsSync4(dir)) return;
|
|
2288
|
+
await mkdir3(dir, { recursive: true });
|
|
2289
|
+
await writeFile4(path4.join(dir, ".gitignore"), "# channelvault backups hold credentials in plain text\n*\n");
|
|
2290
|
+
}
|
|
2291
|
+
async function writePrivate(file, text) {
|
|
2292
|
+
const temp = `${file}.${process.pid}-${randomBytes2(4).toString("hex")}.tmp`;
|
|
2293
|
+
try {
|
|
2294
|
+
await writeFile4(temp, text, { encoding: "utf8", mode: 384 });
|
|
2295
|
+
await rename2(temp, file);
|
|
2296
|
+
} catch (err) {
|
|
2297
|
+
await rm2(temp, { force: true });
|
|
2298
|
+
throw err;
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
2301
|
+
function numericVersion(v) {
|
|
2302
|
+
const m = /^\d+(?:\.\d+)*/.exec(v.trim());
|
|
2303
|
+
return m ? m[0].split(".").map(Number) : null;
|
|
2304
|
+
}
|
|
2305
|
+
function compareVersions(a, b) {
|
|
2306
|
+
const pa = numericVersion(a);
|
|
2307
|
+
const pb = numericVersion(b);
|
|
2308
|
+
for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {
|
|
2309
|
+
const d = (pa[i] ?? 0) - (pb[i] ?? 0);
|
|
2310
|
+
if (d !== 0) return d;
|
|
2311
|
+
}
|
|
2312
|
+
return 0;
|
|
2313
|
+
}
|
|
2314
|
+
|
|
2315
|
+
// src/cli.ts
|
|
2316
|
+
var engine = createExplodeEngine();
|
|
2317
|
+
var xml = new XmlConfigAdapter();
|
|
2318
|
+
var VERSION = createRequire(import.meta.url)("../package.json").version;
|
|
2319
|
+
var CliError = class extends Error {
|
|
2320
|
+
};
|
|
2321
|
+
function fail(message) {
|
|
2322
|
+
throw new CliError(message);
|
|
2323
|
+
}
|
|
2324
|
+
var errorExitCode = 1;
|
|
2325
|
+
var MANAGED_DIRS = ["server", "channels", "codeTemplates", "channelGroups"];
|
|
2326
|
+
var STAGING_DIR = ".channelvault-staging";
|
|
2327
|
+
var RM_OPTS = { recursive: true, force: true, maxRetries: 5, retryDelay: 50 };
|
|
2328
|
+
function resolveClientConfig(flags) {
|
|
2329
|
+
const host = flags.host ?? process.env.MIRTH_HOST;
|
|
2330
|
+
const portStr = flags.port ?? process.env.MIRTH_PORT;
|
|
2331
|
+
const username = flags.user ?? process.env.MIRTH_USER;
|
|
2332
|
+
const password = flags.pass ?? process.env.MIRTH_PASS;
|
|
2333
|
+
if (!host) fail("no server host (pass --host or set MIRTH_HOST)");
|
|
2334
|
+
if (!portStr) fail("no server port (pass --port or set MIRTH_PORT)");
|
|
2335
|
+
if (!username) fail("no username (pass --user or set MIRTH_USER)");
|
|
2336
|
+
if (password == null) fail("no password (pass --pass or set MIRTH_PASS)");
|
|
2337
|
+
const port = Number(portStr);
|
|
2338
|
+
if (!Number.isInteger(port)) fail(`invalid port: ${portStr}`);
|
|
2339
|
+
return {
|
|
2340
|
+
host,
|
|
2341
|
+
port,
|
|
2342
|
+
username,
|
|
2343
|
+
password,
|
|
2344
|
+
https: flags.https !== false,
|
|
2345
|
+
disableTlsCheck: flags.insecure === true,
|
|
2346
|
+
// Opt-in: error bodies can echo credentials (see `scrub`, applied to all output).
|
|
2347
|
+
includeResponseBodies: Boolean(process.env.CHANNELVAULT_DEBUG)
|
|
2348
|
+
};
|
|
2349
|
+
}
|
|
2350
|
+
function addConnectionFlags(cmd) {
|
|
2351
|
+
return cmd.option("--host <host>", "Mirth server host (env MIRTH_HOST)").option("--port <port>", "Mirth server port (env MIRTH_PORT)").option("--user <user>", "username (env MIRTH_USER)").option("--pass <pass>", "password (env MIRTH_PASS)").option("--insecure", "allow self-signed TLS certificates", false).option("--no-https", "use http instead of https");
|
|
2352
|
+
}
|
|
2353
|
+
async function withClient(flags, fn) {
|
|
2354
|
+
const client = createMirthClient(resolveClientConfig(flags));
|
|
2355
|
+
try {
|
|
2356
|
+
await client.login();
|
|
2357
|
+
return await fn(client);
|
|
2358
|
+
} finally {
|
|
2359
|
+
await client.logout().catch(() => void 0);
|
|
2360
|
+
await client.close().catch(() => void 0);
|
|
2361
|
+
}
|
|
2362
|
+
}
|
|
2363
|
+
function addBackupDirFlags(cmd) {
|
|
2364
|
+
return cmd.option("--backup-dir <dir>", `where backups are kept (default ./${DEFAULT_BACKUP_DIR})`).option("--keep <n>", `backups kept per server (default ${DEFAULT_KEEP})`);
|
|
2365
|
+
}
|
|
2366
|
+
function backupDirOf(flags) {
|
|
2367
|
+
return path5.resolve(flags.backupDir ?? DEFAULT_BACKUP_DIR);
|
|
2368
|
+
}
|
|
2369
|
+
function keepOf(flags) {
|
|
2370
|
+
if (flags.keep === void 0) return DEFAULT_KEEP;
|
|
2371
|
+
const n = Number(flags.keep);
|
|
2372
|
+
if (!Number.isInteger(n) || n < 1) fail(`--keep must be a whole number of at least 1, not ${flags.keep}`);
|
|
2373
|
+
return n;
|
|
2374
|
+
}
|
|
2375
|
+
function serverNameOf(config, flags) {
|
|
2376
|
+
const cfg = resolveClientConfig(flags);
|
|
2377
|
+
return backupName(config, `${cfg.host}-${cfg.port}`);
|
|
2378
|
+
}
|
|
2379
|
+
function parseBackup(text, where) {
|
|
2380
|
+
try {
|
|
2381
|
+
return xml.parse(text);
|
|
2382
|
+
} catch (err) {
|
|
2383
|
+
fail(`${where}: ${err instanceof Error ? err.message : String(err)}`);
|
|
2384
|
+
}
|
|
2385
|
+
}
|
|
2386
|
+
async function saveServerBackup(client, text, flags, protect) {
|
|
2387
|
+
const config = parseBackup(text, "the server configuration");
|
|
2388
|
+
const origin = { serverId: await client.getServerId(), host: hostOf(flags) };
|
|
2389
|
+
const file = await saveBackup(backupDirOf(flags), serverNameOf(config, flags), text, { keep: keepOf(flags), origin, protect });
|
|
2390
|
+
if (gitWouldCommit(file)) {
|
|
2391
|
+
process.stderr.write(`warning: git does not ignore ${file}, which holds credentials in plain text; add it to .gitignore
|
|
2392
|
+
`);
|
|
2393
|
+
}
|
|
2394
|
+
return file;
|
|
2395
|
+
}
|
|
2396
|
+
async function backupBeforePush(client, flags) {
|
|
2397
|
+
if (flags.backup === false) return;
|
|
2398
|
+
const file = await saveServerBackup(client, await client.getServerConfigurationXml(), flags);
|
|
2399
|
+
process.stdout.write(`backed up the server to ${file} (undo with: channelvault restore "${file}")
|
|
2400
|
+
`);
|
|
2401
|
+
}
|
|
2402
|
+
function hostOf(flags) {
|
|
2403
|
+
const cfg = resolveClientConfig(flags);
|
|
2404
|
+
return `${cfg.host}:${cfg.port}`;
|
|
2405
|
+
}
|
|
2406
|
+
async function confirm(question) {
|
|
2407
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
2408
|
+
const controller = new AbortController();
|
|
2409
|
+
rl.once("close", () => controller.abort());
|
|
2410
|
+
rl.once("SIGINT", () => controller.abort());
|
|
2411
|
+
try {
|
|
2412
|
+
const answer = (await rl.question(`${question} [y/N] `, { signal: controller.signal })).trim().toLowerCase();
|
|
2413
|
+
return answer === "y" || answer === "yes";
|
|
2414
|
+
} catch (err) {
|
|
2415
|
+
if (controller.signal.aborted) fail("confirmation interrupted; nothing was pushed");
|
|
2416
|
+
throw err;
|
|
2417
|
+
} finally {
|
|
2418
|
+
rl.close();
|
|
2419
|
+
}
|
|
2420
|
+
}
|
|
2421
|
+
function summarize(config) {
|
|
2422
|
+
const asArray2 = (v) => Array.isArray(v) ? v : v == null ? [] : [v];
|
|
2423
|
+
const channels = asArray2(config.channels?.channel);
|
|
2424
|
+
const libraries = asArray2(
|
|
2425
|
+
config.codeTemplateLibraries?.codeTemplateLibrary
|
|
2426
|
+
);
|
|
2427
|
+
const groups = asArray2(config.channelGroups?.channelGroup);
|
|
2428
|
+
let codeTemplates = 0;
|
|
2429
|
+
for (const lib of libraries) {
|
|
2430
|
+
if (lib && typeof lib === "object" && !Array.isArray(lib)) {
|
|
2431
|
+
const cts = lib.codeTemplates?.codeTemplate;
|
|
2432
|
+
codeTemplates += asArray2(cts).length;
|
|
2433
|
+
}
|
|
2434
|
+
}
|
|
2435
|
+
return {
|
|
2436
|
+
channels: channels.length,
|
|
2437
|
+
channelGroups: groups.length,
|
|
2438
|
+
codeTemplateLibraries: libraries.length,
|
|
2439
|
+
codeTemplates
|
|
2440
|
+
};
|
|
2441
|
+
}
|
|
2442
|
+
async function writeMeta(root, source, config, previous) {
|
|
2443
|
+
const meta = {
|
|
2444
|
+
tool: "channelvault",
|
|
2445
|
+
version: VERSION,
|
|
2446
|
+
source,
|
|
2447
|
+
pulledAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2448
|
+
// XML adapter yields `@_version`; the live JSON API yields `@version` (Jackson).
|
|
2449
|
+
engineVersion: typeof config["@_version"] === "string" ? config["@_version"] : typeof config["@version"] === "string" ? config["@version"] : null,
|
|
2450
|
+
resources: resourceIds(config)
|
|
2451
|
+
};
|
|
2452
|
+
const file = path5.join(root, "channelvault.json");
|
|
2453
|
+
if (previous && JSON.stringify({ ...previous, pulledAt: "" }) === JSON.stringify({ ...meta, pulledAt: "" })) return;
|
|
2454
|
+
await writeFile5(file, JSON.stringify(meta, null, 2) + "\n", "utf8");
|
|
2455
|
+
}
|
|
2456
|
+
function envFilePath(root, flags) {
|
|
2457
|
+
return flags.dotenv ? path5.resolve(flags.dotenv) : path5.join(root, ".env");
|
|
2458
|
+
}
|
|
2459
|
+
async function loadEnv(file) {
|
|
2460
|
+
return { ...await readEnvFile(file), ...process.env };
|
|
2461
|
+
}
|
|
2462
|
+
function addEnvFlag(cmd) {
|
|
2463
|
+
return cmd.option("--dotenv <path>", "env file holding secrets and per-environment values (default <dir>/.env)");
|
|
2464
|
+
}
|
|
2465
|
+
function addExtractFlag(cmd) {
|
|
2466
|
+
return cmd.option("--extract-secrets", "move secrets found inside values (URLs, scripts, headers) to the env file", false);
|
|
2467
|
+
}
|
|
2468
|
+
async function existingTree(root) {
|
|
2469
|
+
return existsSync5(path5.join(root, "server", "configuration.json")) ? engine.implode({ root }) : null;
|
|
2470
|
+
}
|
|
2471
|
+
async function renderedTree(root, flags) {
|
|
2472
|
+
const tree = await engine.implode({ root });
|
|
2473
|
+
const env = await loadEnv(envFilePath(root, flags));
|
|
2474
|
+
rememberSecrets(tree, env);
|
|
2475
|
+
return render(tree, env);
|
|
2476
|
+
}
|
|
2477
|
+
var knownSecrets = /* @__PURE__ */ new Set();
|
|
2478
|
+
function rememberSecrets(tree, env) {
|
|
2479
|
+
mapLeaves(tree, (value) => {
|
|
2480
|
+
for (const m of value.matchAll(/\{\{env:([A-Za-z_][A-Za-z0-9_]*)\}\}/g)) {
|
|
2481
|
+
const secret = env[m[1]];
|
|
2482
|
+
if (secret !== void 0 && secret.length >= 4) knownSecrets.add(secret);
|
|
2483
|
+
}
|
|
2484
|
+
return value;
|
|
2485
|
+
});
|
|
2486
|
+
}
|
|
2487
|
+
function scrub(text) {
|
|
2488
|
+
const forms = [...knownSecrets].flatMap((s) => [
|
|
2489
|
+
s,
|
|
2490
|
+
JSON.stringify(s).slice(1, -1),
|
|
2491
|
+
s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'"),
|
|
2492
|
+
encodeURIComponent(s)
|
|
2493
|
+
]);
|
|
2494
|
+
return [...new Set(forms)].sort((a, b) => b.length - a.length).reduce((t, s) => t.split(s).join("<redacted>"), text);
|
|
2495
|
+
}
|
|
2496
|
+
var ALLOW_FILE = "channelvault.allow.json";
|
|
2497
|
+
async function readAllow(root) {
|
|
2498
|
+
const file = path5.join(root, ALLOW_FILE);
|
|
2499
|
+
if (!existsSync5(file)) return [];
|
|
2500
|
+
const parsed = await readJson(file);
|
|
2501
|
+
return parsed.ignore ?? [];
|
|
2502
|
+
}
|
|
2503
|
+
async function writeTree(root, fetched, source, flags) {
|
|
2504
|
+
const envFile = envFilePath(root, flags);
|
|
2505
|
+
const previousMeta = await preflightTree(root, envFile);
|
|
2506
|
+
const env = await loadEnv(envFile);
|
|
2507
|
+
const templated = templatize(fetched, await existingTree(root), env);
|
|
2508
|
+
const scan = scanSecrets(templated.config, {
|
|
2509
|
+
mode: flags.extractSecrets ? "extract" : "find",
|
|
2510
|
+
allow: await readAllow(root),
|
|
2511
|
+
env: { ...env, ...templated.envUpdates }
|
|
2512
|
+
});
|
|
2513
|
+
if (scan.findings.length > 0 && !flags.extractSecrets) {
|
|
2514
|
+
fail(
|
|
2515
|
+
`found ${scan.findings.length} possible secret(s) that would be stored in plain text; nothing was written:
|
|
2516
|
+
${formatFindings(scan.findings)}
|
|
2517
|
+
Rerun with --extract-secrets to move them to ${envFile}, or list false positives in ${ALLOW_FILE}.`
|
|
2518
|
+
);
|
|
2519
|
+
}
|
|
2520
|
+
const config = scan.config;
|
|
2521
|
+
const envUpdates = { ...templated.envUpdates, ...scan.envUpdates };
|
|
2522
|
+
rememberSecrets(config, { ...env, ...envUpdates });
|
|
2523
|
+
const echoes = findEchoes(config, { ...await readEnvFile(envFile), ...envUpdates });
|
|
2524
|
+
await mkdir4(root, { recursive: true });
|
|
2525
|
+
await mkdir4(path5.dirname(envFile), { recursive: true });
|
|
2526
|
+
const rel = path5.relative(root, envFile);
|
|
2527
|
+
const envInTree = !rel.startsWith("..") && !path5.isAbsolute(rel);
|
|
2528
|
+
const backup = await backupEnvFile(envFile, envUpdates, path5.join(root, ".secrets"));
|
|
2529
|
+
if (backup || envInTree && Object.keys(envUpdates).length > 0) await ensureEnvIgnored(root, envInTree ? envFile : void 0);
|
|
2530
|
+
await updateEnvFile(envFile, envUpdates);
|
|
2531
|
+
await replaceTree(root, config);
|
|
2532
|
+
await writeMeta(root, source, fetched, previousMeta);
|
|
2533
|
+
if (scan.findings.length > 0) process.stdout.write(`extracted ${scan.findings.length} secret(s) found in values
|
|
2534
|
+
`);
|
|
2535
|
+
const updated = Object.keys(envUpdates).length;
|
|
2536
|
+
if (updated > 0) process.stdout.write(`stored ${updated} secret value(s) in ${envFile}
|
|
2537
|
+
`);
|
|
2538
|
+
if (backup) process.stdout.write(`previous env file kept as ${backup}
|
|
2539
|
+
`);
|
|
2540
|
+
for (const note of templated.notes) process.stderr.write(`note: ${note}
|
|
2541
|
+
`);
|
|
2542
|
+
for (const e of echoes) {
|
|
2543
|
+
process.stderr.write(`warning: the value of ${e.name} also appears in plain text at ${e.where}
|
|
2544
|
+
`);
|
|
2545
|
+
}
|
|
2546
|
+
if (existsSync5(envFile) && gitWouldCommit(envFile)) {
|
|
2547
|
+
process.stderr.write(`warning: git does not ignore ${envFile}, so its secret values could be committed; add it to .gitignore
|
|
2548
|
+
`);
|
|
2549
|
+
}
|
|
2550
|
+
}
|
|
2551
|
+
function gitWouldCommit(file) {
|
|
2552
|
+
const r = spawnSync("git", ["check-ignore", "-q", path5.basename(file)], { cwd: path5.dirname(file) });
|
|
2553
|
+
return r.status === 1;
|
|
2554
|
+
}
|
|
2555
|
+
async function resolvedPath(p) {
|
|
2556
|
+
const abs = path5.resolve(p);
|
|
2557
|
+
let existing = abs;
|
|
2558
|
+
while (!existsSync5(existing) && path5.dirname(existing) !== existing) existing = path5.dirname(existing);
|
|
2559
|
+
return path5.join(await realpath3(existing), path5.relative(existing, abs));
|
|
2560
|
+
}
|
|
2561
|
+
function isWithin(child, parent) {
|
|
2562
|
+
const norm = (p) => process.platform === "win32" ? p.toLowerCase() : p;
|
|
2563
|
+
const rel = path5.relative(norm(parent), norm(child));
|
|
2564
|
+
return rel === "" || rel !== ".." && !rel.startsWith(`..${path5.sep}`) && !path5.isAbsolute(rel);
|
|
2565
|
+
}
|
|
2566
|
+
async function preflightTree(root, envFile) {
|
|
2567
|
+
const [realRoot, realEnv] = await Promise.all([resolvedPath(root), resolvedPath(envFile)]);
|
|
2568
|
+
const doomed = [...MANAGED_DIRS, STAGING_DIR].find(
|
|
2569
|
+
(d) => isWithin(path5.resolve(envFile), path5.resolve(root, d)) || isWithin(realEnv, path5.join(realRoot, d))
|
|
2570
|
+
);
|
|
2571
|
+
if (doomed) fail(`the env file ${envFile} is inside ${doomed}/, which this command replaces; keep it elsewhere`);
|
|
2572
|
+
const metaPath = path5.join(root, "channelvault.json");
|
|
2573
|
+
if (existsSync5(metaPath)) {
|
|
2574
|
+
let meta;
|
|
2575
|
+
try {
|
|
2576
|
+
meta = await readJson(metaPath);
|
|
2577
|
+
} catch (err) {
|
|
2578
|
+
meta = err;
|
|
2579
|
+
}
|
|
2580
|
+
if (meta === null || typeof meta !== "object" || Array.isArray(meta) || meta instanceof Error || typeof meta.source !== "string") {
|
|
2581
|
+
fail(
|
|
2582
|
+
`${metaPath} is unreadable or not channelvault metadata${meta instanceof Error ? ` (${meta.message})` : ""}; nothing was written. Restore it (for example \`git checkout -- channelvault.json\`) and retry.`
|
|
2583
|
+
);
|
|
2584
|
+
}
|
|
2585
|
+
return meta;
|
|
2586
|
+
}
|
|
2587
|
+
const foreign = MANAGED_DIRS.filter((d) => existsSync5(path5.join(root, d)));
|
|
2588
|
+
if (foreign.length > 0) {
|
|
2589
|
+
fail(
|
|
2590
|
+
`${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).`
|
|
2591
|
+
);
|
|
2592
|
+
}
|
|
2593
|
+
return null;
|
|
2594
|
+
}
|
|
2595
|
+
async function replaceTree(root, config) {
|
|
2596
|
+
const staging = path5.join(root, STAGING_DIR);
|
|
2597
|
+
await rm3(staging, RM_OPTS);
|
|
2598
|
+
try {
|
|
2599
|
+
await engine.explode(config, { root: staging });
|
|
2600
|
+
for (const d of MANAGED_DIRS) {
|
|
2601
|
+
await rm3(path5.join(root, d), RM_OPTS);
|
|
2602
|
+
if (existsSync5(path5.join(staging, d))) await rename3(path5.join(staging, d), path5.join(root, d));
|
|
2603
|
+
}
|
|
2604
|
+
} finally {
|
|
2605
|
+
await rm3(staging, RM_OPTS);
|
|
2606
|
+
}
|
|
2607
|
+
}
|
|
2608
|
+
function assertTree(root) {
|
|
2609
|
+
if (!existsSync5(path5.join(root, "server", "configuration.json"))) {
|
|
2610
|
+
fail(`${root} is not a channelvault tree (missing server/configuration.json). Run 'pull' or 'explode' first.`);
|
|
2611
|
+
}
|
|
2612
|
+
}
|
|
2613
|
+
async function readTreeOrigin(root) {
|
|
2614
|
+
const metaPath = path5.join(root, "channelvault.json");
|
|
2615
|
+
if (!existsSync5(metaPath)) return "unknown";
|
|
2616
|
+
try {
|
|
2617
|
+
const meta = await readJson(metaPath);
|
|
2618
|
+
if (typeof meta.source === "string") {
|
|
2619
|
+
if (meta.source.startsWith("file:")) return "xml";
|
|
2620
|
+
if (/^https?:\/\//i.test(meta.source)) return "live";
|
|
2621
|
+
}
|
|
2622
|
+
} catch {
|
|
2623
|
+
}
|
|
2624
|
+
return "unknown";
|
|
2625
|
+
}
|
|
2626
|
+
function detectConfigShape(config) {
|
|
2627
|
+
if ("@_version" in config) return "xml";
|
|
2628
|
+
if ("@version" in config) return "live";
|
|
2629
|
+
return "unknown";
|
|
2630
|
+
}
|
|
2631
|
+
async function assertCompatibleOrigin(root, config, wants, force) {
|
|
2632
|
+
if (force) return;
|
|
2633
|
+
const origin = await readTreeOrigin(root);
|
|
2634
|
+
const effective = origin !== "unknown" ? origin : detectConfigShape(config);
|
|
2635
|
+
if (effective === "unknown" || effective === wants) return;
|
|
2636
|
+
const msg = wants === "live" ? `this working tree was exploded from an XML backup, but 'push' sends to a live server. The two transports use different config shapes and the normalization bridge is not implemented yet, so pushing would upload a config the Mirth API cannot parse. Seed the tree with 'pull' instead, or pass --ignore-origin to override.` : `this working tree was pulled from a live server, but 'implode' writes a backup XML. The two transports use different config shapes and the normalization bridge is not implemented yet, so imploding would produce malformed XML. Re-create the tree with 'explode' from a backup, or pass --force to override.`;
|
|
2637
|
+
fail(msg);
|
|
2638
|
+
}
|
|
2639
|
+
function collect(value, previous) {
|
|
2640
|
+
return [...previous ?? [], value];
|
|
2641
|
+
}
|
|
2642
|
+
async function readKnown(root) {
|
|
2643
|
+
const metaPath = path5.join(root, "channelvault.json");
|
|
2644
|
+
if (!existsSync5(metaPath)) return void 0;
|
|
2645
|
+
return knownFrom((await readJson(metaPath)).resources);
|
|
2646
|
+
}
|
|
2647
|
+
async function writeKnown(root, known) {
|
|
2648
|
+
const metaPath = path5.join(root, "channelvault.json");
|
|
2649
|
+
if (!existsSync5(metaPath)) return;
|
|
2650
|
+
const meta = await readJson(metaPath);
|
|
2651
|
+
if (!meta.resources) return;
|
|
2652
|
+
meta.resources = known;
|
|
2653
|
+
await writeFile5(metaPath, JSON.stringify(meta, null, 2) + "\n", "utf8");
|
|
2654
|
+
}
|
|
2655
|
+
function printNameChange(incoming, current) {
|
|
2656
|
+
const [to, from] = [configuredName(incoming), configuredName(current)];
|
|
2657
|
+
if (to !== from) process.stdout.write(`server name changes: ${from || "(none)"} -> ${to || "(none)"}
|
|
2658
|
+
`);
|
|
2659
|
+
}
|
|
2660
|
+
function printChanges(plan) {
|
|
2661
|
+
const kindLabel = { channel: "channel", library: "library", codeTemplate: "code template", globalScripts: "" };
|
|
2662
|
+
for (const c of plan.changes) process.stdout.write(` ${c.op.padEnd(6)} ${`${kindLabel[c.kind]} ${c.label}`.trim()}
|
|
2663
|
+
`);
|
|
2664
|
+
}
|
|
2665
|
+
function checkPlan(plan, flags) {
|
|
2666
|
+
if (plan.conflicts.length > 0 && !flags.force) {
|
|
2667
|
+
fail(
|
|
2668
|
+
`changed on the server since the last pull:
|
|
2669
|
+
${plan.conflicts.join("\n ")}
|
|
2670
|
+
pull (and merge) first, or pass --force to overwrite the server's version`
|
|
2671
|
+
);
|
|
2672
|
+
}
|
|
2673
|
+
const deletes = plan.changes.filter((c) => c.op === "delete").length;
|
|
2674
|
+
if (deletes > 0 && !flags.allowDeletes) {
|
|
2675
|
+
fail(`the plan deletes ${deletes} resource(s) from the server; pass --allow-deletes, or narrow with --channel/--library`);
|
|
2676
|
+
}
|
|
2677
|
+
}
|
|
2678
|
+
async function scopedPush(client, root, local, scope, target, flags) {
|
|
2679
|
+
const remote = await client.getServerConfiguration();
|
|
2680
|
+
const known = await readKnown(root);
|
|
2681
|
+
const plan = planPush(local, remote, scope, known);
|
|
2682
|
+
const names = new Map(
|
|
2683
|
+
[...channelsOf(remote), ...channelsOf(local)].map((c) => [String(c["id"]), String(c["name"])])
|
|
2684
|
+
);
|
|
2685
|
+
const nameOf2 = (id) => names.get(id) ?? id;
|
|
2686
|
+
const deployed = flags.deploy && plan.deployIds.length > 0 ? await client.getDeployedChannelIds() : /* @__PURE__ */ new Set();
|
|
2687
|
+
const toDeploy = plan.deployIds.filter((id) => deployed.has(id));
|
|
2688
|
+
const notDeployed = flags.deploy ? plan.deployIds.filter((id) => !deployed.has(id)) : [];
|
|
2689
|
+
if (plan.changes.length === 0) {
|
|
2690
|
+
process.stdout.write(`nothing to push: ${target} already matches the tree
|
|
2691
|
+
`);
|
|
2692
|
+
} else {
|
|
2693
|
+
process.stdout.write(`Push to ${target}:
|
|
2694
|
+
`);
|
|
2695
|
+
printChanges(plan);
|
|
2696
|
+
if (toDeploy.length > 0) process.stdout.write(`then redeploy: ${toDeploy.map(nameOf2).join(", ")}
|
|
2697
|
+
`);
|
|
2698
|
+
if (notDeployed.length > 0) {
|
|
2699
|
+
process.stdout.write(`not redeployed (not deployed on the server now): ${notDeployed.map(nameOf2).join(", ")}
|
|
2700
|
+
`);
|
|
2701
|
+
}
|
|
2702
|
+
}
|
|
2703
|
+
if (plan.notPushed.length > 0) {
|
|
2704
|
+
process.stdout.write(`not pushed (differs; use --whole-server): ${plan.notPushed.join(", ")}
|
|
2705
|
+
`);
|
|
2706
|
+
}
|
|
2707
|
+
if (plan.serverOnly.length > 0) {
|
|
2708
|
+
process.stdout.write(`left alone (created on the server since the last pull; pull to get them): ${plan.serverOnly.join(", ")}
|
|
2709
|
+
`);
|
|
2710
|
+
}
|
|
2711
|
+
if (plan.changes.length === 0) return;
|
|
2712
|
+
checkPlan(plan, flags);
|
|
2713
|
+
if (!flags.yes && !await confirm("Continue?")) {
|
|
2714
|
+
process.stdout.write("aborted.\n");
|
|
2715
|
+
return;
|
|
2716
|
+
}
|
|
2717
|
+
const fresh = await client.getServerConfiguration();
|
|
2718
|
+
const moved = changedSince(plan, remote, fresh);
|
|
2719
|
+
if (moved.length > 0 && !flags.force) {
|
|
2720
|
+
fail(`changed on the server while this push was being confirmed:
|
|
2721
|
+
${moved.join("\n ")}
|
|
2722
|
+
pull and try again, or pass --force`);
|
|
2723
|
+
}
|
|
2724
|
+
await backupBeforePush(client, flags);
|
|
2725
|
+
const result = await applyPlan(client, plan, local, fresh, scope, { force: flags.force === true });
|
|
2726
|
+
try {
|
|
2727
|
+
const after = await client.getServerConfiguration();
|
|
2728
|
+
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"]) }));
|
|
2729
|
+
const changedAgain = [...result.applied, ...refreshedLibraries].filter((c) => !savedChangeMatches(c, local, after));
|
|
2730
|
+
if (changedAgain.length > 0) fail(`changed again after saving: ${[...new Set(changedAgain.map((c) => c.label))].join(", ")}; pull and review before retrying`);
|
|
2731
|
+
if (result.touchedIds.size > 0) await refreshRevisions(root, after, result.touchedIds);
|
|
2732
|
+
if (known) await writeKnown(root, knownAfterPush(known, result.applied, result.touchedIds, after));
|
|
2733
|
+
} catch (err) {
|
|
2734
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2735
|
+
if (!result.failed) fail(`applied ${result.applied.length} change(s), but could not refresh the local sync baseline: ${message}; inspect the server before retrying`);
|
|
2736
|
+
process.stderr.write(`warning: could not refresh the local sync baseline: ${scrub(message)}
|
|
2737
|
+
`);
|
|
2738
|
+
}
|
|
2739
|
+
if (result.failed) {
|
|
2740
|
+
const { change, error } = result.failed;
|
|
2741
|
+
fail(`applied ${result.applied.length} of ${plan.changes.length}; ${change.op} ${change.label} failed: ${error}`);
|
|
2742
|
+
}
|
|
2743
|
+
process.stdout.write(`pushed ${result.applied.length} change(s)
|
|
2744
|
+
`);
|
|
2745
|
+
if (toDeploy.length > 0) {
|
|
2746
|
+
const failures = await deployChannels(client, toDeploy, nameOf2);
|
|
2747
|
+
process.stdout.write(`deployed ${toDeploy.length - failures.length} of ${toDeploy.length} channel(s)
|
|
2748
|
+
`);
|
|
2749
|
+
for (const f of failures) process.stderr.write(`deploy failed: ${f.name}: ${scrub(f.error)}
|
|
2750
|
+
`);
|
|
2751
|
+
if (failures.length > 0) process.exitCode = 1;
|
|
2752
|
+
}
|
|
2753
|
+
}
|
|
2754
|
+
async function wholeServerPush(client, root, local, target, flags) {
|
|
2755
|
+
const remote = await client.getServerConfiguration();
|
|
2756
|
+
const known = await readKnown(root);
|
|
2757
|
+
const plan = planPush(local, remote, {}, known, { wholeReplace: true });
|
|
2758
|
+
const s = summarize(local);
|
|
2759
|
+
process.stdout.write(
|
|
2760
|
+
`Replace the ENTIRE server configuration at ${target} (${s.channels} channels, ${s.codeTemplates} code templates${flags.deploy ? ", then redeploy all channels" : ""}).
|
|
2761
|
+
`
|
|
2762
|
+
);
|
|
2763
|
+
printNameChange(local, remote);
|
|
2764
|
+
if (plan.changes.length > 0) {
|
|
2765
|
+
process.stdout.write("Channel, library and template changes:\n");
|
|
2766
|
+
printChanges(plan);
|
|
2767
|
+
}
|
|
2768
|
+
for (const r of plan.serverOnly) process.stdout.write(` delete ${r} (created on the server since the last pull)
|
|
2769
|
+
`);
|
|
2770
|
+
const keptMap = plan.notPushed.includes("configurationMap") && !flags.overwriteConfigMap;
|
|
2771
|
+
const replaced = plan.notPushed.filter((k) => !(keptMap && k === "configurationMap"));
|
|
2772
|
+
if (replaced.length > 0) process.stdout.write(`also replaced: ${replaced.join(", ")}
|
|
2773
|
+
`);
|
|
2774
|
+
if (keptMap) process.stdout.write("configuration map differs but is kept (--overwrite-config-map replaces it)\n");
|
|
2775
|
+
if (plan.serverOnly.length > 0 && !flags.force) {
|
|
2776
|
+
fail("the replace would delete resources created on the server since the last pull; pull first, or pass --force (and --allow-deletes)");
|
|
2777
|
+
}
|
|
2778
|
+
const deletions = plan.changes.filter((c) => c.op === "delete").length + plan.serverOnly.length;
|
|
2779
|
+
if (deletions > 0 && !flags.allowDeletes) {
|
|
2780
|
+
fail(`the replace deletes ${deletions} resource(s) from the server; pass --allow-deletes`);
|
|
2781
|
+
}
|
|
2782
|
+
checkPlan(plan, flags);
|
|
2783
|
+
if (!flags.yes && !await confirm("Continue?")) {
|
|
2784
|
+
process.stdout.write("aborted.\n");
|
|
2785
|
+
return;
|
|
2786
|
+
}
|
|
2787
|
+
const fresh = await client.getServerConfiguration();
|
|
2788
|
+
if (!sameServerConfig(remote, fresh) && !flags.force) {
|
|
2789
|
+
fail("the server changed while this push was being confirmed; pull and try again, or pass --force");
|
|
2790
|
+
}
|
|
2791
|
+
const freshPlan = planPush(local, fresh, {}, known, { wholeReplace: true });
|
|
2792
|
+
if (!flags.allowDeletes && (freshPlan.serverOnly.length > 0 || freshPlan.changes.some((c) => c.op === "delete"))) {
|
|
2793
|
+
fail("the replace now deletes resources from the server; review the new plan and pass --allow-deletes");
|
|
2794
|
+
}
|
|
2795
|
+
await backupBeforePush(client, flags);
|
|
2796
|
+
await client.putServerConfiguration(local, {
|
|
2797
|
+
deploy: flags.deploy === true,
|
|
2798
|
+
overwriteConfigMap: flags.overwriteConfigMap === true
|
|
2799
|
+
});
|
|
2800
|
+
const after = await client.getServerConfiguration();
|
|
2801
|
+
if (planPush(local, after, {}, void 0, { wholeReplace: true }).changes.length > 0) {
|
|
2802
|
+
fail("applied the whole-server replacement, but resources changed again after saving; pull and review before retrying");
|
|
2803
|
+
}
|
|
2804
|
+
const ids = resourceIds(local);
|
|
2805
|
+
await refreshRevisions(root, after, /* @__PURE__ */ new Set([...Object.keys(ids.channels), ...Object.keys(ids.libraries), ...Object.keys(ids.codeTemplates)]));
|
|
2806
|
+
if (known) await writeKnown(root, resourceIds(after));
|
|
2807
|
+
process.stdout.write(`pushed ${root} -> ${target}
|
|
2808
|
+
`);
|
|
2809
|
+
}
|
|
2810
|
+
var program = new Command();
|
|
2811
|
+
program.name("channelvault").description("Git-style pull/push/diff for Mirth Connect").version(VERSION).allowExcessArguments(false);
|
|
2812
|
+
addExtractFlag(addEnvFlag(
|
|
2813
|
+
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")
|
|
2814
|
+
)).action(async (backupPath, dir, flags) => {
|
|
2815
|
+
const config = xml.parse(await readFile5(backupPath, "utf8"));
|
|
2816
|
+
const root = path5.resolve(dir);
|
|
2817
|
+
await writeTree(root, config, `file:${path5.resolve(backupPath)}`, flags);
|
|
2818
|
+
const s = summarize(config);
|
|
2819
|
+
process.stdout.write(`exploded ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}
|
|
2820
|
+
`);
|
|
2821
|
+
});
|
|
2822
|
+
addEnvFlag(
|
|
2823
|
+
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)
|
|
2824
|
+
).action(async (dir, outPath, flags) => {
|
|
2825
|
+
const root = path5.resolve(dir);
|
|
2826
|
+
assertTree(root);
|
|
2827
|
+
const config = await renderedTree(root, flags);
|
|
2828
|
+
await assertCompatibleOrigin(root, config, "xml", flags.force === true);
|
|
2829
|
+
const xmlStr = xml.build(config);
|
|
2830
|
+
await writeFile5(outPath, xmlStr, "utf8");
|
|
2831
|
+
process.stdout.write(`imploded ${root} -> ${path5.resolve(outPath)}
|
|
2832
|
+
`);
|
|
2833
|
+
});
|
|
2834
|
+
addExtractFlag(addEnvFlag(addConnectionFlags(
|
|
2835
|
+
program.command("pull").description("Pull the live server configuration into a working tree").argument("<dir>", "working-tree directory")
|
|
2836
|
+
))).action(async (dir, flags) => {
|
|
2837
|
+
const root = path5.resolve(dir);
|
|
2838
|
+
await preflightTree(root, envFilePath(root, flags));
|
|
2839
|
+
const config = await withClient(flags, (client) => client.getServerConfiguration());
|
|
2840
|
+
const cfg = resolveClientConfig(flags);
|
|
2841
|
+
await writeTree(root, config, `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`, flags);
|
|
2842
|
+
const s = summarize(config);
|
|
2843
|
+
process.stdout.write(`pulled ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}
|
|
2844
|
+
`);
|
|
2845
|
+
});
|
|
2846
|
+
addBackupDirFlags(addEnvFlag(addConnectionFlags(
|
|
2847
|
+
program.command("push").description("Push changed channels, code templates and global scripts to the live server").argument("<dir>", "working-tree directory").option("--channel <name>", "only this channel (name or id); repeatable", collect).option("--library <name>", "only this code template library (name or id); repeatable", collect).option("--global-scripts", "with --channel/--library: also push global scripts").option("--allow-deletes", "delete server resources that are missing from the tree", false).option("--deploy", "redeploy the changed channels and the channels using changed code templates", false).option("--force", "push even if the server changed since the last pull (overwrites the server's version)", false).option("--ignore-origin", "push a tree that was exploded from an XML backup (normally refused)", false).option("--whole-server", "replace the entire server configuration instead (settings, config map, groups too)", false).option("--overwrite-config-map", "with --whole-server: also overwrite the configuration map", false).option("--no-backup", "skip the backup of the server taken before anything changes").option("-y, --yes", "skip the confirmation prompt", false)
|
|
2848
|
+
))).action(
|
|
2849
|
+
async (dir, flags) => {
|
|
2850
|
+
if (flags.wholeServer && (flags.channel || flags.library || flags.globalScripts)) {
|
|
2851
|
+
fail("--whole-server replaces everything; it cannot be combined with --channel, --library or --global-scripts");
|
|
2852
|
+
}
|
|
2853
|
+
const root = path5.resolve(dir);
|
|
2854
|
+
assertTree(root);
|
|
2855
|
+
const config = await renderedTree(root, flags);
|
|
2856
|
+
await assertCompatibleOrigin(root, config, "live", flags.ignoreOrigin === true);
|
|
2857
|
+
const cfg = resolveClientConfig(flags);
|
|
2858
|
+
const target = `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`;
|
|
2859
|
+
if (!flags.yes && !process.stdin.isTTY) {
|
|
2860
|
+
fail("no terminal to confirm on; review with `diff` and pass --yes");
|
|
2861
|
+
}
|
|
2862
|
+
if (flags.wholeServer) {
|
|
2863
|
+
await withClient(flags, (client) => wholeServerPush(client, root, config, target, flags));
|
|
2864
|
+
return;
|
|
2865
|
+
}
|
|
2866
|
+
const scope = { channels: flags.channel, libraries: flags.library, globalScripts: flags.globalScripts };
|
|
2867
|
+
await withClient(flags, (client) => scopedPush(client, root, config, scope, target, flags));
|
|
2868
|
+
}
|
|
2869
|
+
);
|
|
2870
|
+
addBackupDirFlags(addConnectionFlags(
|
|
2871
|
+
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)")
|
|
2872
|
+
)).action(async (flags) => {
|
|
2873
|
+
const cfg = resolveClientConfig(flags);
|
|
2874
|
+
const target = `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`;
|
|
2875
|
+
const file = await withClient(flags, async (client) => {
|
|
2876
|
+
const text = await client.getServerConfigurationXml();
|
|
2877
|
+
if (!flags.out) return saveServerBackup(client, text, flags);
|
|
2878
|
+
const out = path5.resolve(flags.out);
|
|
2879
|
+
parseBackup(text, "the server configuration");
|
|
2880
|
+
if (existsSync5(out)) fail(`${out} already exists; choose another name`);
|
|
2881
|
+
await mkdir4(path5.dirname(out), { recursive: true });
|
|
2882
|
+
await writePrivate(out, text);
|
|
2883
|
+
if (gitWouldCommit(out)) {
|
|
2884
|
+
process.stderr.write(`warning: git does not ignore ${out}, which holds credentials in plain text; add it to .gitignore
|
|
2885
|
+
`);
|
|
2886
|
+
}
|
|
2887
|
+
return out;
|
|
2888
|
+
});
|
|
2889
|
+
process.stdout.write(`backed up ${target} to ${file}
|
|
2890
|
+
`);
|
|
2891
|
+
});
|
|
2892
|
+
addBackupDirFlags(addConnectionFlags(
|
|
2893
|
+
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)
|
|
2894
|
+
)).action(async (file, flags) => {
|
|
2895
|
+
const cfg = resolveClientConfig(flags);
|
|
2896
|
+
const target = `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`;
|
|
2897
|
+
if (!flags.yes && !process.stdin.isTTY) fail("no terminal to confirm on; pass --yes");
|
|
2898
|
+
const dir = backupDirOf(flags);
|
|
2899
|
+
await withClient(flags, async (client) => {
|
|
2900
|
+
const currentText = await client.getServerConfigurationXml();
|
|
2901
|
+
const current = parseBackup(currentText, "the server configuration");
|
|
2902
|
+
const serverId = await client.getServerId();
|
|
2903
|
+
let chosen;
|
|
2904
|
+
if (file) {
|
|
2905
|
+
chosen = path5.resolve(file);
|
|
2906
|
+
if (!existsSync5(chosen)) fail(`${chosen} does not exist`);
|
|
2907
|
+
} else {
|
|
2908
|
+
const mine = await backupsOf(dir, serverId);
|
|
2909
|
+
if (mine.length === 0) {
|
|
2910
|
+
const others = (await originsIn(dir)).map((o) => o.host);
|
|
2911
|
+
fail(`no backups of ${target} in ${dir}${others.length ? ` (it has backups of: ${others.join(", ")})` : ""}`);
|
|
2912
|
+
}
|
|
2913
|
+
chosen = mine[mine.length - 1].file;
|
|
2914
|
+
}
|
|
2915
|
+
const text = await readFile5(chosen, "utf8");
|
|
2916
|
+
const backup = parseBackup(text, chosen);
|
|
2917
|
+
const origin = await originOf(dir, chosen);
|
|
2918
|
+
if (origin) {
|
|
2919
|
+
if (origin.serverId !== serverId && !flags.force) {
|
|
2920
|
+
fail(`${chosen} was taken from ${origin.host} (server ID ${origin.serverId}), not this server (${serverId}); pass --force to restore it here anyway`);
|
|
2921
|
+
}
|
|
2922
|
+
} else {
|
|
2923
|
+
const [fromContent, fromServer] = [configuredName(backup), configuredName(current)];
|
|
2924
|
+
if (fromContent !== "" && fromServer !== "" && fromContent !== fromServer && !flags.force) {
|
|
2925
|
+
fail(`${chosen} is a backup of ${fromContent}, not ${fromServer}; pass --force to restore it here anyway`);
|
|
2926
|
+
}
|
|
2927
|
+
process.stderr.write(`warning: ${chosen} is not in ${path5.join(dir, MANIFEST)}, so which server it came from cannot be checked
|
|
2928
|
+
`);
|
|
2929
|
+
}
|
|
2930
|
+
const [bv, sv] = [backup["@_version"], current["@_version"]];
|
|
2931
|
+
if (typeof bv === "string" && typeof sv === "string" && numericVersion(bv) && numericVersion(sv)) {
|
|
2932
|
+
if (compareVersions(bv, sv) > 0) fail(`${chosen} is from Mirth ${bv}, newer than this server (${sv}); it cannot be restored here`);
|
|
2933
|
+
if (compareVersions(bv, sv) < 0) process.stderr.write(`note: ${chosen} is from Mirth ${bv}; the server (${sv}) will convert it
|
|
2934
|
+
`);
|
|
2935
|
+
} else {
|
|
2936
|
+
process.stderr.write(`warning: cannot compare the backup's Mirth version (${String(bv ?? "none")}) with the server's (${String(sv ?? "none")})
|
|
2937
|
+
`);
|
|
2938
|
+
}
|
|
2939
|
+
const plan = planPush(backup, current, {}, void 0, { wholeReplace: true });
|
|
2940
|
+
process.stdout.write(`Restore ${chosen}
|
|
2941
|
+
to ${target}, replacing its ENTIRE configuration${flags.deploy ? ", then redeploy all channels" : ""}.
|
|
2942
|
+
`);
|
|
2943
|
+
printNameChange(backup, current);
|
|
2944
|
+
if (plan.changes.length > 0) {
|
|
2945
|
+
process.stdout.write("Channel, library and template changes:\n");
|
|
2946
|
+
printChanges(plan);
|
|
2947
|
+
}
|
|
2948
|
+
const keptMap = plan.notPushed.includes("configurationMap") && !flags.overwriteConfigMap;
|
|
2949
|
+
const replaced = plan.notPushed.filter((k) => !(keptMap && k === "configurationMap"));
|
|
2950
|
+
if (replaced.length > 0) process.stdout.write(`also replaced: ${replaced.join(", ")}
|
|
2951
|
+
`);
|
|
2952
|
+
if (keptMap) process.stdout.write("configuration map differs but is kept (--overwrite-config-map replaces it)\n");
|
|
2953
|
+
if (!flags.yes && !await confirm("Continue?")) {
|
|
2954
|
+
process.stdout.write("aborted.\n");
|
|
2955
|
+
return;
|
|
2956
|
+
}
|
|
2957
|
+
const freshText = await client.getServerConfigurationXml();
|
|
2958
|
+
if (!sameServerConfig(parseBackup(freshText, "the server configuration"), current)) {
|
|
2959
|
+
fail("the server changed while this restore was being confirmed; nothing was restored. Run it again to review the new state");
|
|
2960
|
+
}
|
|
2961
|
+
const undo = await saveServerBackup(client, freshText, flags, chosen);
|
|
2962
|
+
process.stdout.write(`saved the current configuration to ${undo} (undo with: channelvault restore "${undo}")
|
|
2963
|
+
`);
|
|
2964
|
+
await client.putServerConfigurationXml(text, { deploy: flags.deploy === true, overwriteConfigMap: flags.overwriteConfigMap === true });
|
|
2965
|
+
const after = parseBackup(await client.getServerConfigurationXml(), "the server configuration");
|
|
2966
|
+
const differ = planPush(backup, after, {}, void 0, { wholeReplace: true }).changes;
|
|
2967
|
+
if (differ.length > 0) {
|
|
2968
|
+
fail(`restored, but these differ from the backup afterwards: ${differ.map((c) => c.label).join(", ")}; inspect the server`);
|
|
2969
|
+
}
|
|
2970
|
+
process.stdout.write(`restored ${chosen} to ${target}
|
|
2971
|
+
`);
|
|
2972
|
+
});
|
|
2973
|
+
});
|
|
2974
|
+
addEnvFlag(addConnectionFlags(
|
|
2975
|
+
program.command("diff").description("Diff a working tree against the live server configuration (exit 0 = same, 1 = differences, 2 = error)").argument("<dir>", "working-tree directory").exitOverride((err) => {
|
|
2976
|
+
process.exitCode = err.exitCode === 0 ? 0 : 2;
|
|
2977
|
+
throw err;
|
|
2978
|
+
})
|
|
2979
|
+
)).action(async (dir, flags) => {
|
|
2980
|
+
errorExitCode = 2;
|
|
2981
|
+
const root = path5.resolve(dir);
|
|
2982
|
+
assertTree(root);
|
|
2983
|
+
const fetched = await withClient(flags, (client) => client.getServerConfiguration());
|
|
2984
|
+
const tree = await engine.implode({ root });
|
|
2985
|
+
const { config: templatedRemote, envUpdates, notes } = templatize(fetched, tree, await loadEnv(envFilePath(root, flags)));
|
|
2986
|
+
for (const name of Object.keys(envUpdates)) {
|
|
2987
|
+
process.stderr.write(`note: ${name} differs between the server and the env file
|
|
2988
|
+
`);
|
|
2989
|
+
}
|
|
2990
|
+
for (const note of notes) process.stderr.write(`note: ${note}
|
|
2991
|
+
`);
|
|
2992
|
+
const allow = await readAllow(root);
|
|
2993
|
+
const treeView = scanSecrets(redactKnownSecrets(normalizeEolDeep(tree)), { mode: "redact", allow });
|
|
2994
|
+
const serverView = scanSecrets(redactKnownSecrets(normalizeEolDeep(templatedRemote)), { mode: "redact", allow });
|
|
2995
|
+
if (treeView.findings.length > 0) {
|
|
2996
|
+
process.stderr.write(`note: the tree holds ${treeView.findings.length} unextracted secret(s), redacted below; pull --extract-secrets
|
|
2997
|
+
`);
|
|
2998
|
+
}
|
|
2999
|
+
if (serverView.findings.length > 0) {
|
|
3000
|
+
process.stderr.write(`note: ${serverView.findings.length} possible secret(s) on the server are redacted below
|
|
3001
|
+
`);
|
|
3002
|
+
}
|
|
3003
|
+
const tmp = await mkdtemp(path5.join(tmpdir(), "channelvault-diff-"));
|
|
3004
|
+
try {
|
|
3005
|
+
await engine.explode(treeView.config, { root: path5.join(tmp, "tree") });
|
|
3006
|
+
await engine.explode(serverView.config, { root: path5.join(tmp, "server") });
|
|
3007
|
+
await mkdir4(path5.join(tmp, ".empty"));
|
|
3008
|
+
const chunks = [];
|
|
3009
|
+
for (const d of MANAGED_DIRS) {
|
|
3010
|
+
const local = existsSync5(path5.join(tmp, "tree", d)) ? `tree/${d}` : ".empty";
|
|
3011
|
+
const server = existsSync5(path5.join(tmp, "server", d)) ? `server/${d}` : ".empty";
|
|
3012
|
+
if (local === ".empty" && server === ".empty") continue;
|
|
3013
|
+
const result = spawnSync(
|
|
3014
|
+
"git",
|
|
3015
|
+
["-c", "core.autocrlf=false", "diff", "--no-index", "--no-color", "--ignore-cr-at-eol", local, server],
|
|
3016
|
+
{ encoding: "utf8", cwd: tmp }
|
|
3017
|
+
);
|
|
3018
|
+
if (result.error) {
|
|
3019
|
+
fail(`failed to run git (is it installed and on PATH?): ${result.error.message}`);
|
|
3020
|
+
}
|
|
3021
|
+
if (result.status !== 0 && result.status !== 1) {
|
|
3022
|
+
const stderr = (result.stderr ?? "").trim();
|
|
3023
|
+
fail(`git diff failed (exit ${result.status ?? "null"})${stderr ? `: ${stderr}` : ""}`);
|
|
3024
|
+
}
|
|
3025
|
+
const chunk = (result.stdout ?? "").trim();
|
|
3026
|
+
if (chunk !== "") chunks.push(chunk);
|
|
3027
|
+
}
|
|
3028
|
+
const out = chunks.join("\n");
|
|
3029
|
+
const secretDrift = Object.keys(envUpdates);
|
|
3030
|
+
if (out === "" && secretDrift.length === 0) {
|
|
3031
|
+
process.stdout.write("no differences \u2014 working tree matches the server.\n");
|
|
3032
|
+
} else {
|
|
3033
|
+
if (out !== "") process.stdout.write(out + "\n");
|
|
3034
|
+
if (secretDrift.length > 0) {
|
|
3035
|
+
process.stdout.write(`secret values differ between the server and the env file: ${secretDrift.join(", ")}
|
|
3036
|
+
`);
|
|
3037
|
+
}
|
|
3038
|
+
process.exitCode = 1;
|
|
3039
|
+
}
|
|
3040
|
+
} finally {
|
|
3041
|
+
await rm3(tmp, RM_OPTS);
|
|
3042
|
+
}
|
|
3043
|
+
});
|
|
3044
|
+
program.command("status").description("Summarize a working tree").argument("<dir>", "working-tree directory").action(async (dir) => {
|
|
3045
|
+
const root = path5.resolve(dir);
|
|
3046
|
+
assertTree(root);
|
|
3047
|
+
const config = await engine.implode({ root });
|
|
3048
|
+
const s = summarize(config);
|
|
3049
|
+
const metaPath = path5.join(root, "channelvault.json");
|
|
3050
|
+
if (existsSync5(metaPath)) {
|
|
3051
|
+
const meta = await readJson(metaPath);
|
|
3052
|
+
process.stdout.write(`source: ${meta.source}
|
|
3053
|
+
`);
|
|
3054
|
+
process.stdout.write(`pulled: ${meta.pulledAt}
|
|
3055
|
+
`);
|
|
3056
|
+
process.stdout.write(`engine: ${meta.engineVersion ?? "unknown"}
|
|
3057
|
+
`);
|
|
3058
|
+
}
|
|
3059
|
+
process.stdout.write(
|
|
3060
|
+
`channels: ${s.channels}
|
|
3061
|
+
channel groups: ${s.channelGroups}
|
|
3062
|
+
code template libs: ${s.codeTemplateLibraries}
|
|
3063
|
+
code templates: ${s.codeTemplates}
|
|
3064
|
+
`
|
|
3065
|
+
);
|
|
3066
|
+
});
|
|
3067
|
+
program.parseAsync().catch((err) => {
|
|
3068
|
+
if (err instanceof CommanderError) return;
|
|
3069
|
+
process.stderr.write(`error: ${scrub(err instanceof Error ? err.message : String(err))}
|
|
3070
|
+
`);
|
|
3071
|
+
const code = err?.code;
|
|
3072
|
+
if (typeof code === "string" && UNTRUSTED_CERT_CODES.has(code)) {
|
|
3073
|
+
process.stderr.write(
|
|
3074
|
+
"hint: the server's TLS certificate is not trusted. For a self-signed certificate (Mirth's default), pass --insecure, which turns certificate verification off.\n"
|
|
3075
|
+
);
|
|
3076
|
+
}
|
|
3077
|
+
if (!(err instanceof CliError) && err instanceof Error && process.env.CHANNELVAULT_DEBUG) {
|
|
3078
|
+
process.stderr.write(`${scrub(err.stack ?? "")}
|
|
3079
|
+
`);
|
|
3080
|
+
}
|
|
3081
|
+
process.exitCode = errorExitCode;
|
|
3082
|
+
});
|
|
3083
|
+
//# sourceMappingURL=cli.js.map
|