@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/index.js
ADDED
|
@@ -0,0 +1,1368 @@
|
|
|
1
|
+
// src/types.ts
|
|
2
|
+
function isFileRef(v) {
|
|
3
|
+
return typeof v === "object" && v !== null && !Array.isArray(v) && Object.keys(v).length === 1 && typeof v["@file"] === "string";
|
|
4
|
+
}
|
|
5
|
+
var CODE_KEYS = ["script", "code"];
|
|
6
|
+
var CHANNEL_SCRIPT_KEYS = [
|
|
7
|
+
"preprocessingScript",
|
|
8
|
+
"postprocessingScript",
|
|
9
|
+
"deployScript",
|
|
10
|
+
"undeployScript"
|
|
11
|
+
];
|
|
12
|
+
|
|
13
|
+
// src/xml/index.ts
|
|
14
|
+
import { XMLParser, XMLValidator } from "fast-xml-parser";
|
|
15
|
+
var ALWAYS_ARRAY_TAGS = /* @__PURE__ */ new Set([
|
|
16
|
+
"channel",
|
|
17
|
+
"connector",
|
|
18
|
+
"codeTemplate",
|
|
19
|
+
"codeTemplateLibrary",
|
|
20
|
+
"channelGroup",
|
|
21
|
+
"alert",
|
|
22
|
+
"rule",
|
|
23
|
+
"entry",
|
|
24
|
+
"string",
|
|
25
|
+
// Fully-qualified JavaScript step / rule element names (live under <elements>).
|
|
26
|
+
"com.mirth.connect.plugins.javascriptstep.JavaScriptStep",
|
|
27
|
+
"com.mirth.connect.plugins.javascriptrule.JavaScriptRule",
|
|
28
|
+
"com.mirth.connect.plugins.mapper.MapperStep",
|
|
29
|
+
"com.mirth.connect.plugins.messagebuilder.MessageBuilderStep"
|
|
30
|
+
]);
|
|
31
|
+
var ROOT_KEY = "serverConfiguration";
|
|
32
|
+
var TEXT_KEY = "#text";
|
|
33
|
+
var COMMENT_KEY = "#comment";
|
|
34
|
+
var CDATA_KEY = "#cdata";
|
|
35
|
+
var ORDER_KEY = "#order";
|
|
36
|
+
var ATTR_PREFIX = "@_";
|
|
37
|
+
var ORDERED_ATTRS = ":@";
|
|
38
|
+
var INDENT = " ";
|
|
39
|
+
function isWhitespaceOnly(s) {
|
|
40
|
+
return /^\s*$/.test(s);
|
|
41
|
+
}
|
|
42
|
+
var NAMED_DECODE = {
|
|
43
|
+
amp: "&",
|
|
44
|
+
lt: "<",
|
|
45
|
+
gt: ">",
|
|
46
|
+
quot: '"',
|
|
47
|
+
apos: "'"
|
|
48
|
+
};
|
|
49
|
+
function decodeEntities(value) {
|
|
50
|
+
if (!value.includes("&")) return value;
|
|
51
|
+
return value.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g, (whole, body) => {
|
|
52
|
+
if (body[0] !== "#") return NAMED_DECODE[body] ?? whole;
|
|
53
|
+
const code = body[1] === "x" || body[1] === "X" ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
|
|
54
|
+
if (!(code <= 1114111)) {
|
|
55
|
+
throw new Error(`XmlConfigAdapter.parse: invalid character reference ${whole}`);
|
|
56
|
+
}
|
|
57
|
+
return String.fromCodePoint(code);
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
function charRef(ch) {
|
|
61
|
+
return `&#x${ch.charCodeAt(0).toString(16)};`;
|
|
62
|
+
}
|
|
63
|
+
var ESCAPE = {
|
|
64
|
+
"&": "&",
|
|
65
|
+
"<": "<",
|
|
66
|
+
">": ">",
|
|
67
|
+
'"': """,
|
|
68
|
+
"'": "'"
|
|
69
|
+
};
|
|
70
|
+
function encodeText(value) {
|
|
71
|
+
return value.replace(/[&<>"'\x00-\x08\x0b-\x1f]/g, (ch) => ESCAPE[ch] ?? charRef(ch));
|
|
72
|
+
}
|
|
73
|
+
function encodeAttr(value) {
|
|
74
|
+
return value.replace(/[&<>"'\x00-\x1f]/g, (ch) => ESCAPE[ch] ?? charRef(ch));
|
|
75
|
+
}
|
|
76
|
+
function nodeName(node) {
|
|
77
|
+
const name = Object.keys(node).find((k) => k !== ORDERED_ATTRS);
|
|
78
|
+
if (name === void 0) throw new Error("XmlConfigAdapter.parse: empty node");
|
|
79
|
+
return name;
|
|
80
|
+
}
|
|
81
|
+
function rawInnerText(children) {
|
|
82
|
+
return children.map((c) => String(c[TEXT_KEY] ?? "")).join("");
|
|
83
|
+
}
|
|
84
|
+
function defaultOrder(obj) {
|
|
85
|
+
const seq = [];
|
|
86
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
87
|
+
if (key.startsWith(ATTR_PREFIX) || key === ORDER_KEY) continue;
|
|
88
|
+
const count = Array.isArray(value) ? value.length : 1;
|
|
89
|
+
for (let i = 0; i < count; i += 1) seq.push(key);
|
|
90
|
+
}
|
|
91
|
+
return seq;
|
|
92
|
+
}
|
|
93
|
+
function convertElement(children, attrs) {
|
|
94
|
+
const hasElementChild = children.some((c) => {
|
|
95
|
+
const n = nodeName(c);
|
|
96
|
+
return n !== TEXT_KEY && n !== CDATA_KEY;
|
|
97
|
+
});
|
|
98
|
+
const groups = /* @__PURE__ */ new Map();
|
|
99
|
+
const order = [];
|
|
100
|
+
const segments = [];
|
|
101
|
+
let pending = null;
|
|
102
|
+
const flushText = () => {
|
|
103
|
+
if (pending === null) return;
|
|
104
|
+
if (!hasElementChild || !isWhitespaceOnly(pending)) {
|
|
105
|
+
segments.push(pending);
|
|
106
|
+
order.push(TEXT_KEY);
|
|
107
|
+
}
|
|
108
|
+
pending = null;
|
|
109
|
+
};
|
|
110
|
+
for (const child of children) {
|
|
111
|
+
const name = nodeName(child);
|
|
112
|
+
if (name === TEXT_KEY) {
|
|
113
|
+
pending = (pending ?? "") + decodeEntities(String(child[TEXT_KEY]));
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (name === CDATA_KEY) {
|
|
117
|
+
pending = (pending ?? "") + rawInnerText(child[CDATA_KEY]);
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
flushText();
|
|
121
|
+
if (name === "#__proto__") {
|
|
122
|
+
throw new Error("XmlConfigAdapter.parse: unsupported element name <__proto__>");
|
|
123
|
+
}
|
|
124
|
+
const value = name === COMMENT_KEY ? rawInnerText(child[COMMENT_KEY]) : convertElement(child[name], child[ORDERED_ATTRS]);
|
|
125
|
+
const group = groups.get(name);
|
|
126
|
+
if (group) group.push(value);
|
|
127
|
+
else groups.set(name, [value]);
|
|
128
|
+
order.push(name);
|
|
129
|
+
}
|
|
130
|
+
flushText();
|
|
131
|
+
const attrEntries = Object.entries(attrs ?? {});
|
|
132
|
+
if (!hasElementChild && attrEntries.length === 0) {
|
|
133
|
+
return segments.join("");
|
|
134
|
+
}
|
|
135
|
+
const obj = {};
|
|
136
|
+
for (const [name, values] of groups) {
|
|
137
|
+
obj[name] = values.length > 1 || ALWAYS_ARRAY_TAGS.has(name) ? values : values[0];
|
|
138
|
+
}
|
|
139
|
+
if (segments.length === 1) obj[TEXT_KEY] = segments[0];
|
|
140
|
+
else if (segments.length > 1) obj[TEXT_KEY] = segments;
|
|
141
|
+
for (const [key, raw] of attrEntries) {
|
|
142
|
+
if (key === `${ATTR_PREFIX}__proto__`) {
|
|
143
|
+
throw new Error("XmlConfigAdapter.parse: unsupported attribute name __proto__");
|
|
144
|
+
}
|
|
145
|
+
obj[key] = decodeEntities(String(raw).replace(/[\t\n]/g, " "));
|
|
146
|
+
}
|
|
147
|
+
const def = defaultOrder(obj);
|
|
148
|
+
if (def.length !== order.length || def.some((k, i) => k !== order[i])) {
|
|
149
|
+
obj[ORDER_KEY] = order;
|
|
150
|
+
}
|
|
151
|
+
return obj;
|
|
152
|
+
}
|
|
153
|
+
var parser = new XMLParser({
|
|
154
|
+
preserveOrder: true,
|
|
155
|
+
ignoreAttributes: false,
|
|
156
|
+
attributeNamePrefix: ATTR_PREFIX,
|
|
157
|
+
parseTagValue: false,
|
|
158
|
+
parseAttributeValue: false,
|
|
159
|
+
trimValues: false,
|
|
160
|
+
processEntities: false,
|
|
161
|
+
commentPropName: COMMENT_KEY,
|
|
162
|
+
cdataPropName: CDATA_KEY
|
|
163
|
+
});
|
|
164
|
+
function orderedChildren(obj, where) {
|
|
165
|
+
const queues = /* @__PURE__ */ new Map();
|
|
166
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
167
|
+
if (key.startsWith(ATTR_PREFIX) || key === ORDER_KEY) continue;
|
|
168
|
+
queues.set(key, Array.isArray(value) ? [...value] : [value]);
|
|
169
|
+
}
|
|
170
|
+
const out = [];
|
|
171
|
+
const hint = obj[ORDER_KEY];
|
|
172
|
+
if (hint !== void 0) {
|
|
173
|
+
if (!Array.isArray(hint) || !hint.every((h) => typeof h === "string")) {
|
|
174
|
+
throw new Error(`XmlConfigAdapter.build: ${ORDER_KEY} under <${where}> must be an array of names`);
|
|
175
|
+
}
|
|
176
|
+
for (const name of hint) {
|
|
177
|
+
const next = queues.get(name)?.shift();
|
|
178
|
+
if (next !== void 0) out.push([name, next]);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
for (const [key, rest] of queues) {
|
|
182
|
+
for (const value of rest) out.push([key, value]);
|
|
183
|
+
}
|
|
184
|
+
return out;
|
|
185
|
+
}
|
|
186
|
+
function scalar(value) {
|
|
187
|
+
return value === null ? "" : String(value);
|
|
188
|
+
}
|
|
189
|
+
function serialize(name, value, depth, pretty, out) {
|
|
190
|
+
const pad = pretty ? INDENT.repeat(depth) : "";
|
|
191
|
+
const nl = pretty ? "\n" : "";
|
|
192
|
+
if (name === COMMENT_KEY) {
|
|
193
|
+
const text = scalar(value);
|
|
194
|
+
if (text.includes("--") || text.endsWith("-")) {
|
|
195
|
+
throw new Error(`XmlConfigAdapter.build: comment text cannot contain "--": ${text}`);
|
|
196
|
+
}
|
|
197
|
+
out.push(`${pad}<!--${text}-->${nl}`);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
if (name === TEXT_KEY) {
|
|
201
|
+
out.push(encodeText(scalar(value)));
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
205
|
+
out.push(`${pad}<${name}>${encodeText(scalar(value))}</${name}>${nl}`);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const attrs = Object.entries(value).filter(([k]) => k.startsWith(ATTR_PREFIX)).map(([k, v]) => ` ${k.slice(ATTR_PREFIX.length)}="${encodeAttr(scalar(v))}"`).join("");
|
|
209
|
+
const children = orderedChildren(value, name);
|
|
210
|
+
const hasElementChild = children.some(([k]) => k !== TEXT_KEY);
|
|
211
|
+
if (!hasElementChild) {
|
|
212
|
+
const text = children.map(([, v]) => encodeText(scalar(v))).join("");
|
|
213
|
+
out.push(`${pad}<${name}${attrs}>${text}</${name}>${nl}`);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
const mixed = children.some(([k]) => k === TEXT_KEY);
|
|
217
|
+
const childPretty = pretty && !mixed;
|
|
218
|
+
out.push(`${pad}<${name}${attrs}>${childPretty ? "\n" : ""}`);
|
|
219
|
+
for (const [key, child] of children) {
|
|
220
|
+
serialize(key, child, depth + 1, childPretty, out);
|
|
221
|
+
}
|
|
222
|
+
out.push(`${childPretty ? pad : ""}</${name}>${nl}`);
|
|
223
|
+
}
|
|
224
|
+
var XmlConfigAdapter = class {
|
|
225
|
+
/** Parse a Mirth backup XML string into a canonical config. */
|
|
226
|
+
parse(xml) {
|
|
227
|
+
const normalized = xml.replace(/\r\n?/g, "\n");
|
|
228
|
+
if (/<!DOCTYPE/i.test(normalized.slice(0, normalized.search(/<[A-Za-z_]/)))) {
|
|
229
|
+
throw new Error("XmlConfigAdapter.parse: DOCTYPE declarations are not supported");
|
|
230
|
+
}
|
|
231
|
+
const valid = XMLValidator.validate(normalized);
|
|
232
|
+
if (valid !== true) {
|
|
233
|
+
const { line, col, msg } = valid.err;
|
|
234
|
+
throw new Error(`XmlConfigAdapter.parse: not well-formed XML at line ${line}, column ${col}: ${msg}`);
|
|
235
|
+
}
|
|
236
|
+
const nodes = parser.parse(normalized);
|
|
237
|
+
const root = nodes.find((n) => nodeName(n) === ROOT_KEY);
|
|
238
|
+
if (root === void 0) {
|
|
239
|
+
throw new Error(`XmlConfigAdapter.parse: expected a top-level <${ROOT_KEY}> element`);
|
|
240
|
+
}
|
|
241
|
+
const value = convertElement(root[ROOT_KEY], root[ORDERED_ATTRS]);
|
|
242
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
|
|
243
|
+
}
|
|
244
|
+
/** Serialize a canonical config back to Mirth backup XML. */
|
|
245
|
+
build(config) {
|
|
246
|
+
const out = [];
|
|
247
|
+
serialize(ROOT_KEY, config, 0, true, out);
|
|
248
|
+
return out.join("");
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
// src/explode/index.ts
|
|
253
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
254
|
+
import { existsSync } from "fs";
|
|
255
|
+
import { lstat, mkdir, readFile as readFile2, realpath, writeFile } from "fs/promises";
|
|
256
|
+
import * as path from "path";
|
|
257
|
+
|
|
258
|
+
// src/json.ts
|
|
259
|
+
import { readFile } from "fs/promises";
|
|
260
|
+
function parseJson(text, file) {
|
|
261
|
+
try {
|
|
262
|
+
return JSON.parse(text);
|
|
263
|
+
} catch (err) {
|
|
264
|
+
throw new Error(`${file}: ${err instanceof Error ? err.message : String(err)}`);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
async function readJson(file) {
|
|
268
|
+
return parseJson(await readFile(file, "utf8"), file);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// src/explode/index.ts
|
|
272
|
+
function asArray(x) {
|
|
273
|
+
return Array.isArray(x) ? x : x == null ? [] : [x];
|
|
274
|
+
}
|
|
275
|
+
function isRefMarker(v) {
|
|
276
|
+
return typeof v === "object" && v !== null && !Array.isArray(v) && Object.keys(v).length === 1 && typeof v["@ref"] === "string";
|
|
277
|
+
}
|
|
278
|
+
var CODE_KEY_SET = /* @__PURE__ */ new Set([...CODE_KEYS, ...CHANNEL_SCRIPT_KEYS]);
|
|
279
|
+
var CHANNEL_SCRIPT_FRIENDLY = {
|
|
280
|
+
preprocessingScript: "preprocessor",
|
|
281
|
+
postprocessingScript: "postprocessor",
|
|
282
|
+
deployScript: "deploy",
|
|
283
|
+
undeployScript: "undeploy"
|
|
284
|
+
};
|
|
285
|
+
function isPlainObject(v) {
|
|
286
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
287
|
+
}
|
|
288
|
+
function deepClone(v) {
|
|
289
|
+
return structuredClone(v);
|
|
290
|
+
}
|
|
291
|
+
function slug(name) {
|
|
292
|
+
let s = typeof name === "string" ? name : name == null ? "" : String(name);
|
|
293
|
+
s = s.replace(/[/\\:*?"<>|]/g, " ");
|
|
294
|
+
s = s.replace(/[\x00-\x1f\x7f]/g, " ");
|
|
295
|
+
s = s.replace(/\s+/g, "-");
|
|
296
|
+
s = s.replace(/^[-.]+|[-.]+$/g, "");
|
|
297
|
+
if (s.length === 0) return "unnamed";
|
|
298
|
+
return /^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i.test(s) ? `${s}-` : s;
|
|
299
|
+
}
|
|
300
|
+
function uniqueSlug(base, used) {
|
|
301
|
+
let candidate = base;
|
|
302
|
+
for (let n = 2; used.has(candidate.toLowerCase()); n += 1) candidate = `${base}-${n}`;
|
|
303
|
+
used.add(candidate.toLowerCase());
|
|
304
|
+
return candidate;
|
|
305
|
+
}
|
|
306
|
+
function relPosix(fromDir, toFile) {
|
|
307
|
+
return path.relative(fromDir, toFile).split(path.sep).join("/");
|
|
308
|
+
}
|
|
309
|
+
var explodeRoot = new AsyncLocalStorage();
|
|
310
|
+
async function assertInsideTree(filePath) {
|
|
311
|
+
const root = explodeRoot.getStore();
|
|
312
|
+
if (root === void 0) return;
|
|
313
|
+
let dir = path.dirname(filePath);
|
|
314
|
+
while (!existsSync(dir) && path.dirname(dir) !== dir) dir = path.dirname(dir);
|
|
315
|
+
const real = await realpath(dir);
|
|
316
|
+
if (real !== root && !real.startsWith(root + path.sep)) {
|
|
317
|
+
throw new Error(`refusing to write outside the working tree: ${filePath}`);
|
|
318
|
+
}
|
|
319
|
+
const existing = await lstat(filePath).catch((err) => {
|
|
320
|
+
if (err.code !== "ENOENT") throw err;
|
|
321
|
+
return void 0;
|
|
322
|
+
});
|
|
323
|
+
if (existing?.isSymbolicLink()) throw new Error(`refusing to write through a file link: ${filePath}`);
|
|
324
|
+
}
|
|
325
|
+
async function writeFileMkdir(filePath, data) {
|
|
326
|
+
await assertInsideTree(filePath);
|
|
327
|
+
await mkdir(path.dirname(filePath), { recursive: true });
|
|
328
|
+
await writeFile(filePath, data);
|
|
329
|
+
}
|
|
330
|
+
async function writeJson(filePath, value) {
|
|
331
|
+
await assertInsideTree(filePath);
|
|
332
|
+
await mkdir(path.dirname(filePath), { recursive: true });
|
|
333
|
+
await writeFile(filePath, JSON.stringify(value, null, 2));
|
|
334
|
+
}
|
|
335
|
+
async function extractCode(value, ctx) {
|
|
336
|
+
if (Array.isArray(value)) {
|
|
337
|
+
const out = [];
|
|
338
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
339
|
+
out.push(
|
|
340
|
+
await extractCode(value[i], {
|
|
341
|
+
...ctx,
|
|
342
|
+
friendly: null,
|
|
343
|
+
prefixParts: [...ctx.prefixParts, String(i)]
|
|
344
|
+
})
|
|
345
|
+
);
|
|
346
|
+
}
|
|
347
|
+
return out;
|
|
348
|
+
}
|
|
349
|
+
if (!isPlainObject(value)) {
|
|
350
|
+
return value;
|
|
351
|
+
}
|
|
352
|
+
return extractFromObject(value, ctx);
|
|
353
|
+
}
|
|
354
|
+
async function extractFromObject(obj, ctx) {
|
|
355
|
+
const out = {};
|
|
356
|
+
for (const [key, raw] of Object.entries(obj)) {
|
|
357
|
+
if (CODE_KEY_SET.has(key) && typeof raw === "string") {
|
|
358
|
+
if (raw.trim().length === 0) {
|
|
359
|
+
out[key] = raw;
|
|
360
|
+
continue;
|
|
361
|
+
}
|
|
362
|
+
const friendlyBase = key in CHANNEL_SCRIPT_FRIENDLY ? `scripts/${CHANNEL_SCRIPT_FRIENDLY[key]}` : (
|
|
363
|
+
// One filename segment: config keys are untrusted and may hold '/' or '..'.
|
|
364
|
+
ctx.friendly ?? `_code/${slug([...ctx.prefixParts, key].join("."))}`
|
|
365
|
+
);
|
|
366
|
+
const filePath = resolveUnique(ctx.codeDir, `${friendlyBase}.js`, ctx.usedPaths);
|
|
367
|
+
await writeFileMkdir(filePath, raw);
|
|
368
|
+
out[key] = { "@file": relPosix(ctx.jsonDir, filePath) };
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
out[key] = await extractCode(raw, {
|
|
372
|
+
...ctx,
|
|
373
|
+
friendly: null,
|
|
374
|
+
prefixParts: [...ctx.prefixParts, key]
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
return out;
|
|
378
|
+
}
|
|
379
|
+
function resolveUnique(baseDir, relName, used) {
|
|
380
|
+
const ext = path.extname(relName);
|
|
381
|
+
const dir = path.dirname(relName);
|
|
382
|
+
const stem = path.basename(relName, ext);
|
|
383
|
+
const dirSlug = dir === "." ? "" : dir;
|
|
384
|
+
const segs = dirSlug.split("/").filter(Boolean);
|
|
385
|
+
let rel = [...segs, `${stem}${ext}`].join("/");
|
|
386
|
+
for (let n = 2; used.has(rel.toLowerCase()); n += 1) rel = [...segs, `${stem}-${n}${ext}`].join("/");
|
|
387
|
+
used.add(rel.toLowerCase());
|
|
388
|
+
const full = path.resolve(baseDir, ...rel.split("/"));
|
|
389
|
+
if (!full.startsWith(path.resolve(baseDir) + path.sep)) throw new Error(`script path escapes its directory: ${relName}`);
|
|
390
|
+
return full;
|
|
391
|
+
}
|
|
392
|
+
async function explodeChannelTree(channel, dir, usedPaths) {
|
|
393
|
+
const out = {};
|
|
394
|
+
for (const [key, raw] of Object.entries(channel)) {
|
|
395
|
+
if (key in CHANNEL_SCRIPT_FRIENDLY && typeof raw === "string") {
|
|
396
|
+
if (raw.trim().length === 0) {
|
|
397
|
+
out[key] = raw;
|
|
398
|
+
continue;
|
|
399
|
+
}
|
|
400
|
+
const filePath = resolveUnique(dir, `scripts/${CHANNEL_SCRIPT_FRIENDLY[key]}.js`, usedPaths);
|
|
401
|
+
await writeFileMkdir(filePath, raw);
|
|
402
|
+
out[key] = { "@file": relPosix(dir, filePath) };
|
|
403
|
+
continue;
|
|
404
|
+
}
|
|
405
|
+
if (key === "sourceConnector" && isPlainObject(raw)) {
|
|
406
|
+
out[key] = await explodeConnector(raw, dir, "source", "source/receiver", usedPaths);
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
if (key === "destinationConnectors" && isPlainObject(raw)) {
|
|
410
|
+
out[key] = await explodeDestinationConnectors(raw, dir, usedPaths);
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
out[key] = await extractCode(raw, {
|
|
414
|
+
jsonDir: dir,
|
|
415
|
+
codeDir: dir,
|
|
416
|
+
friendly: null,
|
|
417
|
+
prefixParts: [key],
|
|
418
|
+
usedPaths
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
return out;
|
|
422
|
+
}
|
|
423
|
+
async function explodeConnector(connector, channelDir, baseRel, scriptFileBase, usedPaths) {
|
|
424
|
+
const out = {};
|
|
425
|
+
for (const [key, raw] of Object.entries(connector)) {
|
|
426
|
+
if (key === "transformer" && isPlainObject(raw)) {
|
|
427
|
+
out[key] = await explodeStepContainer(raw, channelDir, `${baseRel}/transformer`, usedPaths);
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
430
|
+
if (key === "responseTransformer" && isPlainObject(raw)) {
|
|
431
|
+
out[key] = await explodeStepContainer(
|
|
432
|
+
raw,
|
|
433
|
+
channelDir,
|
|
434
|
+
`${baseRel}/responseTransformer`,
|
|
435
|
+
usedPaths
|
|
436
|
+
);
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
if (key === "filter" && isPlainObject(raw)) {
|
|
440
|
+
out[key] = await explodeStepContainer(raw, channelDir, `${baseRel}/filter`, usedPaths);
|
|
441
|
+
continue;
|
|
442
|
+
}
|
|
443
|
+
if (key === "properties" && isPlainObject(raw)) {
|
|
444
|
+
out[key] = await explodeConnectorProperties(raw, channelDir, scriptFileBase, usedPaths);
|
|
445
|
+
continue;
|
|
446
|
+
}
|
|
447
|
+
out[key] = await extractCode(raw, {
|
|
448
|
+
jsonDir: channelDir,
|
|
449
|
+
codeDir: channelDir,
|
|
450
|
+
friendly: null,
|
|
451
|
+
prefixParts: [baseRel, key],
|
|
452
|
+
usedPaths
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
return out;
|
|
456
|
+
}
|
|
457
|
+
async function explodeConnectorProperties(properties, channelDir, scriptFileBase, usedPaths) {
|
|
458
|
+
const out = {};
|
|
459
|
+
for (const [key, raw] of Object.entries(properties)) {
|
|
460
|
+
if (key === "script" && typeof raw === "string") {
|
|
461
|
+
if (raw.trim().length === 0) {
|
|
462
|
+
out[key] = raw;
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
const filePath = resolveUnique(channelDir, `${scriptFileBase}.js`, usedPaths);
|
|
466
|
+
await writeFileMkdir(filePath, raw);
|
|
467
|
+
out[key] = { "@file": relPosix(channelDir, filePath) };
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
out[key] = await extractCode(raw, {
|
|
471
|
+
jsonDir: channelDir,
|
|
472
|
+
codeDir: channelDir,
|
|
473
|
+
friendly: null,
|
|
474
|
+
prefixParts: ["properties", key],
|
|
475
|
+
usedPaths
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
return out;
|
|
479
|
+
}
|
|
480
|
+
async function explodeDestinationConnectors(container, channelDir, usedPaths) {
|
|
481
|
+
const out = {};
|
|
482
|
+
const usedDestSlugs = /* @__PURE__ */ new Set();
|
|
483
|
+
for (const [key, raw] of Object.entries(container)) {
|
|
484
|
+
if (key === "connector") {
|
|
485
|
+
const connectors = asArray(raw);
|
|
486
|
+
const wasArray = Array.isArray(raw);
|
|
487
|
+
const transformed = [];
|
|
488
|
+
for (const conn of connectors) {
|
|
489
|
+
const name = isPlainObject(conn) ? conn["name"] : void 0;
|
|
490
|
+
const destSlug = uniqueSlug(slug(name), usedDestSlugs);
|
|
491
|
+
transformed.push(
|
|
492
|
+
isPlainObject(conn) ? await explodeConnector(
|
|
493
|
+
conn,
|
|
494
|
+
channelDir,
|
|
495
|
+
`destinations/${destSlug}`,
|
|
496
|
+
`destinations/${destSlug}/writer`,
|
|
497
|
+
usedPaths
|
|
498
|
+
) : conn
|
|
499
|
+
);
|
|
500
|
+
}
|
|
501
|
+
out[key] = wasArray ? transformed : transformed[0];
|
|
502
|
+
continue;
|
|
503
|
+
}
|
|
504
|
+
out[key] = await extractCode(raw, {
|
|
505
|
+
jsonDir: channelDir,
|
|
506
|
+
codeDir: channelDir,
|
|
507
|
+
friendly: null,
|
|
508
|
+
prefixParts: ["destinationConnectors", key],
|
|
509
|
+
usedPaths
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
return out;
|
|
513
|
+
}
|
|
514
|
+
async function explodeStepContainer(container, channelDir, baseRel, usedPaths) {
|
|
515
|
+
const out = {};
|
|
516
|
+
for (const [key, raw] of Object.entries(container)) {
|
|
517
|
+
if (key === "elements" && (Array.isArray(raw) || isPlainObject(raw))) {
|
|
518
|
+
out[key] = await explodeElementsContainer(
|
|
519
|
+
raw,
|
|
520
|
+
channelDir,
|
|
521
|
+
baseRel,
|
|
522
|
+
usedPaths
|
|
523
|
+
);
|
|
524
|
+
continue;
|
|
525
|
+
}
|
|
526
|
+
out[key] = await extractCode(raw, {
|
|
527
|
+
jsonDir: channelDir,
|
|
528
|
+
codeDir: channelDir,
|
|
529
|
+
friendly: null,
|
|
530
|
+
prefixParts: [baseRel, key],
|
|
531
|
+
usedPaths
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
return out;
|
|
535
|
+
}
|
|
536
|
+
function isStepLike(obj) {
|
|
537
|
+
return typeof obj["script"] === "string" || typeof obj["code"] === "string" || "sequenceNumber" in obj || "name" in obj;
|
|
538
|
+
}
|
|
539
|
+
async function explodeElementsContainer(elements, channelDir, baseRel, usedPaths) {
|
|
540
|
+
const counter = { i: 0 };
|
|
541
|
+
if (Array.isArray(elements)) {
|
|
542
|
+
return explodeStepArray(elements, channelDir, baseRel, usedPaths, counter);
|
|
543
|
+
}
|
|
544
|
+
if (isStepLike(elements)) {
|
|
545
|
+
return explodeStep(elements, channelDir, baseRel, counter.i++, usedPaths);
|
|
546
|
+
}
|
|
547
|
+
const out = {};
|
|
548
|
+
for (const [className, raw] of Object.entries(elements)) {
|
|
549
|
+
if (className.startsWith("@_") || className.startsWith("#") || raw == null) {
|
|
550
|
+
out[className] = await extractCode(raw, {
|
|
551
|
+
jsonDir: channelDir,
|
|
552
|
+
codeDir: channelDir,
|
|
553
|
+
friendly: null,
|
|
554
|
+
prefixParts: [baseRel, "elements", className],
|
|
555
|
+
usedPaths
|
|
556
|
+
});
|
|
557
|
+
continue;
|
|
558
|
+
}
|
|
559
|
+
if (Array.isArray(raw)) {
|
|
560
|
+
out[className] = await explodeStepArray(raw, channelDir, baseRel, usedPaths, counter);
|
|
561
|
+
continue;
|
|
562
|
+
}
|
|
563
|
+
if (isPlainObject(raw) && isStepLike(raw)) {
|
|
564
|
+
out[className] = await explodeStep(raw, channelDir, baseRel, counter.i++, usedPaths);
|
|
565
|
+
continue;
|
|
566
|
+
}
|
|
567
|
+
out[className] = await extractCode(raw, {
|
|
568
|
+
jsonDir: channelDir,
|
|
569
|
+
codeDir: channelDir,
|
|
570
|
+
friendly: null,
|
|
571
|
+
prefixParts: [baseRel, "elements", className],
|
|
572
|
+
usedPaths
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
return out;
|
|
576
|
+
}
|
|
577
|
+
async function explodeStepArray(steps, channelDir, baseRel, usedPaths, counter) {
|
|
578
|
+
const transformed = [];
|
|
579
|
+
for (const step of steps) {
|
|
580
|
+
transformed.push(await explodeStep(step, channelDir, baseRel, counter.i++, usedPaths));
|
|
581
|
+
}
|
|
582
|
+
return transformed;
|
|
583
|
+
}
|
|
584
|
+
async function explodeStep(step, channelDir, baseRel, index, usedPaths) {
|
|
585
|
+
if (!isPlainObject(step)) {
|
|
586
|
+
return step;
|
|
587
|
+
}
|
|
588
|
+
const seqRaw = step["sequenceNumber"];
|
|
589
|
+
let seq = index;
|
|
590
|
+
if (typeof seqRaw === "number") seq = seqRaw;
|
|
591
|
+
else if (typeof seqRaw === "string" && seqRaw.trim() !== "" && !Number.isNaN(Number(seqRaw))) {
|
|
592
|
+
seq = Number(seqRaw);
|
|
593
|
+
}
|
|
594
|
+
const n = seq + 1;
|
|
595
|
+
const stepName = step["name"];
|
|
596
|
+
const hasName = typeof stepName === "string" && stepName.trim().length > 0;
|
|
597
|
+
const friendlyBase = hasName ? `${baseRel}/${n}.${slug(stepName)}` : `${baseRel}/${n}`;
|
|
598
|
+
const out = {};
|
|
599
|
+
for (const [key, raw] of Object.entries(step)) {
|
|
600
|
+
if (CODE_KEY_SET.has(key) && typeof raw === "string") {
|
|
601
|
+
if (raw.trim().length === 0) {
|
|
602
|
+
out[key] = raw;
|
|
603
|
+
continue;
|
|
604
|
+
}
|
|
605
|
+
const filePath = resolveUnique(channelDir, `${friendlyBase}.js`, usedPaths);
|
|
606
|
+
await writeFileMkdir(filePath, raw);
|
|
607
|
+
out[key] = { "@file": relPosix(channelDir, filePath) };
|
|
608
|
+
continue;
|
|
609
|
+
}
|
|
610
|
+
out[key] = await extractCode(raw, {
|
|
611
|
+
jsonDir: channelDir,
|
|
612
|
+
codeDir: channelDir,
|
|
613
|
+
friendly: null,
|
|
614
|
+
prefixParts: [baseRel, String(index), key],
|
|
615
|
+
usedPaths
|
|
616
|
+
});
|
|
617
|
+
}
|
|
618
|
+
return out;
|
|
619
|
+
}
|
|
620
|
+
async function splitCollection(parent, containerKey, elementKey, root, serverDir, targetFor, usedSlugs, explodeResource) {
|
|
621
|
+
const container = parent[containerKey];
|
|
622
|
+
if (!isPlainObject(container)) return;
|
|
623
|
+
const raw = container[elementKey];
|
|
624
|
+
if (raw == null) return;
|
|
625
|
+
const wasArray = Array.isArray(raw);
|
|
626
|
+
const elements = asArray(raw);
|
|
627
|
+
const refs = [];
|
|
628
|
+
for (const el of elements) {
|
|
629
|
+
if (!isPlainObject(el)) {
|
|
630
|
+
refs.push(el);
|
|
631
|
+
continue;
|
|
632
|
+
}
|
|
633
|
+
const slugName = uniqueSlug(slug(el["name"]), usedSlugs);
|
|
634
|
+
const { jsonFile, resourceDir } = targetFor(el["name"], slugName);
|
|
635
|
+
const transformed = await explodeResource(el, resourceDir);
|
|
636
|
+
await writeJson(jsonFile, transformed);
|
|
637
|
+
refs.push({ "@ref": relPosix(serverDir, jsonFile) });
|
|
638
|
+
}
|
|
639
|
+
container[elementKey] = wasArray ? refs : refs[0];
|
|
640
|
+
}
|
|
641
|
+
async function explode(config, opts) {
|
|
642
|
+
await mkdir(opts.root, { recursive: true });
|
|
643
|
+
await explodeRoot.run(await realpath(opts.root), () => explodeInto(config, opts));
|
|
644
|
+
}
|
|
645
|
+
async function explodeInto(config, opts) {
|
|
646
|
+
const root = opts.root;
|
|
647
|
+
const serverDir = path.join(root, "server");
|
|
648
|
+
const skeleton = deepClone(config);
|
|
649
|
+
if (isPlainObject(skeleton["channels"])) {
|
|
650
|
+
const channelSlugs = /* @__PURE__ */ new Set();
|
|
651
|
+
await splitCollection(
|
|
652
|
+
skeleton,
|
|
653
|
+
"channels",
|
|
654
|
+
"channel",
|
|
655
|
+
root,
|
|
656
|
+
serverDir,
|
|
657
|
+
(_name, slugName) => {
|
|
658
|
+
const resourceDir = path.join(root, "channels", slugName);
|
|
659
|
+
return { jsonFile: path.join(resourceDir, "channel.json"), resourceDir };
|
|
660
|
+
},
|
|
661
|
+
channelSlugs,
|
|
662
|
+
async (el, resourceDir) => explodeChannelTree(el, resourceDir, /* @__PURE__ */ new Set())
|
|
663
|
+
);
|
|
664
|
+
}
|
|
665
|
+
if (isPlainObject(skeleton["codeTemplateLibraries"])) {
|
|
666
|
+
const libSlugs = /* @__PURE__ */ new Set();
|
|
667
|
+
await splitCollection(
|
|
668
|
+
skeleton,
|
|
669
|
+
"codeTemplateLibraries",
|
|
670
|
+
"codeTemplateLibrary",
|
|
671
|
+
root,
|
|
672
|
+
serverDir,
|
|
673
|
+
(_name, slugName) => {
|
|
674
|
+
const resourceDir = path.join(root, "codeTemplates", slugName);
|
|
675
|
+
return { jsonFile: path.join(resourceDir, "library.json"), resourceDir };
|
|
676
|
+
},
|
|
677
|
+
libSlugs,
|
|
678
|
+
async (el, resourceDir) => explodeLibrary(el, resourceDir)
|
|
679
|
+
);
|
|
680
|
+
}
|
|
681
|
+
if (isPlainObject(skeleton["channelGroups"])) {
|
|
682
|
+
const groupSlugs = /* @__PURE__ */ new Set();
|
|
683
|
+
await splitCollection(
|
|
684
|
+
skeleton,
|
|
685
|
+
"channelGroups",
|
|
686
|
+
"channelGroup",
|
|
687
|
+
root,
|
|
688
|
+
serverDir,
|
|
689
|
+
(_name, slugName) => {
|
|
690
|
+
const resourceDir = path.join(root, "channelGroups");
|
|
691
|
+
return { jsonFile: path.join(resourceDir, `${slugName}.json`), resourceDir };
|
|
692
|
+
},
|
|
693
|
+
groupSlugs,
|
|
694
|
+
async (el, resourceDir) => (
|
|
695
|
+
// group json lives in channelGroups/; sidecar code (rare) under same dir
|
|
696
|
+
extractCode(el, {
|
|
697
|
+
jsonDir: resourceDir,
|
|
698
|
+
codeDir: resourceDir,
|
|
699
|
+
friendly: null,
|
|
700
|
+
prefixParts: ["channelGroup"],
|
|
701
|
+
usedPaths: /* @__PURE__ */ new Set()
|
|
702
|
+
})
|
|
703
|
+
)
|
|
704
|
+
);
|
|
705
|
+
}
|
|
706
|
+
const finalSkeleton = await extractCode(skeleton, {
|
|
707
|
+
jsonDir: serverDir,
|
|
708
|
+
codeDir: serverDir,
|
|
709
|
+
friendly: null,
|
|
710
|
+
prefixParts: [],
|
|
711
|
+
usedPaths: /* @__PURE__ */ new Set()
|
|
712
|
+
});
|
|
713
|
+
await writeJson(path.join(serverDir, "configuration.json"), finalSkeleton);
|
|
714
|
+
}
|
|
715
|
+
async function explodeLibrary(library, resourceDir) {
|
|
716
|
+
const used = /* @__PURE__ */ new Set();
|
|
717
|
+
const usedTemplateSlugs = /* @__PURE__ */ new Set();
|
|
718
|
+
const out = {};
|
|
719
|
+
for (const [key, raw] of Object.entries(library)) {
|
|
720
|
+
if (key === "codeTemplates" && isPlainObject(raw)) {
|
|
721
|
+
out[key] = await explodeLibraryTemplates(raw, resourceDir, usedTemplateSlugs, used);
|
|
722
|
+
continue;
|
|
723
|
+
}
|
|
724
|
+
out[key] = await extractCode(raw, {
|
|
725
|
+
jsonDir: resourceDir,
|
|
726
|
+
codeDir: resourceDir,
|
|
727
|
+
friendly: null,
|
|
728
|
+
prefixParts: [key],
|
|
729
|
+
usedPaths: used
|
|
730
|
+
});
|
|
731
|
+
}
|
|
732
|
+
return out;
|
|
733
|
+
}
|
|
734
|
+
async function explodeLibraryTemplates(container, resourceDir, usedTemplateSlugs, usedPaths) {
|
|
735
|
+
const out = {};
|
|
736
|
+
for (const [key, raw] of Object.entries(container)) {
|
|
737
|
+
if (key === "codeTemplate" && raw != null) {
|
|
738
|
+
const wasArray = Array.isArray(raw);
|
|
739
|
+
const templates = asArray(raw);
|
|
740
|
+
const transformed = [];
|
|
741
|
+
for (const t of templates) {
|
|
742
|
+
transformed.push(
|
|
743
|
+
await explodeCodeTemplate(t, resourceDir, usedTemplateSlugs, usedPaths)
|
|
744
|
+
);
|
|
745
|
+
}
|
|
746
|
+
out[key] = wasArray ? transformed : transformed[0];
|
|
747
|
+
continue;
|
|
748
|
+
}
|
|
749
|
+
out[key] = await extractCode(raw, {
|
|
750
|
+
jsonDir: resourceDir,
|
|
751
|
+
codeDir: resourceDir,
|
|
752
|
+
friendly: null,
|
|
753
|
+
prefixParts: ["codeTemplates", key],
|
|
754
|
+
usedPaths
|
|
755
|
+
});
|
|
756
|
+
}
|
|
757
|
+
return out;
|
|
758
|
+
}
|
|
759
|
+
async function explodeCodeTemplate(template, resourceDir, usedTemplateSlugs, usedPaths) {
|
|
760
|
+
if (!isPlainObject(template)) return template;
|
|
761
|
+
const friendlyBase = uniqueSlug(slug(template["name"]), usedTemplateSlugs);
|
|
762
|
+
const out = {};
|
|
763
|
+
for (const [key, raw] of Object.entries(template)) {
|
|
764
|
+
if (key === "properties" && isPlainObject(raw)) {
|
|
765
|
+
out[key] = await explodeTemplateProperties(raw, resourceDir, friendlyBase, usedPaths);
|
|
766
|
+
continue;
|
|
767
|
+
}
|
|
768
|
+
if (CODE_KEY_SET.has(key) && typeof raw === "string") {
|
|
769
|
+
if (raw.trim().length === 0) {
|
|
770
|
+
out[key] = raw;
|
|
771
|
+
continue;
|
|
772
|
+
}
|
|
773
|
+
const filePath = resolveUnique(resourceDir, `${friendlyBase}.js`, usedPaths);
|
|
774
|
+
await writeFileMkdir(filePath, raw);
|
|
775
|
+
out[key] = { "@file": relPosix(resourceDir, filePath) };
|
|
776
|
+
continue;
|
|
777
|
+
}
|
|
778
|
+
out[key] = await extractCode(raw, {
|
|
779
|
+
jsonDir: resourceDir,
|
|
780
|
+
codeDir: resourceDir,
|
|
781
|
+
friendly: null,
|
|
782
|
+
prefixParts: ["codeTemplate", key],
|
|
783
|
+
usedPaths
|
|
784
|
+
});
|
|
785
|
+
}
|
|
786
|
+
return out;
|
|
787
|
+
}
|
|
788
|
+
async function explodeTemplateProperties(properties, resourceDir, friendlyBase, usedPaths) {
|
|
789
|
+
const out = {};
|
|
790
|
+
for (const [key, raw] of Object.entries(properties)) {
|
|
791
|
+
if (CODE_KEY_SET.has(key) && typeof raw === "string") {
|
|
792
|
+
if (raw.trim().length === 0) {
|
|
793
|
+
out[key] = raw;
|
|
794
|
+
continue;
|
|
795
|
+
}
|
|
796
|
+
const filePath = resolveUnique(resourceDir, `${friendlyBase}.js`, usedPaths);
|
|
797
|
+
await writeFileMkdir(filePath, raw);
|
|
798
|
+
out[key] = { "@file": relPosix(resourceDir, filePath) };
|
|
799
|
+
continue;
|
|
800
|
+
}
|
|
801
|
+
out[key] = await extractCode(raw, {
|
|
802
|
+
jsonDir: resourceDir,
|
|
803
|
+
codeDir: resourceDir,
|
|
804
|
+
friendly: null,
|
|
805
|
+
prefixParts: ["codeTemplate", "properties", key],
|
|
806
|
+
usedPaths
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
return out;
|
|
810
|
+
}
|
|
811
|
+
function resolveWithinRoot(root, jsonDir, rel) {
|
|
812
|
+
const target = path.resolve(jsonDir, rel);
|
|
813
|
+
if (target !== root && !target.startsWith(root + path.sep)) {
|
|
814
|
+
throw new Error(`marker path escapes the working tree: ${rel}`);
|
|
815
|
+
}
|
|
816
|
+
return target;
|
|
817
|
+
}
|
|
818
|
+
async function readWithinRoot(root, target, rel) {
|
|
819
|
+
const [realRoot, realTarget] = await Promise.all([realpath(root), realpath(target)]);
|
|
820
|
+
if (realTarget !== realRoot && !realTarget.startsWith(realRoot + path.sep)) {
|
|
821
|
+
throw new Error(`marker path escapes the working tree through a link: ${rel}`);
|
|
822
|
+
}
|
|
823
|
+
return readFile2(realTarget, "utf8");
|
|
824
|
+
}
|
|
825
|
+
async function resolveMarkers(value, jsonDir, root) {
|
|
826
|
+
if (Array.isArray(value)) {
|
|
827
|
+
const out = [];
|
|
828
|
+
for (const item of value) {
|
|
829
|
+
if (isRefMarker(item) && !existsSync(resolveWithinRoot(root, jsonDir, item["@ref"]))) continue;
|
|
830
|
+
out.push(await resolveMarkers(item, jsonDir, root));
|
|
831
|
+
}
|
|
832
|
+
return out;
|
|
833
|
+
}
|
|
834
|
+
if (isFileRef(value)) {
|
|
835
|
+
const target = resolveWithinRoot(root, jsonDir, value["@file"]);
|
|
836
|
+
return readWithinRoot(root, target, value["@file"]);
|
|
837
|
+
}
|
|
838
|
+
if (isRefMarker(value)) {
|
|
839
|
+
const target = resolveWithinRoot(root, jsonDir, value["@ref"]);
|
|
840
|
+
const text = await readWithinRoot(root, target, value["@ref"]);
|
|
841
|
+
const parsed = parseJson(text, target);
|
|
842
|
+
return resolveMarkers(parsed, path.dirname(target), root);
|
|
843
|
+
}
|
|
844
|
+
if (isPlainObject(value)) {
|
|
845
|
+
const out = {};
|
|
846
|
+
for (const [k, v] of Object.entries(value)) {
|
|
847
|
+
if (isRefMarker(v) && !existsSync(resolveWithinRoot(root, jsonDir, v["@ref"]))) continue;
|
|
848
|
+
out[k] = await resolveMarkers(v, jsonDir, root);
|
|
849
|
+
}
|
|
850
|
+
return out;
|
|
851
|
+
}
|
|
852
|
+
return value;
|
|
853
|
+
}
|
|
854
|
+
async function implode(opts) {
|
|
855
|
+
const root = path.resolve(opts.root);
|
|
856
|
+
const serverDir = path.join(root, "server");
|
|
857
|
+
const configPath = path.join(serverDir, "configuration.json");
|
|
858
|
+
const parsed = await readJson(configPath);
|
|
859
|
+
const resolved = await resolveMarkers(parsed, serverDir, root);
|
|
860
|
+
return resolved;
|
|
861
|
+
}
|
|
862
|
+
function createExplodeEngine() {
|
|
863
|
+
return { explode, implode };
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
// src/client/index.ts
|
|
867
|
+
import { CookieJar } from "tough-cookie";
|
|
868
|
+
import { Agent } from "undici";
|
|
869
|
+
|
|
870
|
+
// src/secrets/detect.ts
|
|
871
|
+
import { createHash } from "crypto";
|
|
872
|
+
|
|
873
|
+
// src/secrets/index.ts
|
|
874
|
+
var PLACEHOLDER = /\{\{env:([A-Za-z_][A-Za-z0-9_]*)\}\}/g;
|
|
875
|
+
var SECRET_KEY = /(password|passwd|passphrase|passcode|secret|token|pw|pwd|(?:api|access|secret|private)[_-]?key)$/i;
|
|
876
|
+
function hasPlaceholder(value) {
|
|
877
|
+
PLACEHOLDER.lastIndex = 0;
|
|
878
|
+
return PLACEHOLDER.test(value);
|
|
879
|
+
}
|
|
880
|
+
function isSecretKey(key) {
|
|
881
|
+
return SECRET_KEY.test(key);
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
// src/secrets/detect.ts
|
|
885
|
+
function regexSpans(re, group) {
|
|
886
|
+
return (value) => {
|
|
887
|
+
const out = [];
|
|
888
|
+
for (const m of value.matchAll(re)) {
|
|
889
|
+
const secret = m[group];
|
|
890
|
+
if (secret === void 0) continue;
|
|
891
|
+
const start = m.index + m[0].lastIndexOf(secret);
|
|
892
|
+
out.push({ start, end: start + secret.length });
|
|
893
|
+
}
|
|
894
|
+
return out;
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
function dbConnectionSpans(value) {
|
|
898
|
+
const out = [];
|
|
899
|
+
for (const m of value.matchAll(/createDatabaseConnection\s*\(/g)) {
|
|
900
|
+
let depth = 0;
|
|
901
|
+
let quote = null;
|
|
902
|
+
let argStart = m.index + m[0].length;
|
|
903
|
+
const args = [];
|
|
904
|
+
for (let i = argStart; i < value.length; i += 1) {
|
|
905
|
+
const c = value[i];
|
|
906
|
+
if (quote) {
|
|
907
|
+
if (c === "\\") i += 1;
|
|
908
|
+
else if (c === quote) quote = null;
|
|
909
|
+
continue;
|
|
910
|
+
}
|
|
911
|
+
if (c === '"' || c === "'") quote = c;
|
|
912
|
+
else if (c === "(" || c === "[" || c === "{") depth += 1;
|
|
913
|
+
else if ((c === ")" || c === "]" || c === "}") && depth > 0) depth -= 1;
|
|
914
|
+
else if (c === "," && depth === 0 || c === ")") {
|
|
915
|
+
args.push({ start: argStart, end: i });
|
|
916
|
+
argStart = i + 1;
|
|
917
|
+
if (c === ")") break;
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
const pw = args[3];
|
|
921
|
+
if (!pw) continue;
|
|
922
|
+
const literal = /^\s*(["'])(.+)\1\s*$/s.exec(value.slice(pw.start, pw.end));
|
|
923
|
+
if (literal) {
|
|
924
|
+
const start = value.indexOf(literal[2], pw.start);
|
|
925
|
+
out.push({ start, end: start + literal[2].length });
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
return out;
|
|
929
|
+
}
|
|
930
|
+
var ASSIGNED = String.raw`["']?\s*[:=]\s*(?:[\w$.[\]'"]+\s*(?:\|\||\?\?)\s*)?(["'])((?=\S)(?:[^"'{}\s]{4,}|(?=[^"'{}\n]*[0-9@#$%^&*+=~|\\/<>_])[^"'{}\n]{4,}))\1`;
|
|
931
|
+
var CONN_VALUE = String.raw`([^;&'"\s](?:[^;&'"\n]*[^;&'"\s])?)`;
|
|
932
|
+
function textSpans(code) {
|
|
933
|
+
const out = [];
|
|
934
|
+
let i = 0;
|
|
935
|
+
while (i < code.length) {
|
|
936
|
+
const c = code[i];
|
|
937
|
+
const next = code[i + 1];
|
|
938
|
+
if (c === "/" && (next === "/" || next === "*")) {
|
|
939
|
+
const close = next === "/" ? code.indexOf("\n", i) : code.indexOf("*/", i + 2);
|
|
940
|
+
const end = close < 0 ? code.length : close;
|
|
941
|
+
out.push({ start: i + 2, end });
|
|
942
|
+
i = end + 2;
|
|
943
|
+
} else if (c === '"' || c === "'" || c === "`") {
|
|
944
|
+
let j = i + 1;
|
|
945
|
+
while (j < code.length && code[j] !== c && (c === "`" || code[j] !== "\n")) j += code[j] === "\\" ? 2 : 1;
|
|
946
|
+
out.push({ start: i + 1, end: Math.min(j, code.length) });
|
|
947
|
+
i = j + 1;
|
|
948
|
+
} else {
|
|
949
|
+
i += 1;
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
return out;
|
|
953
|
+
}
|
|
954
|
+
function outsideCode(spans) {
|
|
955
|
+
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);
|
|
956
|
+
}
|
|
957
|
+
var RULES = [
|
|
958
|
+
{
|
|
959
|
+
kind: "private-key",
|
|
960
|
+
suffix: "PRIVATE_KEY",
|
|
961
|
+
spans: regexSpans(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, 0)
|
|
962
|
+
},
|
|
963
|
+
{ kind: "aws-access-key", suffix: "AWS_ACCESS_KEY", spans: regexSpans(/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, 0) },
|
|
964
|
+
{ 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) },
|
|
965
|
+
{ kind: "github-token", suffix: "TOKEN", spans: regexSpans(/\b(?:ghp|gho|ghs|ghu|github_pat)_[A-Za-z0-9_]{20,}/g, 0) },
|
|
966
|
+
{ kind: "slack-token", suffix: "TOKEN", spans: regexSpans(/\bxox[abprs]-[A-Za-z0-9-]{10,}/g, 0) },
|
|
967
|
+
// user:password@host. The user part stops at ';', '?' and '&' so a JDBC
|
|
968
|
+
// parameter like `user=svc@srv` is not mistaken for credentials.
|
|
969
|
+
{ kind: "url-credentials", suffix: "PASSWORD", spans: regexSpans(/\b[a-z][a-z0-9+.-]*:\/\/[^\s:/@'";?&]+:([^\s@'"/;?&]+)@/gi, 1) },
|
|
970
|
+
// Drivers trim around `=` and the value, so spaces are allowed there. In a
|
|
971
|
+
// script only string literals and comments are searched: `pwd=$('x')` is code.
|
|
972
|
+
{
|
|
973
|
+
kind: "connection-string",
|
|
974
|
+
suffix: "PASSWORD",
|
|
975
|
+
spans: outsideCode(regexSpans(new RegExp(String.raw`[;?&]\s*(?:password|pwd)\s*=\s*${CONN_VALUE}`, "gi"), 1))
|
|
976
|
+
},
|
|
977
|
+
// Leading the whole value (`Password=…;Server=…`), when another key=value follows.
|
|
978
|
+
{
|
|
979
|
+
kind: "connection-string",
|
|
980
|
+
suffix: "PASSWORD",
|
|
981
|
+
spans: outsideCode(regexSpans(new RegExp(String.raw`^\s*(?:password|pwd)\s*=\s*${CONN_VALUE}(?=\s*;\s*[\w ]+=)`, "gi"), 1))
|
|
982
|
+
},
|
|
983
|
+
// Case-sensitive, and the credential must contain a digit or a base64/token
|
|
984
|
+
// symbol, so prose like "Basic authentication" does not match.
|
|
985
|
+
{
|
|
986
|
+
kind: "authorization-header",
|
|
987
|
+
suffix: "TOKEN",
|
|
988
|
+
spans: regexSpans(/\b(?:Basic|Bearer)\s+((?=[A-Za-z0-9+/=._~-]*[0-9+/=])[A-Za-z0-9+/=._~-]{12,})/g, 1)
|
|
989
|
+
},
|
|
990
|
+
{ kind: "db-connection-call", suffix: "DB_PASSWORD", spans: dbConnectionSpans },
|
|
991
|
+
// name = 'literal' where the name ends in a secret word: password, dbPassword,
|
|
992
|
+
// db_password, DB_PASSWORD, apiKey, authToken… (not tokenizer, not ==).
|
|
993
|
+
// Also the default-value idiom: apiKey = apiKey || 'literal' (or ??).
|
|
994
|
+
{
|
|
995
|
+
kind: "assignment",
|
|
996
|
+
suffix: "PASSWORD",
|
|
997
|
+
spans: regexSpans(new RegExp(`(?<![\\w$])[\\w$]*?(?:password|passwd|pwd|secret|api[_-]?key|access[_-]?key|token)${ASSIGNED}`, "gi"), 2)
|
|
998
|
+
},
|
|
999
|
+
// `pass` as a whole name or a word boundary within one (pass, dbPass,
|
|
1000
|
+
// DB_PASS, sftp_pass), case-sensitive so bypass and compass don't match,
|
|
1001
|
+
// and not after words that make it an ordinary noun (byPass, firstPass).
|
|
1002
|
+
{
|
|
1003
|
+
kind: "assignment",
|
|
1004
|
+
suffix: "PASSWORD",
|
|
1005
|
+
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)
|
|
1006
|
+
},
|
|
1007
|
+
// conn.setPassword('literal'), props.setApiKey("literal")…
|
|
1008
|
+
{
|
|
1009
|
+
kind: "setter-call",
|
|
1010
|
+
suffix: "PASSWORD",
|
|
1011
|
+
spans: regexSpans(/\bset[A-Za-z]*(?:Password|Passwd|Passphrase|Secret|Token|ApiKey)\s*\(\s*(["'])([^"'\n]{4,})\1\s*\)/g, 2)
|
|
1012
|
+
}
|
|
1013
|
+
];
|
|
1014
|
+
function isReference(secret) {
|
|
1015
|
+
return secret.includes("${") || hasPlaceholder(secret);
|
|
1016
|
+
}
|
|
1017
|
+
function hitsIn(value, script = false) {
|
|
1018
|
+
const taken = [];
|
|
1019
|
+
for (const rule of RULES) {
|
|
1020
|
+
for (const span of rule.spans(value, script)) {
|
|
1021
|
+
if (span.end <= span.start || isReference(value.slice(span.start, span.end))) continue;
|
|
1022
|
+
if (taken.some((t) => span.start < t.end && t.start < span.end)) continue;
|
|
1023
|
+
taken.push({ ...span, rule });
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
return taken.sort((a, b) => a.start - b.start);
|
|
1027
|
+
}
|
|
1028
|
+
var SCRIPT_KEYS = /* @__PURE__ */ new Set([...CODE_KEYS, ...CHANNEL_SCRIPT_KEYS]);
|
|
1029
|
+
function redactSecretsInText(text) {
|
|
1030
|
+
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);
|
|
1031
|
+
let out = "";
|
|
1032
|
+
let at = 0;
|
|
1033
|
+
for (const h of hitsIn(value)) {
|
|
1034
|
+
out += `${value.slice(at, h.start)}<redacted ${h.rule.kind}>`;
|
|
1035
|
+
at = h.end;
|
|
1036
|
+
}
|
|
1037
|
+
return out + value.slice(at);
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
// src/client/index.ts
|
|
1041
|
+
function connectionError(url, err) {
|
|
1042
|
+
let cause = err instanceof Error ? err.cause : void 0;
|
|
1043
|
+
if (cause instanceof AggregateError && cause.errors[0] instanceof Error) cause = cause.errors[0];
|
|
1044
|
+
const detail = cause?.message || (err instanceof Error ? err.message : String(err));
|
|
1045
|
+
const code = cause?.code;
|
|
1046
|
+
const error = new Error(
|
|
1047
|
+
`cannot reach ${new URL(url).origin}: ${detail}${code && !detail.includes(code) ? ` (${code})` : ""}`,
|
|
1048
|
+
{ cause: err }
|
|
1049
|
+
);
|
|
1050
|
+
error.code = code;
|
|
1051
|
+
return error;
|
|
1052
|
+
}
|
|
1053
|
+
var SERVER_CONFIG_KEY = "serverConfiguration";
|
|
1054
|
+
function unwrapSingleKey(value) {
|
|
1055
|
+
const keys = Object.keys(value);
|
|
1056
|
+
if (keys.length === 1) {
|
|
1057
|
+
return value[keys[0]];
|
|
1058
|
+
}
|
|
1059
|
+
return value;
|
|
1060
|
+
}
|
|
1061
|
+
var MirthClientImpl = class {
|
|
1062
|
+
config;
|
|
1063
|
+
baseUrl;
|
|
1064
|
+
cookieJar;
|
|
1065
|
+
/** Our own pool (not the global one) so `close()` can release it. */
|
|
1066
|
+
dispatcher;
|
|
1067
|
+
authenticated = false;
|
|
1068
|
+
/** Single in-flight login promise (concurrency guard). */
|
|
1069
|
+
loginPromise = null;
|
|
1070
|
+
constructor(config) {
|
|
1071
|
+
this.config = config;
|
|
1072
|
+
const protocol = config.https !== false ? "https" : "http";
|
|
1073
|
+
this.baseUrl = `${protocol}://${config.host}:${config.port}/api`;
|
|
1074
|
+
this.cookieJar = new CookieJar();
|
|
1075
|
+
this.dispatcher = new Agent(config.disableTlsCheck ? { connect: { rejectUnauthorized: false } } : {});
|
|
1076
|
+
}
|
|
1077
|
+
isAuthenticated() {
|
|
1078
|
+
return this.authenticated;
|
|
1079
|
+
}
|
|
1080
|
+
/**
|
|
1081
|
+
* Establish a session. Concurrent calls share a single in-flight login.
|
|
1082
|
+
*/
|
|
1083
|
+
async login() {
|
|
1084
|
+
if (this.loginPromise) {
|
|
1085
|
+
return this.loginPromise;
|
|
1086
|
+
}
|
|
1087
|
+
this.loginPromise = (async () => {
|
|
1088
|
+
try {
|
|
1089
|
+
const loginUrl = `${this.baseUrl}/users/_login`;
|
|
1090
|
+
const body = new URLSearchParams({
|
|
1091
|
+
username: this.config.username,
|
|
1092
|
+
password: this.config.password
|
|
1093
|
+
});
|
|
1094
|
+
const response = await this.send(loginUrl, {
|
|
1095
|
+
method: "POST",
|
|
1096
|
+
headers: {
|
|
1097
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
1098
|
+
"X-Requested-With": "XMLHttpRequest",
|
|
1099
|
+
Accept: "application/json"
|
|
1100
|
+
},
|
|
1101
|
+
body: body.toString()
|
|
1102
|
+
});
|
|
1103
|
+
await this.storeCookies(response, this.baseUrl);
|
|
1104
|
+
if (!response.ok) {
|
|
1105
|
+
await response.body?.cancel();
|
|
1106
|
+
throw new Error(`Login failed: HTTP ${response.status} ${response.statusText}`.trimEnd());
|
|
1107
|
+
}
|
|
1108
|
+
const result = await response.json();
|
|
1109
|
+
const payload = unwrapSingleKey(result);
|
|
1110
|
+
if (payload.status !== "SUCCESS") {
|
|
1111
|
+
throw new Error(`Login failed: ${payload.status} - ${payload.message ?? "Unknown error"}`);
|
|
1112
|
+
}
|
|
1113
|
+
this.authenticated = true;
|
|
1114
|
+
} finally {
|
|
1115
|
+
this.loginPromise = null;
|
|
1116
|
+
}
|
|
1117
|
+
})();
|
|
1118
|
+
return this.loginPromise;
|
|
1119
|
+
}
|
|
1120
|
+
/**
|
|
1121
|
+
* End the session and clear local auth state + cookies.
|
|
1122
|
+
*/
|
|
1123
|
+
async logout() {
|
|
1124
|
+
if (!this.authenticated) {
|
|
1125
|
+
return;
|
|
1126
|
+
}
|
|
1127
|
+
try {
|
|
1128
|
+
const logoutUrl = `${this.baseUrl}/users/_logout`;
|
|
1129
|
+
const cookieString = await this.cookieJar.getCookieString(logoutUrl);
|
|
1130
|
+
await this.send(logoutUrl, {
|
|
1131
|
+
method: "POST",
|
|
1132
|
+
headers: {
|
|
1133
|
+
"X-Requested-With": "XMLHttpRequest",
|
|
1134
|
+
...cookieString ? { Cookie: cookieString } : {}
|
|
1135
|
+
}
|
|
1136
|
+
});
|
|
1137
|
+
} finally {
|
|
1138
|
+
this.authenticated = false;
|
|
1139
|
+
await this.cookieJar.removeAllCookies();
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
/**
|
|
1143
|
+
* GET /server/configuration -> canonical config.
|
|
1144
|
+
*
|
|
1145
|
+
* Requests JSON, parses it, and unwraps the single top-level
|
|
1146
|
+
* `serverConfiguration` key (defensively: any single-key wrapper is unwrapped;
|
|
1147
|
+
* a multi-key object is returned as-is).
|
|
1148
|
+
*/
|
|
1149
|
+
async getServerConfiguration() {
|
|
1150
|
+
const response = await this.request("GET", "/server/configuration", {
|
|
1151
|
+
headers: { Accept: "application/json" }
|
|
1152
|
+
});
|
|
1153
|
+
const json = await response.json();
|
|
1154
|
+
return unwrapSingleKey(json);
|
|
1155
|
+
}
|
|
1156
|
+
/**
|
|
1157
|
+
* PUT /server/configuration <- canonical config.
|
|
1158
|
+
*
|
|
1159
|
+
* Re-wraps the canonical config as `{ serverConfiguration: config }` and
|
|
1160
|
+
* forwards the optional `deploy` / `overwriteConfigMap` flags as query params.
|
|
1161
|
+
*/
|
|
1162
|
+
async putServerConfiguration(config, options = {}) {
|
|
1163
|
+
const query = {};
|
|
1164
|
+
if (options.deploy !== void 0) {
|
|
1165
|
+
query.deploy = options.deploy;
|
|
1166
|
+
}
|
|
1167
|
+
if (options.overwriteConfigMap !== void 0) {
|
|
1168
|
+
query.overwriteConfigMap = options.overwriteConfigMap;
|
|
1169
|
+
}
|
|
1170
|
+
const wrapped = { [SERVER_CONFIG_KEY]: config };
|
|
1171
|
+
await this.request("PUT", "/server/configuration", {
|
|
1172
|
+
query,
|
|
1173
|
+
headers: {
|
|
1174
|
+
"Content-Type": "application/json",
|
|
1175
|
+
Accept: "application/json"
|
|
1176
|
+
},
|
|
1177
|
+
body: JSON.stringify(wrapped)
|
|
1178
|
+
});
|
|
1179
|
+
}
|
|
1180
|
+
async getServerId() {
|
|
1181
|
+
const response = await this.request("GET", "/server/id", { headers: { Accept: "text/plain" } });
|
|
1182
|
+
return (await response.text()).trim();
|
|
1183
|
+
}
|
|
1184
|
+
async getServerConfigurationXml() {
|
|
1185
|
+
const response = await this.request("GET", "/server/configuration", { headers: { Accept: "application/xml" } });
|
|
1186
|
+
return response.text();
|
|
1187
|
+
}
|
|
1188
|
+
async putServerConfigurationXml(xml, options = {}) {
|
|
1189
|
+
await this.request("PUT", "/server/configuration", {
|
|
1190
|
+
query: { deploy: options.deploy, overwriteConfigMap: options.overwriteConfigMap },
|
|
1191
|
+
headers: { "Content-Type": "application/xml", Accept: "application/json" },
|
|
1192
|
+
body: xml
|
|
1193
|
+
});
|
|
1194
|
+
}
|
|
1195
|
+
// --- per-resource ---------------------------------------------------------
|
|
1196
|
+
// Override is on: Mirth does not reject a stale revision anyway (verified on
|
|
1197
|
+
// 4.5.2), so conflict detection happens in the push planner instead.
|
|
1198
|
+
async getChannel(id) {
|
|
1199
|
+
const response = await this.request("GET", `/channels/${encodeURIComponent(id)}`, {
|
|
1200
|
+
headers: { Accept: "application/json" }
|
|
1201
|
+
});
|
|
1202
|
+
const text = await response.text();
|
|
1203
|
+
if (text.trim() === "") return null;
|
|
1204
|
+
return unwrapSingleKey(JSON.parse(text));
|
|
1205
|
+
}
|
|
1206
|
+
async close() {
|
|
1207
|
+
await this.dispatcher.close();
|
|
1208
|
+
}
|
|
1209
|
+
async putChannel(channel) {
|
|
1210
|
+
await this.sendJson("PUT", `/channels/${encodeURIComponent(String(channel.id))}`, { channel }, { override: true });
|
|
1211
|
+
}
|
|
1212
|
+
async deleteChannel(id) {
|
|
1213
|
+
await this.request("DELETE", `/channels/${encodeURIComponent(id)}`);
|
|
1214
|
+
}
|
|
1215
|
+
async putCodeTemplate(template) {
|
|
1216
|
+
await this.sendJson("PUT", `/codeTemplates/${encodeURIComponent(String(template.id))}`, { codeTemplate: template }, { override: true });
|
|
1217
|
+
}
|
|
1218
|
+
async deleteCodeTemplate(id) {
|
|
1219
|
+
await this.request("DELETE", `/codeTemplates/${encodeURIComponent(id)}`);
|
|
1220
|
+
}
|
|
1221
|
+
async putCodeTemplateLibraries(libraries) {
|
|
1222
|
+
await this.sendJson("PUT", "/codeTemplateLibraries", { list: { codeTemplateLibrary: libraries } }, { override: true });
|
|
1223
|
+
}
|
|
1224
|
+
async putGlobalScripts(globalScripts) {
|
|
1225
|
+
await this.sendJson("PUT", "/server/globalScripts", { map: globalScripts });
|
|
1226
|
+
}
|
|
1227
|
+
async getDeployedChannelIds() {
|
|
1228
|
+
const response = await this.request("GET", "/channels/statuses", { headers: { Accept: "application/json" } });
|
|
1229
|
+
const text = await response.text();
|
|
1230
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1231
|
+
for (const m of text.matchAll(/"channelId"\s*:\s*"([^"]+)"/g)) ids.add(m[1]);
|
|
1232
|
+
return ids;
|
|
1233
|
+
}
|
|
1234
|
+
async deployChannel(id) {
|
|
1235
|
+
await this.request("POST", `/channels/${encodeURIComponent(id)}/_deploy`, { query: { returnErrors: true } });
|
|
1236
|
+
}
|
|
1237
|
+
/** Send a JSON body; Mirth answers some updates with `{"boolean": false}` instead of an error status. */
|
|
1238
|
+
async sendJson(method, path2, body, query) {
|
|
1239
|
+
const response = await this.request(method, path2, {
|
|
1240
|
+
query,
|
|
1241
|
+
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
1242
|
+
body: JSON.stringify(body)
|
|
1243
|
+
});
|
|
1244
|
+
const text = await response.text();
|
|
1245
|
+
if (/^\s*\{\s*"boolean"\s*:\s*false\s*\}\s*$/.test(text)) {
|
|
1246
|
+
throw new Error(`${method} ${path2}: the server refused the update`);
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
// --- internal transport ---------------------------------------------------
|
|
1250
|
+
/**
|
|
1251
|
+
* Make an authenticated request. Ensures login, attaches/stores cookies, and
|
|
1252
|
+
* on a 401 while authenticated resets auth, re-logs in once, and retries.
|
|
1253
|
+
* Throws an {@link ApiError}-shaped error on a non-2xx response.
|
|
1254
|
+
*/
|
|
1255
|
+
async request(method, path2, options = {}, isRetry = false) {
|
|
1256
|
+
if (!this.authenticated) {
|
|
1257
|
+
await this.login();
|
|
1258
|
+
}
|
|
1259
|
+
const url = this.buildUrl(path2, options.query);
|
|
1260
|
+
const headers = {
|
|
1261
|
+
"X-Requested-With": "XMLHttpRequest",
|
|
1262
|
+
...options.headers
|
|
1263
|
+
};
|
|
1264
|
+
const cookieString = await this.cookieJar.getCookieString(url);
|
|
1265
|
+
if (cookieString) {
|
|
1266
|
+
headers.Cookie = cookieString;
|
|
1267
|
+
}
|
|
1268
|
+
const response = await this.send(url, { method, headers, body: options.body });
|
|
1269
|
+
await this.storeCookies(response, url);
|
|
1270
|
+
if (response.status === 401 && this.authenticated && !isRetry) {
|
|
1271
|
+
this.authenticated = false;
|
|
1272
|
+
await this.login();
|
|
1273
|
+
return this.request(method, path2, options, true);
|
|
1274
|
+
}
|
|
1275
|
+
if (!response.ok) {
|
|
1276
|
+
throw await this.toApiError(response);
|
|
1277
|
+
}
|
|
1278
|
+
return response;
|
|
1279
|
+
}
|
|
1280
|
+
/** fetch through this client's pool, with network failures explained. */
|
|
1281
|
+
async send(url, init) {
|
|
1282
|
+
try {
|
|
1283
|
+
return await fetch(url, {
|
|
1284
|
+
...init,
|
|
1285
|
+
// @ts-expect-error - dispatcher is a Node.js/undici specific option
|
|
1286
|
+
dispatcher: this.dispatcher
|
|
1287
|
+
});
|
|
1288
|
+
} catch (err) {
|
|
1289
|
+
throw connectionError(url, err);
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
/** Build an absolute URL with an optional query string. */
|
|
1293
|
+
buildUrl(path2, query) {
|
|
1294
|
+
const url = `${this.baseUrl}${path2}`;
|
|
1295
|
+
if (!query || Object.keys(query).length === 0) {
|
|
1296
|
+
return url;
|
|
1297
|
+
}
|
|
1298
|
+
const searchParams = new URLSearchParams();
|
|
1299
|
+
for (const [key, value] of Object.entries(query)) {
|
|
1300
|
+
if (value === void 0 || value === null) {
|
|
1301
|
+
continue;
|
|
1302
|
+
}
|
|
1303
|
+
searchParams.append(key, String(value));
|
|
1304
|
+
}
|
|
1305
|
+
const qs = searchParams.toString();
|
|
1306
|
+
return qs ? `${url}?${qs}` : url;
|
|
1307
|
+
}
|
|
1308
|
+
/** Persist any `set-cookie` from a response into the jar. */
|
|
1309
|
+
async storeCookies(response, url) {
|
|
1310
|
+
for (const cookie of response.headers.getSetCookie()) {
|
|
1311
|
+
await this.cookieJar.setCookie(cookie, url);
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
/** Build an ApiError-shaped Error from a non-2xx response. */
|
|
1315
|
+
async toApiError(response) {
|
|
1316
|
+
let body;
|
|
1317
|
+
try {
|
|
1318
|
+
body = await response.text();
|
|
1319
|
+
} catch {
|
|
1320
|
+
}
|
|
1321
|
+
const text = typeof body === "string" ? redactSecretsInText(readableBody(body)).trim() : "";
|
|
1322
|
+
const reason = text === "" ? "" : this.config.includeResponseBodies ? `: ${text}` : " (server response withheld; it may echo credentials)";
|
|
1323
|
+
const message = `HTTP ${response.status}: ${response.statusText}${reason}`;
|
|
1324
|
+
const error = new Error(message);
|
|
1325
|
+
error.status = response.status;
|
|
1326
|
+
error.statusText = response.statusText;
|
|
1327
|
+
error.message = message;
|
|
1328
|
+
error.body = text;
|
|
1329
|
+
return error;
|
|
1330
|
+
}
|
|
1331
|
+
};
|
|
1332
|
+
var XML_ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
|
|
1333
|
+
function readableBody(body) {
|
|
1334
|
+
const trimmed = body.trim();
|
|
1335
|
+
if (/^[[{"]/.test(trimmed)) {
|
|
1336
|
+
try {
|
|
1337
|
+
return flattenJson(JSON.parse(trimmed));
|
|
1338
|
+
} catch {
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
if (!trimmed.startsWith("<")) return trimmed;
|
|
1342
|
+
if (/^<(!doctype|html)/i.test(trimmed)) return "";
|
|
1343
|
+
const REDACTED = "\0redacted\0";
|
|
1344
|
+
return trimmed.replace(/<([\w.:-]+)>[^<]*<\/\1>/g, (whole, key) => isSecretKey(key) ? ` ${key}: ${REDACTED} ` : whole).replace(/<[^>]*>/g, " ").split(REDACTED).join("<redacted>").replace(
|
|
1345
|
+
/&(#x[0-9a-f]+|#[0-9]+|amp|lt|gt|quot|apos);/gi,
|
|
1346
|
+
(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
|
|
1347
|
+
);
|
|
1348
|
+
}
|
|
1349
|
+
function flattenJson(value, key = "") {
|
|
1350
|
+
if (typeof value === "string") return key !== "" && isSecretKey(key) && value !== "" ? "<redacted>" : value;
|
|
1351
|
+
if (Array.isArray(value)) return value.map((v) => flattenJson(v, key)).join("; ");
|
|
1352
|
+
if (value !== null && typeof value === "object") {
|
|
1353
|
+
return Object.entries(value).map(([k, v]) => `${k}: ${flattenJson(v, k)}`).join(", ");
|
|
1354
|
+
}
|
|
1355
|
+
return String(value);
|
|
1356
|
+
}
|
|
1357
|
+
function createMirthClient(config) {
|
|
1358
|
+
return new MirthClientImpl(config);
|
|
1359
|
+
}
|
|
1360
|
+
export {
|
|
1361
|
+
CHANNEL_SCRIPT_KEYS,
|
|
1362
|
+
CODE_KEYS,
|
|
1363
|
+
XmlConfigAdapter,
|
|
1364
|
+
createExplodeEngine,
|
|
1365
|
+
createMirthClient,
|
|
1366
|
+
isFileRef
|
|
1367
|
+
};
|
|
1368
|
+
//# sourceMappingURL=index.js.map
|