@ubercode/channelvault 0.2.1 → 0.3.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/explode/index.ts","../src/types.ts","../src/json.ts","../src/xml/index.ts","../src/client/index.ts","../src/secrets/detect.ts","../src/secrets/index.ts","../src/push/index.ts","../src/push/apply.ts","../src/secrets/envfile.ts","../src/backup/index.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * channelvault CLI — git-style pull/push/diff for Mirth Connect.\n *\n * channelvault explode <backup.xml> <dir> XML -> tree\n * channelvault implode <dir> <backup.xml> tree -> XML\n * channelvault pull <dir> live server -> tree\n * channelvault push <dir> tree -> live server\n * channelvault diff <dir> tree vs live server\n * channelvault status <dir> summary of the working tree\n */\n\nimport { spawnSync } from 'node:child_process';\nimport { mkdir, mkdtemp, readdir, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { createRequire } from 'node:module';\nimport * as path from 'node:path';\nimport { createInterface } from 'node:readline/promises';\n\nimport { Command, CommanderError } from 'commander';\n\nimport { createExplodeEngine } from './explode/index.js';\nimport { XmlConfigAdapter } from './xml/index.js';\nimport { createMirthClient, UNTRUSTED_CERT_CODES, type MirthClientExt } from './client/index.js';\nimport {\n changedSince,\n channelsOf,\n knownAfterPush,\n librariesOf,\n savedChangeMatches,\n knownFrom,\n newerOnServer,\n normalizeEolDeep,\n withoutVolatile,\n planPush,\n resourceIds,\n sameServerConfig,\n type Change,\n type Known,\n type Plan,\n type Scope,\n} from './push/index.js';\nimport { applyPlan, deployChannels, refreshRevisions } from './push/apply.js';\nimport { mapLeaves, redactKnownSecrets, render, templatize } from './secrets/index.js';\nimport { backupEnvFile, ensureEnvIgnored, readEnvFile, updateEnvFile } from './secrets/envfile.js';\nimport { findEchoes, formatFindings, scanSecrets, type AllowEntry } from './secrets/detect.js';\nimport { backupName, backupsOf, compareVersions, configuredName, DEFAULT_BACKUP_DIR, DEFAULT_KEEP, MANIFEST, numericVersion, originOf, originsIn, saveBackup, writePrivate } from './backup/index.js';\nimport { readJson } from './json.js';\nimport type { CanonicalConfig, ClientConfig, Json } from './types.js';\n\nconst engine = createExplodeEngine();\nconst xml = new XmlConfigAdapter();\n\n/** From package.json, one level up from both src/cli.ts and dist/cli.js. */\nconst VERSION = (createRequire(import.meta.url)('../package.json') as { version: string }).version;\n\n// --- helpers --------------------------------------------------------------\n\n/** A user-facing error: printed without a stack trace. */\nclass CliError extends Error {}\n\n/**\n * Abort the command. Throws rather than calling process.exit so open\n * connections close first; exiting while undici sockets are closing crashes\n * Node on Windows with a libuv assertion.\n */\nfunction fail(message: string): never {\n throw new CliError(message);\n}\n\n/** Exit status for an error. `diff` uses 2, because its 1 means \"differences found\". */\nlet errorExitCode = 1;\n\n/** Directories under a working tree that `explode` owns (cleared before a pull). */\nconst MANAGED_DIRS = ['server', 'channels', 'codeTemplates', 'channelGroups'];\n\n/** Where `replaceTree` explodes before swapping in; removed before and after. */\nconst STAGING_DIR = '.channelvault-staging';\n\n/**\n * Recursive-remove options. `maxRetries` is essential on Windows, where a\n * recursive delete can transiently fail with EBUSY/ENOTEMPTY/EPERM while the OS\n * releases just-closed handles; `fs.rm` retries those specific errors.\n */\nconst RM_OPTS = { recursive: true, force: true, maxRetries: 5, retryDelay: 50 } as const;\n\ninterface ConnectionFlags {\n host?: string;\n port?: string;\n user?: string;\n pass?: string;\n insecure?: boolean;\n https?: boolean;\n}\n\n/** Resolve server connection from flags, falling back to MIRTH_* env vars. */\nfunction resolveClientConfig(flags: ConnectionFlags): ClientConfig {\n const host = flags.host ?? process.env.MIRTH_HOST;\n const portStr = flags.port ?? process.env.MIRTH_PORT;\n const username = flags.user ?? process.env.MIRTH_USER;\n const password = flags.pass ?? process.env.MIRTH_PASS;\n\n if (!host) fail('no server host (pass --host or set MIRTH_HOST)');\n if (!portStr) fail('no server port (pass --port or set MIRTH_PORT)');\n if (!username) fail('no username (pass --user or set MIRTH_USER)');\n if (password == null) fail('no password (pass --pass or set MIRTH_PASS)');\n\n const port = Number(portStr);\n if (!Number.isInteger(port)) fail(`invalid port: ${portStr}`);\n\n return {\n host,\n port,\n username,\n password,\n https: flags.https !== false,\n disableTlsCheck: flags.insecure === true,\n // Opt-in: error bodies can echo credentials (see `scrub`, applied to all output).\n includeResponseBodies: Boolean(process.env.CHANNELVAULT_DEBUG),\n };\n}\n\nfunction addConnectionFlags(cmd: Command): Command {\n return cmd\n .option('--host <host>', 'Mirth server host (env MIRTH_HOST)')\n .option('--port <port>', 'Mirth server port (env MIRTH_PORT)')\n .option('--user <user>', 'username (env MIRTH_USER)')\n .option('--pass <pass>', 'password (env MIRTH_PASS)')\n .option('--insecure', 'allow self-signed TLS certificates', false)\n .option('--no-https', 'use http instead of https');\n}\n\nasync function withClient<T>(flags: ConnectionFlags, fn: (client: MirthClientExt) => Promise<T>): Promise<T> {\n const client = createMirthClient(resolveClientConfig(flags));\n try {\n await client.login();\n return await fn(client);\n } finally {\n await client.logout().catch(() => undefined);\n await client.close().catch(() => undefined);\n }\n}\n\n// --- JSON output --------------------------------------------------------------\n\ninterface JsonFlags {\n json?: boolean;\n}\n\n/**\n * `--json`: one JSON document on stdout, for scripts and agents. Errors still\n * go to stderr with the command's exit code; notes move into the document.\n */\nfunction addJsonFlag(cmd: Command): Command {\n return cmd.option('--json', 'print the result as one JSON document on stdout', false);\n}\n\nfunction writeJson(value: unknown): void {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\n// --- backups ------------------------------------------------------------------\n\ninterface BackupFlags {\n backupDir?: string;\n keep?: string;\n /** false with --no-backup (push). */\n backup?: boolean;\n}\n\nfunction addBackupDirFlags(cmd: Command): Command {\n return cmd\n .option('--backup-dir <dir>', `where backups are kept (default ./${DEFAULT_BACKUP_DIR})`)\n .option('--keep <n>', `backups kept per server (default ${DEFAULT_KEEP})`);\n}\n\nfunction backupDirOf(flags: BackupFlags): string {\n return path.resolve(flags.backupDir ?? DEFAULT_BACKUP_DIR);\n}\n\nfunction keepOf(flags: BackupFlags): number {\n if (flags.keep === undefined) return DEFAULT_KEEP;\n const n = Number(flags.keep);\n if (!Number.isInteger(n) || n < 1) fail(`--keep must be a whole number of at least 1, not ${flags.keep}`);\n return n;\n}\n\n/** The name a server's backups are filed under; the host and port when it has no configured name. */\nfunction serverNameOf(config: CanonicalConfig, flags: ConnectionFlags): string {\n const cfg = resolveClientConfig(flags);\n return backupName(config, `${cfg.host}-${cfg.port}`);\n}\n\n/** Parse backup XML, naming the file in the error. */\nfunction parseBackup(text: string, where: string): CanonicalConfig {\n try {\n return xml.parse(text);\n } catch (err) {\n fail(`${where}: ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\n/** Save the server's configuration `text` as its newest backup and say where. */\nasync function saveServerBackup(\n client: MirthClientExt,\n text: string,\n flags: ConnectionFlags & BackupFlags,\n protect?: string,\n): Promise<string> {\n const config = parseBackup(text, 'the server configuration');\n const origin = { serverId: await client.getServerId(), host: hostOf(flags) };\n const file = await saveBackup(backupDirOf(flags), serverNameOf(config, flags), text, { keep: keepOf(flags), origin, protect });\n if (gitWouldCommit(file)) {\n process.stderr.write(`warning: git does not ignore ${file}, which holds credentials in plain text; add it to .gitignore\\n`);\n }\n return file;\n}\n\n/** Before a push changes anything: a backup to undo it with, unless --no-backup. */\nasync function backupBeforePush(client: MirthClientExt, flags: ConnectionFlags & BackupFlags): Promise<void> {\n if (flags.backup === false) return;\n const file = await saveServerBackup(client, await client.getServerConfigurationXml(), flags);\n process.stdout.write(`backed up the server to ${file} (undo with: channelvault restore \"${file}\")\\n`);\n}\n\n/** `host:port`, for telling people which server a backup came from. */\nfunction hostOf(flags: ConnectionFlags): string {\n const cfg = resolveClientConfig(flags);\n return `${cfg.host}:${cfg.port}`;\n}\n\nasync function confirm(question: string): Promise<boolean> {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n const controller = new AbortController();\n rl.once('close', () => controller.abort());\n rl.once('SIGINT', () => controller.abort());\n try {\n const answer = (await rl.question(`${question} [y/N] `, { signal: controller.signal })).trim().toLowerCase();\n return answer === 'y' || answer === 'yes';\n } catch (err) {\n if (controller.signal.aborted) fail('confirmation interrupted; nothing was pushed');\n throw err;\n } finally {\n rl.close();\n }\n}\n\n/** Walk a canonical config and tally headline resource counts for `status`. */\nfunction summarize(config: CanonicalConfig): Record<string, number> {\n const asArray = (v: Json | undefined): Json[] => (Array.isArray(v) ? v : v == null ? [] : [v]);\n const channels = asArray((config.channels as Record<string, Json> | undefined)?.channel);\n const libraries = asArray(\n (config.codeTemplateLibraries as Record<string, Json> | undefined)?.codeTemplateLibrary,\n );\n const groups = asArray((config.channelGroups as Record<string, Json> | undefined)?.channelGroup);\n\n let codeTemplates = 0;\n for (const lib of libraries) {\n if (lib && typeof lib === 'object' && !Array.isArray(lib)) {\n const cts = (lib.codeTemplates as Record<string, Json> | undefined)?.codeTemplate;\n codeTemplates += asArray(cts).length;\n }\n }\n\n return {\n channels: channels.length,\n channelGroups: groups.length,\n codeTemplateLibraries: libraries.length,\n codeTemplates,\n };\n}\n\ninterface SyncMeta {\n tool: string;\n version: string;\n source: string;\n pulledAt: string;\n engineVersion: string | null;\n /** Resource ids the tree held at pull time (see Known in src/push). Absent in older trees. */\n resources?: Known;\n}\n\nasync function writeMeta(root: string, source: string, config: CanonicalConfig, previous: SyncMeta | null): Promise<void> {\n const meta: SyncMeta = {\n tool: 'channelvault',\n version: VERSION,\n source,\n pulledAt: new Date().toISOString(),\n // XML adapter yields `@_version`; the live JSON API yields `@version` (Jackson).\n engineVersion:\n typeof config['@_version'] === 'string'\n ? (config['@_version'] as string)\n : typeof config['@version'] === 'string'\n ? (config['@version'] as string)\n : null,\n resources: resourceIds(config),\n };\n // A pull that changed nothing else must not leave a timestamp-only change\n // for git to show.\n const file = path.join(root, 'channelvault.json');\n if (previous && JSON.stringify({ ...previous, pulledAt: '' }) === JSON.stringify({ ...meta, pulledAt: '' })) return;\n await writeFile(file, JSON.stringify(meta, null, 2) + '\\n', 'utf8');\n}\n\n// --- secrets / env ----------------------------------------------------------\n\ninterface EnvFlags {\n dotenv?: string;\n extractSecrets?: boolean;\n}\n\nfunction envFilePath(root: string, flags: EnvFlags): string {\n return flags.dotenv ? path.resolve(flags.dotenv) : path.join(root, '.env');\n}\n\n/** The env file overlaid with the process environment (which wins, as in CI). */\nasync function loadEnv(file: string): Promise<Record<string, string | undefined>> {\n return { ...(await readEnvFile(file)), ...process.env };\n}\n\nfunction addEnvFlag(cmd: Command): Command {\n // Not --env-file: Node scans the whole command line for that name and parses\n // the file itself (it fails on a directory and honours NODE_OPTIONS in it).\n return cmd.option('--dotenv <path>', 'env file holding secrets and per-environment values (default <dir>/.env)');\n}\n\nfunction addExtractFlag(cmd: Command): Command {\n return cmd.option('--extract-secrets', 'move secrets found inside values (URLs, scripts, headers) to the env file', false);\n}\n\n/** The tree as stored, placeholders unresolved; null if there is no tree yet. */\nasync function existingTree(root: string): Promise<CanonicalConfig | null> {\n return existsSync(path.join(root, 'server', 'configuration.json')) ? engine.implode({ root }) : null;\n}\n\n/** The tree with placeholders filled from the env file; fails listing any missing names. */\nasync function renderedTree(root: string, flags: EnvFlags): Promise<CanonicalConfig> {\n const tree = await engine.implode({ root });\n const env = await loadEnv(envFilePath(root, flags));\n rememberSecrets(tree, env);\n return render(tree, env);\n}\n\n/**\n * The values behind the tree's placeholders. A server's error can echo what\n * was sent, so everything printed about a failure goes through `scrub`.\n */\nconst knownSecrets = new Set<string>();\n\nfunction rememberSecrets(tree: CanonicalConfig, env: Record<string, string | undefined>): void {\n mapLeaves(tree, (value) => {\n for (const m of value.matchAll(/\\{\\{env:([A-Za-z_][A-Za-z0-9_]*)\\}\\}/g)) {\n const secret = env[m[1]!];\n // Shorter values (a port, \"true\") would redact ordinary words.\n if (secret !== undefined && secret.length >= 4) knownSecrets.add(secret);\n }\n return value;\n });\n}\n\n/**\n * `text` with every known secret value replaced, longest first. Error bodies\n * reach here decoded (see `readableBody`); the encoded forms cover text that\n * quotes a secret some other way.\n */\nfunction scrub(text: string): string {\n const forms = [...knownSecrets].flatMap((s) => [\n s,\n JSON.stringify(s).slice(1, -1),\n s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/'/g, '&apos;'),\n encodeURIComponent(s),\n ]);\n return [...new Set(forms)].sort((a, b) => b.length - a.length).reduce((t, s) => t.split(s).join('<redacted>'), text);\n}\n\n/**\n * Write a fetched config into the tree with credentials swapped for\n * placeholders; their values go to the env file, never to the tree.\n */\nconst ALLOW_FILE = 'channelvault.allow.json';\n\n/** Known false positives, committed with the tree: `{ \"ignore\": [{ \"location\", \"kind\", \"note\"? }] }`. */\nasync function readAllow(root: string): Promise<AllowEntry[]> {\n const file = path.join(root, ALLOW_FILE);\n if (!existsSync(file)) return [];\n const parsed = await readJson<{ ignore?: AllowEntry[] }>(file);\n return parsed.ignore ?? [];\n}\n\n/**\n * Write a fetched config into the tree with credentials swapped for\n * placeholders; their values go to the env file, never to the tree. Anything\n * that still looks like a secret stops the write unless --extract-secrets.\n */\nasync function writeTree(root: string, fetched: CanonicalConfig, source: string, flags: EnvFlags): Promise<void> {\n const envFile = envFilePath(root, flags);\n const previousMeta = await preflightTree(root, envFile);\n const env = await loadEnv(envFile);\n const templated = templatize(fetched, await existingTree(root), env);\n const scan = scanSecrets(templated.config, {\n mode: flags.extractSecrets ? 'extract' : 'find',\n allow: await readAllow(root),\n env: { ...env, ...templated.envUpdates },\n });\n if (scan.findings.length > 0 && !flags.extractSecrets) {\n fail(\n `found ${scan.findings.length} possible secret(s) that would be stored in plain text; nothing was written:\\n` +\n `${formatFindings(scan.findings)}\\n` +\n `Rerun with --extract-secrets to move them to ${envFile}, or list false positives in ${ALLOW_FILE}.`,\n );\n }\n const config = scan.config;\n const envUpdates = { ...templated.envUpdates, ...scan.envUpdates };\n rememberSecrets(config, { ...env, ...envUpdates });\n // A known secret repeated somewhere no rule recognised is still in plain\n // text; say where (the env file's own values only, not all of process.env).\n const echoes = findEchoes(config, { ...(await readEnvFile(envFile)), ...envUpdates });\n\n // Secrets first: a tree whose placeholders have no values behind them is\n // the one state a pull must never leave. If the env file can't be written,\n // the tree is untouched.\n await mkdir(root, { recursive: true });\n await mkdir(path.dirname(envFile), { recursive: true });\n const rel = path.relative(root, envFile);\n const envInTree = !rel.startsWith('..') && !path.isAbsolute(rel);\n const backup = await backupEnvFile(envFile, envUpdates, path.join(root, '.secrets'));\n if (backup || (envInTree && Object.keys(envUpdates).length > 0)) await ensureEnvIgnored(root, envInTree ? envFile : undefined);\n await updateEnvFile(envFile, envUpdates);\n\n await replaceTree(root, config);\n await writeMeta(root, source, fetched, previousMeta);\n if (scan.findings.length > 0) process.stdout.write(`extracted ${scan.findings.length} secret(s) found in values\\n`);\n const updated = Object.keys(envUpdates).length;\n if (updated > 0) process.stdout.write(`stored ${updated} secret value(s) in ${envFile}\\n`);\n if (backup) process.stdout.write(`previous env file kept as ${backup}\\n`);\n for (const note of templated.notes) process.stderr.write(`note: ${note}\\n`);\n for (const e of echoes) {\n process.stderr.write(`warning: the value of ${e.name} also appears in plain text at ${e.where}\\n`);\n }\n if (existsSync(envFile) && gitWouldCommit(envFile)) {\n process.stderr.write(`warning: git does not ignore ${envFile}, so its secret values could be committed; add it to .gitignore\\n`);\n }\n}\n\n/**\n * True when `file` is inside a git work tree and not ignored there (or is\n * already tracked). Outside a repository, or without git, there is nothing to\n * commit it to.\n */\nfunction gitWouldCommit(file: string): boolean {\n const r = spawnSync('git', ['check-ignore', '-q', path.basename(file)], { cwd: path.dirname(file) });\n return r.status === 1;\n}\n\n/** `p` with links resolved as far as it exists (the rest may not be created yet). */\nasync function resolvedPath(p: string): Promise<string> {\n const abs = path.resolve(p);\n let existing = abs;\n while (!existsSync(existing) && path.dirname(existing) !== existing) existing = path.dirname(existing);\n return path.join(await realpath(existing), path.relative(existing, abs));\n}\n\n/** `child` is `parent` or inside it (case-insensitively on Windows). */\nfunction isWithin(child: string, parent: string): boolean {\n const norm = (p: string) => (process.platform === 'win32' ? p.toLowerCase() : p);\n const rel = path.relative(norm(parent), norm(child));\n // `..runtime.env` is a file name, not a step up.\n return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));\n}\n\n/**\n * Everything that can stop `pull`/`explode` must be checked before either\n * writes: they update the env file, then replace the managed directories,\n * then rewrite `channelvault.json`. Returns the existing metadata, if any.\n */\nasync function preflightTree(root: string, envFile: string): Promise<SyncMeta | null> {\n // The swap deletes these, so the env file must not live in one: neither by\n // the path given (a link inside one is removed with it) nor by where links\n // lead.\n const [realRoot, realEnv] = await Promise.all([resolvedPath(root), resolvedPath(envFile)]);\n const doomed = [...MANAGED_DIRS, STAGING_DIR].find(\n (d) => isWithin(path.resolve(envFile), path.resolve(root, d)) || isWithin(realEnv, path.join(realRoot, d)),\n );\n if (doomed) fail(`the env file ${envFile} is inside ${doomed}/, which this command replaces; keep it elsewhere`);\n\n const metaPath = path.join(root, 'channelvault.json');\n if (existsSync(metaPath)) {\n let meta: unknown;\n try {\n meta = await readJson(metaPath);\n } catch (err) {\n meta = err;\n }\n if (meta === null || typeof meta !== 'object' || Array.isArray(meta) || meta instanceof Error || typeof (meta as SyncMeta).source !== 'string') {\n fail(\n `${metaPath} is unreadable or not channelvault metadata${meta instanceof Error ? ` (${meta.message})` : ''}; nothing was written. ` +\n 'Restore it (for example `git checkout -- channelvault.json`) and retry.',\n );\n }\n return meta as SyncMeta;\n }\n // The managed directories must be ones channelvault wrote.\n const foreign = MANAGED_DIRS.filter((d) => existsSync(path.join(root, d)));\n if (foreign.length > 0) {\n fail(\n `${root} is not a channelvault tree (no channelvault.json) but has ${foreign.map((d) => `${d}/`).join(', ')}, ` +\n 'which this command would replace; nothing was written. Use a new or empty directory ' +\n '(or, if an earlier pull or explode into it was interrupted, delete those directories).',\n );\n }\n return null;\n}\n\n/**\n * Explode into a staging directory inside the tree, then swap it in one\n * managed directory at a time. A failure while exploding leaves the old tree\n * as it was; only the swap itself (a few renames) can be interrupted.\n */\nasync function replaceTree(root: string, config: CanonicalConfig): Promise<void> {\n const staging = path.join(root, STAGING_DIR);\n await rm(staging, RM_OPTS);\n try {\n await engine.explode(config, { root: staging });\n for (const d of MANAGED_DIRS) {\n await rm(path.join(root, d), RM_OPTS);\n if (existsSync(path.join(staging, d))) await rename(path.join(staging, d), path.join(root, d));\n }\n } finally {\n await rm(staging, RM_OPTS);\n }\n}\n\n\nfunction assertTree(root: string): void {\n if (!existsSync(path.join(root, 'server', 'configuration.json'))) {\n fail(`${root} is not a channelvault tree (missing server/configuration.json). Run 'pull' or 'explode' first.`);\n }\n}\n\n/**\n * Which transport a working tree came from. The XML adapter and the live REST\n * API produce structurally DIFFERENT canonical configs (fast-xml-parser\n * `@_version`/`#text`/all-strings vs Jackson `@version`/native types), and the\n * normalization bridge between them is not implemented yet. So an XML-exploded\n * tree cannot be `push`ed to a live server, and a live-pulled tree cannot be\n * `implode`d to XML, without silent corruption. These helpers detect the origin\n * so those cross-path operations can be refused.\n */\ntype TreeOrigin = 'xml' | 'live' | 'unknown';\n\n/** Read the recorded origin from `channelvault.json` (`source` field). */\nasync function readTreeOrigin(root: string): Promise<TreeOrigin> {\n const metaPath = path.join(root, 'channelvault.json');\n if (!existsSync(metaPath)) return 'unknown';\n try {\n const meta = await readJson<SyncMeta>(metaPath);\n if (typeof meta.source === 'string') {\n if (meta.source.startsWith('file:')) return 'xml';\n if (/^https?:\\/\\//i.test(meta.source)) return 'live';\n }\n } catch {\n /* unreadable meta -> fall back to shape detection */\n }\n return 'unknown';\n}\n\n/** Infer origin from the config's attribute-key convention when meta is absent. */\nfunction detectConfigShape(config: CanonicalConfig): TreeOrigin {\n if ('@_version' in config) return 'xml';\n if ('@version' in config) return 'live';\n return 'unknown';\n}\n\n/**\n * Resolve a tree's transport, preferring recorded provenance and falling back\n * to the imploded config's shape. Refuses the operation when the tree's origin\n * is incompatible with `wants` (unless `force`).\n */\nasync function assertCompatibleOrigin(\n root: string,\n config: CanonicalConfig,\n wants: 'xml' | 'live',\n force: boolean,\n): Promise<void> {\n if (force) return;\n const origin = await readTreeOrigin(root);\n const effective = origin !== 'unknown' ? origin : detectConfigShape(config);\n if (effective === 'unknown' || effective === wants) return;\n\n const msg =\n wants === 'live'\n ? `this working tree was exploded from an XML backup, but 'push' sends to a live server. ` +\n `The two transports use different config shapes and the normalization bridge is not implemented yet, ` +\n `so pushing would upload a config the Mirth API cannot parse. Seed the tree with 'pull' instead, or pass --ignore-origin to override.`\n : `this working tree was pulled from a live server, but 'implode' writes a backup XML. ` +\n `The two transports use different config shapes and the normalization bridge is not implemented yet, ` +\n `so imploding would produce malformed XML. Re-create the tree with 'explode' from a backup, or pass --force to override.`;\n fail(msg);\n}\n\n/** Commander collector for a repeatable option; undefined until first used. */\nfunction collect(value: string, previous: string[] | undefined): string[] {\n return [...(previous ?? []), value];\n}\n\n// --- push ---------------------------------------------------------------------\n\n/** Resource ids recorded at the last pull, if this tree has them. */\nasync function readKnown(root: string): Promise<Known | undefined> {\n const metaPath = path.join(root, 'channelvault.json');\n if (!existsSync(metaPath)) return undefined;\n return knownFrom((await readJson<SyncMeta>(metaPath)).resources);\n}\n\nasync function writeKnown(root: string, known: Known): Promise<void> {\n const metaPath = path.join(root, 'channelvault.json');\n if (!existsSync(metaPath)) return;\n const meta = await readJson<SyncMeta>(metaPath);\n if (!meta.resources) return; // an older tree: leave it to the next pull\n meta.resources = known;\n await writeFile(metaPath, JSON.stringify(meta, null, 2) + '\\n', 'utf8');\n}\n\n/**\n * A whole replace carries the server and environment name along; say so, or\n * the server silently starts calling itself by another's name.\n */\nfunction printNameChange(incoming: CanonicalConfig, current: CanonicalConfig): void {\n const [to, from] = [configuredName(incoming), configuredName(current)];\n if (to !== from) process.stdout.write(`server name changes: ${from || '(none)'} -> ${to || '(none)'}\\n`);\n}\n\nfunction printChanges(plan: Plan): void {\n const kindLabel: Record<Change['kind'], string> = { channel: 'channel', library: 'library', codeTemplate: 'code template', globalScripts: '' };\n for (const c of plan.changes) process.stdout.write(` ${c.op.padEnd(6)} ${`${kindLabel[c.kind]} ${c.label}`.trim()}\\n`);\n}\n\n/** Refuse conflicts and deletions unless the user opted in. */\nfunction planProblems(plan: Plan, flags: { allowDeletes?: boolean; force?: boolean }): string[] {\n const problems: string[] = [];\n if (plan.conflicts.length > 0 && !flags.force) {\n problems.push(\n `changed on the server since the last pull:\\n ${plan.conflicts.join('\\n ')}\\n` +\n `pull (and merge) first, or pass --force to overwrite the server's version`,\n );\n }\n const deletes = plan.changes.filter((c) => c.op === 'delete').length;\n if (deletes > 0 && !flags.allowDeletes) {\n problems.push(`the plan deletes ${deletes} resource(s) from the server; pass --allow-deletes, or narrow with --channel/--library`);\n }\n return problems;\n}\n\n/** What stops a whole-server replace: the scoped checks, plus resources the tree never had (deleted by a replace). */\nfunction wholeServerProblems(plan: Plan, flags: { allowDeletes?: boolean; force?: boolean }): string[] {\n const problems: string[] = [];\n if (plan.serverOnly.length > 0 && !flags.force) {\n problems.push('the replace would delete resources created on the server since the last pull; pull first, or pass --force (and --allow-deletes)');\n }\n const deletions = plan.changes.filter((c) => c.op === 'delete').length + plan.serverOnly.length;\n if (deletions > 0 && !flags.allowDeletes) problems.push(`the replace deletes ${deletions} resource(s) from the server; pass --allow-deletes`);\n if (plan.conflicts.length > 0 && !flags.force) problems.push(...planProblems({ ...plan, changes: [] }, flags));\n return problems;\n}\n\n/** `push --plan-only`: report the plan and what would stop it, change nothing. */\nfunction reportPlanOnly(\n flags: PushFlags,\n plan: Plan,\n problems: string[],\n extra: { target: string; mode: 'scoped' | 'whole-server'; redeploy?: string[]; notRedeployed?: string[] },\n): void {\n if (flags.json) {\n writeJson({\n target: extra.target,\n mode: extra.mode,\n changes: plan.changes,\n conflicts: plan.conflicts,\n serverOnly: plan.serverOnly,\n notPushed: plan.notPushed,\n ...(extra.redeploy ? { redeploy: extra.redeploy, notRedeployed: extra.notRedeployed ?? [] } : {}),\n wouldStop: problems,\n });\n return;\n }\n for (const p of problems) process.stdout.write(`a push would stop: ${p}\\n`);\n process.stdout.write('plan only: nothing was changed\\n');\n}\n\ninterface PushFlags extends ConnectionFlags, BackupFlags, JsonFlags {\n /** --plan-only: report the plan and what would stop it; change nothing. */\n planOnly?: boolean;\n allowDeletes?: boolean;\n deploy?: boolean;\n force?: boolean;\n yes?: boolean;\n overwriteConfigMap?: boolean;\n}\n\nasync function scopedPush(\n client: MirthClientExt,\n root: string,\n local: CanonicalConfig,\n scope: Scope,\n target: string,\n flags: PushFlags,\n): Promise<void> {\n const remote = await client.getServerConfiguration();\n const known = await readKnown(root);\n const plan = planPush(local, remote, scope, known);\n const names = new Map(\n [...channelsOf(remote), ...channelsOf(local)].map((c) => [String(c['id']), String(c['name'])] as const),\n );\n const nameOf = (id: string): string => names.get(id) ?? id;\n\n // --deploy refreshes what is running; it never starts a channel that is not\n // deployed now (an operator may have taken it down on purpose).\n const deployed = flags.deploy && plan.deployIds.length > 0 ? await client.getDeployedChannelIds() : new Set<string>();\n const toDeploy = plan.deployIds.filter((id) => deployed.has(id));\n const notDeployed = flags.deploy ? plan.deployIds.filter((id) => !deployed.has(id)) : [];\n\n if (flags.planOnly && flags.json) {\n const redeploy = flags.deploy ? { redeploy: toDeploy.map(nameOf), notRedeployed: notDeployed.map(nameOf) } : {};\n reportPlanOnly(flags, plan, planProblems(plan, flags), { target, mode: 'scoped', ...redeploy });\n return;\n }\n if (plan.changes.length === 0) {\n process.stdout.write(`nothing to push: ${target} already matches the tree\\n`);\n } else {\n process.stdout.write(`Push to ${target}:\\n`);\n printChanges(plan);\n if (toDeploy.length > 0) process.stdout.write(`then redeploy: ${toDeploy.map(nameOf).join(', ')}\\n`);\n if (notDeployed.length > 0) {\n process.stdout.write(`not redeployed (not deployed on the server now): ${notDeployed.map(nameOf).join(', ')}\\n`);\n }\n }\n if (plan.notPushed.length > 0) {\n process.stdout.write(`not pushed (differs; use --whole-server): ${plan.notPushed.join(', ')}\\n`);\n }\n if (plan.serverOnly.length > 0) {\n process.stdout.write(`left alone (created on the server since the last pull; pull to get them): ${plan.serverOnly.join(', ')}\\n`);\n }\n if (flags.planOnly) {\n reportPlanOnly(flags, plan, planProblems(plan, flags), { target, mode: 'scoped' });\n return;\n }\n if (plan.changes.length === 0) return;\n\n const problems = planProblems(plan, flags);\n if (problems.length > 0) fail(problems.join('\\n'));\n if (!flags.yes && !(await confirm('Continue?'))) {\n process.stdout.write('aborted.\\n');\n return;\n }\n\n // The prompt may have been open for a while: re-check that nothing in the\n // plan changed on the server meanwhile. Each channel save re-checks its own\n // revision once more; the gap after that last check can't be closed from\n // here, because Mirth accepts a stale revision.\n const fresh = await client.getServerConfiguration();\n const moved = changedSince(plan, remote, fresh);\n if (moved.length > 0 && !flags.force) {\n fail(`changed on the server while this push was being confirmed:\\n ${moved.join('\\n ')}\\npull and try again, or pass --force`);\n }\n // Apply against the fresh snapshot, so whatever is sent for resources\n // outside the plan (the rest of the library list) is the server's latest.\n await backupBeforePush(client, flags);\n const result = await applyPlan(client, plan, local, fresh, scope, { force: flags.force === true });\n // Record the server's new revisions even after a partial failure, so the\n // resources that did go through don't read as conflicts next time.\n try {\n const after = await client.getServerConfiguration();\n const refreshedLibraries: Change[] = librariesOf(local)\n .filter(l => result.touchedIds.has(String(l['id'])))\n .map(l => ({ kind: 'library', op: 'update', id: String(l['id']), label: String(l['name']) }));\n const changedAgain = [...result.applied, ...refreshedLibraries].filter(c => !savedChangeMatches(c, local, after));\n if (changedAgain.length > 0) fail(`changed again after saving: ${[...new Set(changedAgain.map(c => c.label))].join(', ')}; pull and review before retrying`);\n if (result.touchedIds.size > 0) await refreshRevisions(root, after, result.touchedIds);\n if (known) await writeKnown(root, knownAfterPush(known, result.applied, result.touchedIds, after));\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (!result.failed) fail(`applied ${result.applied.length} change(s), but could not refresh the local sync baseline: ${message}; inspect the server before retrying`);\n process.stderr.write(`warning: could not refresh the local sync baseline: ${scrub(message)}\\n`);\n }\n if (result.failed) {\n const { change, error } = result.failed;\n fail(`applied ${result.applied.length} of ${plan.changes.length}; ${change.op} ${change.label} failed: ${error}`);\n }\n process.stdout.write(`pushed ${result.applied.length} change(s)\\n`);\n\n if (toDeploy.length > 0) {\n const failures = await deployChannels(client, toDeploy, nameOf);\n process.stdout.write(`deployed ${toDeploy.length - failures.length} of ${toDeploy.length} channel(s)\\n`);\n for (const f of failures) process.stderr.write(`deploy failed: ${f.name}: ${scrub(f.error)}\\n`);\n if (failures.length > 0) process.exitCode = 1;\n }\n}\n\n/** The full replace, gated like a scoped push: it lists and guards deletions and conflicts too. */\nasync function wholeServerPush(\n client: MirthClientExt,\n root: string,\n local: CanonicalConfig,\n target: string,\n flags: PushFlags,\n): Promise<void> {\n const remote = await client.getServerConfiguration();\n const known = await readKnown(root);\n const plan = planPush(local, remote, {}, known, { wholeReplace: true });\n if (flags.planOnly && flags.json) {\n reportPlanOnly(flags, plan, wholeServerProblems(plan, flags), { target, mode: 'whole-server' });\n return;\n }\n const s = summarize(local);\n process.stdout.write(\n `Replace the ENTIRE server configuration at ${target} (${s.channels} channels, ${s.codeTemplates} code templates` +\n `${flags.deploy ? ', then redeploy all channels' : ''}).\\n`,\n );\n printNameChange(local, remote);\n if (plan.changes.length > 0) {\n process.stdout.write('Channel, library and template changes:\\n');\n printChanges(plan);\n }\n // A full replace also deletes what the server has and the tree never had\n // (created since the pull). That is both a deletion and someone else's\n // work: it needs --allow-deletes and --force, and the preview names it.\n for (const r of plan.serverOnly) process.stdout.write(` delete ${r} (created on the server since the last pull)\\n`);\n // Mirth keeps its own configuration map unless told to overwrite it.\n const keptMap = plan.notPushed.includes('configurationMap') && !flags.overwriteConfigMap;\n const replaced = plan.notPushed.filter((k) => !(keptMap && k === 'configurationMap'));\n if (replaced.length > 0) process.stdout.write(`also replaced: ${replaced.join(', ')}\\n`);\n if (keptMap) process.stdout.write('configuration map differs but is kept (--overwrite-config-map replaces it)\\n');\n const problems = wholeServerProblems(plan, flags);\n if (flags.planOnly) {\n reportPlanOnly(flags, plan, problems, { target, mode: 'whole-server' });\n return;\n }\n if (problems.length > 0) fail(problems.join('\\n'));\n if (!flags.yes && !(await confirm('Continue?'))) {\n process.stdout.write('aborted.\\n');\n return;\n }\n // The preview was made from `remote`; anything changed since would be\n // overwritten without having been shown.\n const fresh = await client.getServerConfiguration();\n if (!sameServerConfig(remote, fresh) && !flags.force) {\n fail('the server changed while this push was being confirmed; pull and try again, or pass --force');\n }\n // Force permits concurrent edits, but never grants deletion consent.\n const freshPlan = planPush(local, fresh, {}, known, { wholeReplace: true });\n if (!flags.allowDeletes && (freshPlan.serverOnly.length > 0 || freshPlan.changes.some(c => c.op === 'delete'))) {\n fail('the replace now deletes resources from the server; review the new plan and pass --allow-deletes');\n }\n await backupBeforePush(client, flags);\n await client.putServerConfiguration(local, {\n deploy: flags.deploy === true,\n overwriteConfigMap: flags.overwriteConfigMap === true,\n });\n const after = await client.getServerConfiguration();\n if (planPush(local, after, {}, undefined, { wholeReplace: true }).changes.length > 0) {\n fail('applied the whole-server replacement, but resources changed again after saving; pull and review before retrying');\n }\n const ids = resourceIds(local);\n await refreshRevisions(root, after, new Set([...Object.keys(ids.channels), ...Object.keys(ids.libraries), ...Object.keys(ids.codeTemplates)]));\n if (known) await writeKnown(root, resourceIds(after));\n process.stdout.write(`pushed ${root} -> ${target}\\n`);\n}\n\n// --- commands -------------------------------------------------------------\n\nconst program = new Command();\nprogram\n .name('channelvault')\n .description('Git-style pull/push/diff for Mirth Connect')\n .version(VERSION)\n // An unused argument is almost always a flag lost in transit (e.g. a script\n // runner passing a literal `--`); fail rather than silently drop it.\n // Subcommands defined below inherit this.\n .allowExcessArguments(false);\n\naddExtractFlag(addEnvFlag(\n program\n .command('explode')\n .description('Explode a Mirth backup XML into a working tree')\n .argument('<backup.xml>', 'path to a Mirth backup config XML file')\n .argument('<dir>', 'output working-tree directory'),\n)).action(async (backupPath: string, dir: string, flags: EnvFlags) => {\n const config = xml.parse(await readFile(backupPath, 'utf8'));\n const root = path.resolve(dir);\n await writeTree(root, config, `file:${path.resolve(backupPath)}`, flags);\n const s = summarize(config);\n process.stdout.write(`exploded ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}\\n`);\n});\n\naddEnvFlag(\n program\n .command('implode')\n .description('Reassemble a working tree into a Mirth backup XML')\n .argument('<dir>', 'working-tree directory')\n .argument('<backup.xml>', 'output XML path')\n .option('--force', 'implode even if the tree was pulled from a live server', false),\n).action(async (dir: string, outPath: string, flags: EnvFlags & { force?: boolean }) => {\n const root = path.resolve(dir);\n assertTree(root);\n const config = await renderedTree(root, flags);\n await assertCompatibleOrigin(root, config, 'xml', flags.force === true);\n const xmlStr = xml.build(config);\n await writeFile(outPath, xmlStr, 'utf8');\n process.stdout.write(`imploded ${root} -> ${path.resolve(outPath)}\\n`);\n });\n\naddExtractFlag(addEnvFlag(addConnectionFlags(\n program\n .command('pull')\n .description('Pull the live server configuration into a working tree')\n .argument('<dir>', 'working-tree directory'),\n))).action(async (dir: string, flags: ConnectionFlags & EnvFlags) => {\n const root = path.resolve(dir);\n await preflightTree(root, envFilePath(root, flags)); // before fetching a whole server for nothing\n const config = await withClient(flags, (client) => client.getServerConfiguration());\n const cfg = resolveClientConfig(flags);\n await writeTree(root, config, `${cfg.https === false ? 'http' : 'https'}://${cfg.host}:${cfg.port}`, flags);\n const s = summarize(config);\n process.stdout.write(`pulled ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}\\n`);\n});\n\naddBackupDirFlags(addEnvFlag(addConnectionFlags(\n program\n .command('push')\n .description('Push changed channels, code templates and global scripts to the live server')\n .argument('<dir>', 'working-tree directory')\n .option('--channel <name>', 'only this channel (name or id); repeatable', collect)\n .option('--library <name>', 'only this code template library (name or id); repeatable', collect)\n .option('--global-scripts', 'with --channel/--library: also push global scripts')\n .option('--allow-deletes', 'delete server resources that are missing from the tree', false)\n .option('--deploy', 'redeploy the changed channels and the channels using changed code templates', false)\n .option('--force', \"push even if the server changed since the last pull (overwrites the server's version)\", false)\n .option('--ignore-origin', 'push a tree that was exploded from an XML backup (normally refused)', false)\n .option('--whole-server', 'replace the entire server configuration instead (settings, config map, groups too)', false)\n .option('--overwrite-config-map', 'with --whole-server: also overwrite the configuration map', false)\n .option('--no-backup', 'skip the backup of the server taken before anything changes')\n .option('--plan-only', 'show what would be pushed and what would stop it; change nothing (no prompt)', false)\n .option('--json', 'with --plan-only: print the plan as one JSON document', false)\n .option('-y, --yes', 'skip the confirmation prompt', false),\n))).action(\n async (\n dir: string,\n flags: PushFlags & EnvFlags & {\n channel?: string[];\n library?: string[];\n globalScripts?: boolean;\n allowDeletes?: boolean;\n deploy?: boolean;\n wholeServer?: boolean;\n overwriteConfigMap?: boolean;\n yes?: boolean;\n force?: boolean;\n ignoreOrigin?: boolean;\n },\n ) => {\n if (flags.wholeServer && (flags.channel || flags.library || flags.globalScripts)) {\n fail('--whole-server replaces everything; it cannot be combined with --channel, --library or --global-scripts');\n }\n const root = path.resolve(dir);\n assertTree(root);\n const config = await renderedTree(root, flags);\n await assertCompatibleOrigin(root, config, 'live', flags.ignoreOrigin === true);\n const cfg = resolveClientConfig(flags);\n const target = `${cfg.https === false ? 'http' : 'https'}://${cfg.host}:${cfg.port}`;\n if (flags.json && !flags.planOnly) fail('--json needs --plan-only');\n if (!flags.yes && !flags.planOnly && !process.stdin.isTTY) {\n fail('no terminal to confirm on; review with `push --plan-only` or `diff`, and pass --yes');\n }\n if (flags.wholeServer) {\n await withClient(flags, (client) => wholeServerPush(client, root, config, target, flags));\n return;\n }\n const scope: Scope = { channels: flags.channel, libraries: flags.library, globalScripts: flags.globalScripts };\n await withClient(flags, (client) => scopedPush(client, root, config, scope, target, flags));\n },\n);\n\naddBackupDirFlags(addConnectionFlags(\n program\n .command('backup')\n .description(`Save the server configuration as <server>-<UTC time>.xml in ./${DEFAULT_BACKUP_DIR} (holds credentials in plain text)`)\n .option('--out <file>', 'write to this file instead (no rotation)'),\n)).action(async (flags: ConnectionFlags & BackupFlags & { out?: string }) => {\n const cfg = resolveClientConfig(flags);\n const target = `${cfg.https === false ? 'http' : 'https'}://${cfg.host}:${cfg.port}`;\n const file = await withClient(flags, async (client) => {\n const text = await client.getServerConfigurationXml();\n if (!flags.out) return saveServerBackup(client, text, flags);\n const out = path.resolve(flags.out);\n parseBackup(text, 'the server configuration');\n if (existsSync(out)) fail(`${out} already exists; choose another name`);\n await mkdir(path.dirname(out), { recursive: true });\n await writePrivate(out, text);\n if (gitWouldCommit(out)) {\n process.stderr.write(`warning: git does not ignore ${out}, which holds credentials in plain text; add it to .gitignore\\n`);\n }\n return out;\n });\n process.stdout.write(`backed up ${target} to ${file}\\n`);\n});\n\ninterface RestoreFlags extends ConnectionFlags, BackupFlags {\n deploy?: boolean;\n overwriteConfigMap?: boolean;\n yes?: boolean;\n force?: boolean;\n}\n\naddBackupDirFlags(addConnectionFlags(\n program\n .command('restore')\n .description('Replace the entire server configuration with a backup (default: the newest backup of this server)')\n .argument('[file]', 'backup XML to restore')\n .option('--deploy', 'redeploy all channels afterwards', false)\n .option('--overwrite-config-map', 'also replace the configuration map', false)\n .option('--force', 'restore a backup taken from another server', false)\n .option('-y, --yes', 'skip the confirmation prompt', false),\n)).action(async (file: string | undefined, flags: RestoreFlags) => {\n const cfg = resolveClientConfig(flags);\n const target = `${cfg.https === false ? 'http' : 'https'}://${cfg.host}:${cfg.port}`;\n if (!flags.yes && !process.stdin.isTTY) fail('no terminal to confirm on; pass --yes');\n const dir = backupDirOf(flags);\n await withClient(flags, async (client) => {\n const currentText = await client.getServerConfigurationXml();\n const current = parseBackup(currentText, 'the server configuration');\n const serverId = await client.getServerId();\n\n // Which backup: the one named, else the newest taken from this server\n // (by server ID: the name in the file name travels with the configuration).\n let chosen: string;\n if (file) {\n chosen = path.resolve(file);\n if (!existsSync(chosen)) fail(`${chosen} does not exist`);\n } else {\n const mine = await backupsOf(dir, serverId);\n if (mine.length === 0) {\n const others = (await originsIn(dir)).map((o) => o.host);\n fail(`no backups of ${target} in ${dir}${others.length ? ` (it has backups of: ${others.join(', ')})` : ''}`);\n }\n chosen = mine[mine.length - 1]!.file;\n }\n const text = await readFile(chosen, 'utf8');\n const backup = parseBackup(text, chosen);\n\n // A backup of another server would replace this one's configuration with it.\n const origin = await originOf(dir, chosen);\n if (origin) {\n if (origin.serverId !== serverId && !flags.force) {\n fail(`${chosen} was taken from ${origin.host} (server ID ${origin.serverId}), not this server (${serverId}); pass --force to restore it here anyway`);\n }\n } else {\n // Not one of this directory's backups: only the names can be compared.\n const [fromContent, fromServer] = [configuredName(backup), configuredName(current)];\n if (fromContent !== '' && fromServer !== '' && fromContent !== fromServer && !flags.force) {\n fail(`${chosen} is a backup of ${fromContent}, not ${fromServer}; pass --force to restore it here anyway`);\n }\n process.stderr.write(`warning: ${chosen} is not in ${path.join(dir, MANIFEST)}, so which server it came from cannot be checked\\n`);\n }\n\n // Older servers cannot read a newer configuration; Mirth converts older ones.\n const [bv, sv] = [backup['@_version'], current['@_version']];\n if (typeof bv === 'string' && typeof sv === 'string' && numericVersion(bv) && numericVersion(sv)) {\n if (compareVersions(bv, sv) > 0) fail(`${chosen} is from Mirth ${bv}, newer than this server (${sv}); it cannot be restored here`);\n if (compareVersions(bv, sv) < 0) process.stderr.write(`note: ${chosen} is from Mirth ${bv}; the server (${sv}) will convert it\\n`);\n } else {\n process.stderr.write(`warning: cannot compare the backup's Mirth version (${String(bv ?? 'none')}) with the server's (${String(sv ?? 'none')})\\n`);\n }\n\n const plan = planPush(backup, current, {}, undefined, { wholeReplace: true });\n process.stdout.write(`Restore ${chosen}\\nto ${target}, replacing its ENTIRE configuration${flags.deploy ? ', then redeploy all channels' : ''}.\\n`);\n printNameChange(backup, current);\n if (plan.changes.length > 0) {\n process.stdout.write('Channel, library and template changes:\\n');\n printChanges(plan);\n }\n const keptMap = plan.notPushed.includes('configurationMap') && !flags.overwriteConfigMap;\n const replaced = plan.notPushed.filter((k) => !(keptMap && k === 'configurationMap'));\n if (replaced.length > 0) process.stdout.write(`also replaced: ${replaced.join(', ')}\\n`);\n if (keptMap) process.stdout.write('configuration map differs but is kept (--overwrite-config-map replaces it)\\n');\n if (!flags.yes && !(await confirm('Continue?'))) {\n process.stdout.write('aborted.\\n');\n return;\n }\n\n // What the preview showed must still be what gets replaced; --force does\n // not cover this (it is about which server the backup is from).\n const freshText = await client.getServerConfigurationXml();\n if (!sameServerConfig(parseBackup(freshText, 'the server configuration'), current)) {\n fail('the server changed while this restore was being confirmed; nothing was restored. Run it again to review the new state');\n }\n // The undo: the configuration about to be replaced. The backup being\n // restored is protected from rotation.\n const undo = await saveServerBackup(client, freshText, flags, chosen);\n process.stdout.write(`saved the current configuration to ${undo} (undo with: channelvault restore \"${undo}\")\\n`);\n\n await client.putServerConfigurationXml(text, { deploy: flags.deploy === true, overwriteConfigMap: flags.overwriteConfigMap === true });\n const after = parseBackup(await client.getServerConfigurationXml(), 'the server configuration');\n const differ = planPush(backup, after, {}, undefined, { wholeReplace: true }).changes;\n if (differ.length > 0) {\n fail(`restored, but these differ from the backup afterwards: ${differ.map((c) => c.label).join(', ')}; inspect the server`);\n }\n process.stdout.write(`restored ${chosen} to ${target}\\n`);\n });\n});\n\naddJsonFlag(addEnvFlag(addConnectionFlags(\n program\n .command('diff')\n .description('Diff a working tree against the live server configuration (exit 0 = same, 1 = differences, 2 = error)')\n .argument('<dir>', 'working-tree directory')\n // Usage errors must not read as \"differences found\" either.\n .exitOverride((err) => {\n process.exitCode = err.exitCode === 0 ? 0 : 2;\n throw err;\n }),\n))).action(async (dir: string, flags: ConnectionFlags & EnvFlags & JsonFlags) => {\n errorExitCode = 2;\n const root = path.resolve(dir);\n assertTree(root);\n\n const fetched = await withClient(flags, (client) => client.getServerConfiguration());\n const tree = await engine.implode({ root });\n // Compare like with like: the server's credentials become the placeholders\n // the tree holds. Values that differ from the env file are named, never shown.\n const { config: templatedRemote, envUpdates, notes } = templatize(fetched, tree, await loadEnv(envFilePath(root, flags)));\n const messages: string[] = [\n ...Object.keys(envUpdates).map((name) => `${name} differs between the server and the env file`),\n ...notes,\n ];\n // Redact both sides the same way, so neither can print a secret and a raw\n // secret held on both sides doesn't read as a difference.\n const allow = await readAllow(root);\n // Line endings are normalised too: push ignores them because Mirth rewrites them on save.\n // So are revisions and timestamps, which Mirth bumps on any save or restore:\n // compare content, and report newer revisions separately.\n const staleRevisions = newerOnServer(tree, templatedRemote);\n if (staleRevisions.length > 0) {\n messages.push(`${staleRevisions.length} resource(s) have a newer revision on the server; pull to update the tree's baseline`);\n }\n const treeView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withoutVolatile(tree))), { mode: 'redact', allow });\n const serverView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withoutVolatile(templatedRemote))), { mode: 'redact', allow });\n if (treeView.findings.length > 0) {\n messages.push(`the tree holds ${treeView.findings.length} unextracted secret(s), redacted below; pull --extract-secrets`);\n }\n if (serverView.findings.length > 0) messages.push(`${serverView.findings.length} possible secret(s) on the server are redacted below`);\n if (!flags.json) for (const m of messages) process.stderr.write(`note: ${m}\\n`);\n\n const tmp = await mkdtemp(path.join(tmpdir(), 'channelvault-diff-'));\n try {\n // Both sides are exploded fresh from their configs, into tmp/tree and\n // tmp/server, and compared from tmp so paths print as tree/… and server/….\n await engine.explode(treeView.config, { root: path.join(tmp, 'tree') });\n await engine.explode(serverView.config, { root: path.join(tmp, 'server') });\n await mkdir(path.join(tmp, '.empty'));\n const chunks: string[] = [];\n // Only what explode owns; per directory, because git diff --no-index takes two paths.\n for (const d of MANAGED_DIRS) {\n const local = existsSync(path.join(tmp, 'tree', d)) ? `tree/${d}` : '.empty';\n const server = existsSync(path.join(tmp, 'server', d)) ? `server/${d}` : '.empty';\n if (local === '.empty' && server === '.empty') continue;\n // Pin line-ending handling so the answer doesn't depend on the user's git\n // config, and match push, which ignores CR-only differences.\n const result = spawnSync(\n 'git',\n ['-c', 'core.autocrlf=false', 'diff', '--no-index', '--no-color', '--ignore-cr-at-eol', local, server],\n { encoding: 'utf8', cwd: tmp },\n );\n // spawnSync does NOT throw when the binary is missing or the spawn fails --\n // it returns { error, status: null }. Treating an empty stdout as \"no diff\"\n // would print a confident false-clean on the exact gate users run before a\n // destructive push, so inspect the outcome explicitly.\n // git diff --no-index exits 0 when identical, 1 when differences exist;\n // any other code (or a spawn error) is a real failure.\n if (result.error) {\n fail(`failed to run git (is it installed and on PATH?): ${result.error.message}`);\n }\n if (result.status !== 0 && result.status !== 1) {\n const stderr = (result.stderr ?? '').trim();\n fail(`git diff failed (exit ${result.status ?? 'null'})${stderr ? `: ${stderr}` : ''}`);\n }\n const chunk = (result.stdout ?? '').trim();\n if (chunk !== '') chunks.push(chunk);\n }\n const out = chunks.join('\\n');\n // A secret changed on the server is drift too, even though both sides show\n // the same placeholder; name it, never its value.\n const secretDrift = Object.keys(envUpdates);\n const clean = out === '' && secretDrift.length === 0;\n if (!clean) process.exitCode = 1;\n if (flags.json) {\n const files = await changedFiles(path.join(tmp, 'tree'), path.join(tmp, 'server'));\n writeJson({ clean, files, secretDrift, staleRevisions, notes: messages, patch: out });\n } else if (clean) {\n process.stdout.write('no differences — working tree matches the server.\\n');\n } else {\n if (out !== '') process.stdout.write(out + '\\n');\n if (secretDrift.length > 0) {\n process.stdout.write(`secret values differ between the server and the env file: ${secretDrift.join(', ')}\\n`);\n }\n }\n } finally {\n await rm(tmp, RM_OPTS);\n }\n});\n\n/**\n * Files that differ between two exploded trees, by path relative to the\n * working tree. Both sides were normalised to LF before exploding, so a byte\n * comparison agrees with the patch.\n */\nasync function changedFiles(treeDir: string, serverDir: string): Promise<Array<{ path: string; change: 'modified' | 'only-in-tree' | 'only-on-server' }>> {\n const list = async (base: string): Promise<string[]> => {\n const out: string[] = [];\n for (const d of MANAGED_DIRS) {\n if (!existsSync(path.join(base, d))) continue;\n for (const entry of await readdir(path.join(base, d), { recursive: true, withFileTypes: true })) {\n if (entry.isFile()) out.push(path.relative(base, path.join(entry.parentPath, entry.name)).split(path.sep).join('/'));\n }\n }\n return out;\n };\n const [local, remote] = await Promise.all([list(treeDir), list(serverDir)]);\n const remoteSet = new Set(remote);\n const files: Array<{ path: string; change: 'modified' | 'only-in-tree' | 'only-on-server' }> = [];\n for (const p of local) {\n if (!remoteSet.has(p)) files.push({ path: p, change: 'only-in-tree' });\n else if ((await readFile(path.join(treeDir, p), 'utf8')) !== (await readFile(path.join(serverDir, p), 'utf8'))) files.push({ path: p, change: 'modified' });\n }\n const localSet = new Set(local);\n for (const p of remote) if (!localSet.has(p)) files.push({ path: p, change: 'only-on-server' });\n return files.sort((a, b) => a.path.localeCompare(b.path));\n}\n\naddJsonFlag(\n program\n .command('status')\n .description('Summarize a working tree')\n .argument('<dir>', 'working-tree directory'),\n).action(async (dir: string, flags: JsonFlags) => {\n const root = path.resolve(dir);\n assertTree(root);\n const config = await engine.implode({ root });\n const s = summarize(config);\n const metaPath = path.join(root, 'channelvault.json');\n const meta = existsSync(metaPath) ? await readJson<SyncMeta>(metaPath) : null;\n if (flags.json) {\n writeJson({ root, source: meta?.source ?? null, pulledAt: meta?.pulledAt ?? null, engineVersion: meta?.engineVersion ?? null, counts: s });\n return;\n }\n if (meta) {\n process.stdout.write(`source: ${meta.source}\\n`);\n process.stdout.write(`pulled: ${meta.pulledAt}\\n`);\n process.stdout.write(`engine: ${meta.engineVersion ?? 'unknown'}\\n`);\n }\n process.stdout.write(\n `channels: ${s.channels}\\n` +\n `channel groups: ${s.channelGroups}\\n` +\n `code template libs: ${s.codeTemplateLibraries}\\n` +\n `code templates: ${s.codeTemplates}\\n`,\n );\n});\n\nprogram.parseAsync().catch((err: unknown) => {\n // Commander has already printed it and set the exit code.\n if (err instanceof CommanderError) return;\n process.stderr.write(`error: ${scrub(err instanceof Error ? err.message : String(err))}\\n`);\n const code = (err as { code?: unknown } | null)?.code;\n if (typeof code === 'string' && UNTRUSTED_CERT_CODES.has(code)) {\n process.stderr.write(\n \"hint: the server's TLS certificate is not trusted. For a self-signed certificate (Mirth's default), \" +\n 'pass --insecure, which turns certificate verification off.\\n',\n );\n }\n if (!(err instanceof CliError) && err instanceof Error && process.env.CHANNELVAULT_DEBUG) {\n process.stderr.write(`${scrub(err.stack ?? '')}\\n`);\n }\n process.exitCode = errorExitCode;\n});\n","/**\n * Explode / implode engine.\n *\n * Projects a canonical config (the unwrapped Mirth `serverConfiguration`) onto a\n * git-friendly directory tree and reverses it losslessly. The exploded tree is a\n * verbatim *projection* of the config split across files using two marker types:\n *\n * - `{ \"@file\": \"<relpath>\" }` replaces an extracted code/script STRING leaf;\n * the string is written to a sidecar `.js` file (path relative to the JSON\n * file holding the marker).\n * - `{ \"@ref\": \"<relpath>\" }` replaces a whole sub-object split into its own\n * `.json` file (path relative to the JSON file holding the marker).\n *\n * Invariant: `implode(explode(config))` deep-equals `config`.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { existsSync } from 'node:fs';\nimport { lstat, mkdir, readFile, realpath, writeFile } from 'node:fs/promises';\nimport * as path from 'node:path';\n\nimport {\n CHANNEL_SCRIPT_KEYS,\n CODE_KEYS,\n isFileRef,\n type CanonicalConfig,\n type ExplodeEngine,\n type ExplodeOptions,\n type Json,\n} from '../types.js';\nimport { parseJson, readJson } from '../json.js';\n\n// --- shared helpers --------------------------------------------------------\n\n/** Coerce a \"container may be object or array depending on count\" value. */\nexport function asArray<T = Json>(x: unknown): T[] {\n return Array.isArray(x) ? (x as T[]) : x == null ? [] : [x as T];\n}\n\n/** Marker left in a `*.json` file in place of an extracted sub-object. */\ninterface RefMarker {\n '@ref': string;\n}\n\nexport function isRefMarker(v: unknown): v is RefMarker {\n return (\n typeof v === 'object' &&\n v !== null &&\n !Array.isArray(v) &&\n Object.keys(v).length === 1 &&\n typeof (v as Record<string, unknown>)['@ref'] === 'string'\n );\n}\n\nconst CODE_KEY_SET: ReadonlySet<string> = new Set([...CODE_KEYS, ...CHANNEL_SCRIPT_KEYS]);\n\n/** Map of channel-level script key -> friendly file base name. */\nconst CHANNEL_SCRIPT_FRIENDLY: Record<string, string> = {\n preprocessingScript: 'preprocessor',\n postprocessingScript: 'postprocessor',\n deployScript: 'deploy',\n undeployScript: 'undeploy',\n};\n\nfunction isPlainObject(v: unknown): v is Record<string, Json> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction deepClone<T>(v: T): T {\n return structuredClone(v);\n}\n\n/**\n * Slugify a name into a filesystem-safe segment.\n * Replaces `/ \\ : * ? \" < > |` and control chars, collapses whitespace to `-`,\n * trims leading/trailing separators. Never returns an empty string.\n */\nfunction slug(name: unknown): string {\n let s = typeof name === 'string' ? name : name == null ? '' : String(name);\n // Replace reserved / control characters with a space (later collapsed).\n s = s.replace(/[/\\\\:*?\"<>|]/g, ' ');\n // eslint-disable-next-line no-control-regex\n s = s.replace(/[\\x00-\\x1f\\x7f]/g, ' ');\n // Collapse any run of whitespace to a single dash.\n s = s.replace(/\\s+/g, '-');\n // Trim leading/trailing dashes/dots.\n s = s.replace(/^[-.]+|[-.]+$/g, '');\n if (s.length === 0) return 'unnamed';\n // Windows reserves these device names in every directory.\n return /^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i.test(s) ? `${s}-` : s;\n}\n\n/**\n * Deterministically resolve slug collisions within a namespace. Compared\n * case-insensitively: on Windows and macOS `Alpha` and `alpha` are the same\n * directory, and one would silently overwrite the other.\n */\nfunction uniqueSlug(base: string, used: Set<string>): string {\n let candidate = base;\n for (let n = 2; used.has(candidate.toLowerCase()); n += 1) candidate = `${base}-${n}`;\n used.add(candidate.toLowerCase());\n return candidate;\n}\n\n/** POSIX-style relative path for storage inside markers (stable across OS). */\nfunction relPosix(fromDir: string, toFile: string): string {\n return path.relative(fromDir, toFile).split(path.sep).join('/');\n}\n\n/** The real path of the tree being exploded, for the write check below. */\nconst explodeRoot = new AsyncLocalStorage<string>();\n\n/**\n * Refuse a write whose real directory is outside the tree: the names are\n * sanitised, but a symlink or junction already inside the tree could still\n * redirect it.\n */\nasync function assertInsideTree(filePath: string): Promise<void> {\n const root = explodeRoot.getStore();\n if (root === undefined) return;\n // Check the nearest directory that already exists, before creating any:\n // mkdir through a link would already have created directories outside.\n let dir = path.dirname(filePath);\n while (!existsSync(dir) && path.dirname(dir) !== dir) dir = path.dirname(dir);\n const real = await realpath(dir);\n if (real !== root && !real.startsWith(root + path.sep)) {\n throw new Error(`refusing to write outside the working tree: ${filePath}`);\n }\n // A safe parent does not make an existing file link safe to overwrite.\n const existing = await lstat(filePath).catch((err: NodeJS.ErrnoException) => {\n if (err.code !== 'ENOENT') throw err;\n return undefined;\n });\n if (existing?.isSymbolicLink()) throw new Error(`refusing to write through a file link: ${filePath}`);\n}\n\nasync function writeFileMkdir(filePath: string, data: string): Promise<void> {\n await assertInsideTree(filePath);\n await mkdir(path.dirname(filePath), { recursive: true });\n // NO added trailing newline — code strings must round-trip byte-identical.\n await writeFile(filePath, data);\n}\n\nasync function writeJson(filePath: string, value: Json): Promise<void> {\n await assertInsideTree(filePath);\n await mkdir(path.dirname(filePath), { recursive: true });\n await writeFile(filePath, JSON.stringify(value, null, 2));\n}\n\n// --- explode ---------------------------------------------------------------\n\n/**\n * Recursively extract code leaves from a value tree, IN PLACE (caller passes a\n * clone). `jsonDir` is the directory of the JSON file that will hold this tree;\n * `codeDir` is the directory under which sidecar `.js` files for this tree are\n * written; `prefixParts` accumulates the ancestor key/index chain for fallback\n * naming. `usedPaths` dedupes generated file paths within this resource.\n */\nasync function extractCode(\n value: Json,\n ctx: {\n jsonDir: string;\n codeDir: string;\n friendly: string | null; // friendly relative path (no extension) if known\n prefixParts: string[]; // ancestor key chain for fallback naming\n usedPaths: Set<string>;\n },\n): Promise<Json> {\n if (Array.isArray(value)) {\n const out: Json[] = [];\n for (let i = 0; i < value.length; i += 1) {\n out.push(\n await extractCode(value[i] as Json, {\n ...ctx,\n friendly: null,\n prefixParts: [...ctx.prefixParts, String(i)],\n }),\n );\n }\n return out;\n }\n\n if (!isPlainObject(value)) {\n return value;\n }\n\n // Recurse, applying friendly-path recognition for known Mirth structures.\n return extractFromObject(value, ctx);\n}\n\nasync function extractFromObject(\n obj: Record<string, Json>,\n ctx: {\n jsonDir: string;\n codeDir: string;\n friendly: string | null;\n prefixParts: string[];\n usedPaths: Set<string>;\n },\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n\n for (const [key, raw] of Object.entries(obj)) {\n // Code leaf? Only extract plain non-empty string leaves.\n if (CODE_KEY_SET.has(key) && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw; // keep empty/whitespace-only inline (no file)\n continue;\n }\n const friendlyBase =\n key in CHANNEL_SCRIPT_FRIENDLY\n ? `scripts/${CHANNEL_SCRIPT_FRIENDLY[key]}`\n : // One filename segment: config keys are untrusted and may hold '/' or '..'.\n ctx.friendly ?? `_code/${slug([...ctx.prefixParts, key].join('.'))}`;\n const filePath = resolveUnique(ctx.codeDir, `${friendlyBase}.js`, ctx.usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(ctx.jsonDir, filePath) };\n continue;\n }\n\n // Recurse into children.\n out[key] = await extractCode(raw as Json, {\n ...ctx,\n friendly: null,\n prefixParts: [...ctx.prefixParts, key],\n });\n }\n\n return out;\n}\n\n/** Resolve a unique absolute file path for a friendly-or-fallback rel path. */\nfunction resolveUnique(baseDir: string, relName: string, used: Set<string>): string {\n const ext = path.extname(relName);\n const dir = path.dirname(relName);\n const stem = path.basename(relName, ext);\n const dirSlug = dir === '.' ? '' : dir;\n // Build slugged segments for the directory portion (preserve structure).\n const segs = dirSlug.split('/').filter(Boolean);\n // Case-insensitive, like uniqueSlug.\n let rel = [...segs, `${stem}${ext}`].join('/');\n for (let n = 2; used.has(rel.toLowerCase()); n += 1) rel = [...segs, `${stem}-${n}${ext}`].join('/');\n used.add(rel.toLowerCase());\n const full = path.resolve(baseDir, ...rel.split('/'));\n if (!full.startsWith(path.resolve(baseDir) + path.sep)) throw new Error(`script path escapes its directory: ${relName}`);\n return full;\n}\n\n/**\n * Walk a channel object giving friendly paths to its scripts and connector\n * transformer/filter steps, extracting code leaves in place. Returns the\n * transformed channel object. `dir` is the channel's directory (also the dir of\n * its `channel.json`). `usedPaths` dedupes within the channel.\n */\nasync function explodeChannelTree(\n channel: Record<string, Json>,\n dir: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n\n for (const [key, raw] of Object.entries(channel)) {\n // Channel-level scripts -> scripts/<friendly>.js\n if (key in CHANNEL_SCRIPT_FRIENDLY && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw;\n continue;\n }\n const filePath = resolveUnique(dir, `scripts/${CHANNEL_SCRIPT_FRIENDLY[key]}.js`, usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(dir, filePath) };\n continue;\n }\n\n if (key === 'sourceConnector' && isPlainObject(raw)) {\n out[key] = await explodeConnector(raw, dir, 'source', 'source/receiver', usedPaths);\n continue;\n }\n\n if (key === 'destinationConnectors' && isPlainObject(raw)) {\n out[key] = await explodeDestinationConnectors(raw, dir, usedPaths);\n continue;\n }\n\n // Everything else: generic extraction (covers unknown structures / code).\n out[key] = await extractCode(raw as Json, {\n jsonDir: dir,\n codeDir: dir,\n friendly: null,\n prefixParts: [key],\n usedPaths,\n });\n }\n\n return out;\n}\n\n/**\n * Explode a connector (source or a single destination). `baseRel` is the\n * relative directory prefix within the channel dir for this connector's\n * transformer/filter steps (e.g. `source` or `destinations/<slug>`).\n * `scriptFileBase` is the friendly path (no extension) for the connector's own\n * reader/writer code at `properties.script` (e.g. `source/receiver` or\n * `destinations/<slug>/writer`).\n */\nasync function explodeConnector(\n connector: Record<string, Json>,\n channelDir: string,\n baseRel: string,\n scriptFileBase: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n\n for (const [key, raw] of Object.entries(connector)) {\n if (key === 'transformer' && isPlainObject(raw)) {\n out[key] = await explodeStepContainer(raw, channelDir, `${baseRel}/transformer`, usedPaths);\n continue;\n }\n if (key === 'responseTransformer' && isPlainObject(raw)) {\n out[key] = await explodeStepContainer(\n raw,\n channelDir,\n `${baseRel}/responseTransformer`,\n usedPaths,\n );\n continue;\n }\n if (key === 'filter' && isPlainObject(raw)) {\n out[key] = await explodeStepContainer(raw, channelDir, `${baseRel}/filter`, usedPaths);\n continue;\n }\n if (key === 'properties' && isPlainObject(raw)) {\n out[key] = await explodeConnectorProperties(raw, channelDir, scriptFileBase, usedPaths);\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: [baseRel, key],\n usedPaths,\n });\n }\n\n return out;\n}\n\n/**\n * Explode a connector's `properties` object. The JavaScript Reader/Writer\n * connectors carry their body directly at `properties.script`; extract it to a\n * friendly `<scriptFileBase>.js`. Anything else recurses generically.\n */\nasync function explodeConnectorProperties(\n properties: Record<string, Json>,\n channelDir: string,\n scriptFileBase: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n for (const [key, raw] of Object.entries(properties)) {\n if (key === 'script' && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw;\n continue;\n }\n const filePath = resolveUnique(channelDir, `${scriptFileBase}.js`, usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(channelDir, filePath) };\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: ['properties', key],\n usedPaths,\n });\n }\n return out;\n}\n\nasync function explodeDestinationConnectors(\n container: Record<string, Json>,\n channelDir: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n const usedDestSlugs = new Set<string>();\n\n for (const [key, raw] of Object.entries(container)) {\n if (key === 'connector') {\n const connectors = asArray<Record<string, Json>>(raw);\n const wasArray = Array.isArray(raw);\n const transformed: Record<string, Json>[] = [];\n for (const conn of connectors) {\n const name = isPlainObject(conn) ? conn['name'] : undefined;\n const destSlug = uniqueSlug(slug(name), usedDestSlugs);\n transformed.push(\n isPlainObject(conn)\n ? await explodeConnector(\n conn,\n channelDir,\n `destinations/${destSlug}`,\n `destinations/${destSlug}/writer`,\n usedPaths,\n )\n : conn,\n );\n }\n out[key] = wasArray ? transformed : (transformed[0] as Json);\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: ['destinationConnectors', key],\n usedPaths,\n });\n }\n\n return out;\n}\n\n/**\n * Explode a transformer/filter/responseTransformer container. Mirth nests the\n * actual steps under an `elements` key. In REAL data `elements` is an OBJECT\n * keyed by the step's fully-qualified Java class name (e.g.\n * `com.mirth.connect.plugins.javascriptstep.JavaScriptStep`), whose value is an\n * array of step objects:\n *\n * elements: { \"com.mirth...JavaScriptStep\": [ { name, sequenceNumber, script } ] }\n *\n * An empty transformer/filter serializes `elements` as the empty string `\"\"`.\n * We give each step a friendly `<baseRel>/<n>.<slug(step name)>.js` path, where\n * `n` is `sequenceNumber + 1` (string-parsed) falling back to a running index.\n * Unknown shapes fall back to generic extraction so we never crash.\n */\nasync function explodeStepContainer(\n container: Record<string, Json>,\n channelDir: string,\n baseRel: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n\n for (const [key, raw] of Object.entries(container)) {\n if (key === 'elements' && (Array.isArray(raw) || isPlainObject(raw))) {\n out[key] = await explodeElementsContainer(\n raw as Json[] | Record<string, Json>,\n channelDir,\n baseRel,\n usedPaths,\n );\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: [baseRel, key],\n usedPaths,\n });\n }\n\n return out;\n}\n\n/** Does an object look like a single step (carries a code leaf or step metadata)? */\nfunction isStepLike(obj: Record<string, Json>): boolean {\n return (\n typeof obj['script'] === 'string' ||\n typeof obj['code'] === 'string' ||\n 'sequenceNumber' in obj ||\n 'name' in obj\n );\n}\n\n/**\n * Dispatch the `elements` value of a step container, numbering steps globally\n * in encounter order. Handles three shapes:\n * - ARRAY of step objects (a legacy / hand-written form).\n * - a single step OBJECT (`elements` collapsed to one step).\n * - the REAL Mirth form: an OBJECT keyed by fully-qualified class name whose\n * values are arrays (or single objects) of step objects.\n */\nasync function explodeElementsContainer(\n elements: Json[] | Record<string, Json>,\n channelDir: string,\n baseRel: string,\n usedPaths: Set<string>,\n): Promise<Json> {\n const counter = { i: 0 };\n\n if (Array.isArray(elements)) {\n return explodeStepArray(elements, channelDir, baseRel, usedPaths, counter);\n }\n\n // A single step object directly under `elements`.\n if (isStepLike(elements)) {\n return explodeStep(elements, channelDir, baseRel, counter.i++, usedPaths);\n }\n\n // Class-keyed map of step buckets (the real shape).\n const out: Record<string, Json> = {};\n for (const [className, raw] of Object.entries(elements)) {\n // Attributes (`@_...`), adapter metadata (`#order`, `#comment`) and nulls\n // are passed through generically, not numbered as steps.\n if (className.startsWith('@_') || className.startsWith('#') || raw == null) {\n out[className] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: [baseRel, 'elements', className],\n usedPaths,\n });\n continue;\n }\n if (Array.isArray(raw)) {\n out[className] = await explodeStepArray(raw, channelDir, baseRel, usedPaths, counter);\n continue;\n }\n if (isPlainObject(raw) && isStepLike(raw)) {\n out[className] = await explodeStep(raw, channelDir, baseRel, counter.i++, usedPaths);\n continue;\n }\n out[className] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: [baseRel, 'elements', className],\n usedPaths,\n });\n }\n return out;\n}\n\nasync function explodeStepArray(\n steps: Json[],\n channelDir: string,\n baseRel: string,\n usedPaths: Set<string>,\n counter: { i: number },\n): Promise<Json[]> {\n const transformed: Json[] = [];\n for (const step of steps) {\n transformed.push(await explodeStep(step, channelDir, baseRel, counter.i++, usedPaths));\n }\n return transformed;\n}\n\nasync function explodeStep(\n step: Json,\n channelDir: string,\n baseRel: string,\n index: number,\n usedPaths: Set<string>,\n): Promise<Json> {\n if (!isPlainObject(step)) {\n return step;\n }\n\n // Sequence number (Mirth) is 0-based; prefer it, else fall back to index.\n const seqRaw = step['sequenceNumber'];\n let seq = index;\n if (typeof seqRaw === 'number') seq = seqRaw;\n else if (typeof seqRaw === 'string' && seqRaw.trim() !== '' && !Number.isNaN(Number(seqRaw))) {\n seq = Number(seqRaw);\n }\n const n = seq + 1;\n const stepName = step['name'];\n // Many real steps have no `name`; fall back to a bare `<n>` segment so the\n // file reads as e.g. `1.js` rather than `1.unnamed.js`.\n const hasName = typeof stepName === 'string' && stepName.trim().length > 0;\n const friendlyBase = hasName ? `${baseRel}/${n}.${slug(stepName)}` : `${baseRel}/${n}`;\n\n const out: Record<string, Json> = {};\n for (const [key, raw] of Object.entries(step)) {\n if (CODE_KEY_SET.has(key) && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw;\n continue;\n }\n const filePath = resolveUnique(channelDir, `${friendlyBase}.js`, usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(channelDir, filePath) };\n continue;\n }\n // Recurse generically into anything else (handles nested unknowns).\n out[key] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: [baseRel, String(index), key],\n usedPaths,\n });\n }\n return out;\n}\n\n/**\n * Split the three known top-level collections into per-resource JSON files,\n * replacing each element with an `@ref` marker (order preserved). Each split-out\n * resource is itself code-extracted under its own directory.\n *\n * Returns the rewritten container value (object or array preserved as-is) with\n * `@ref` markers, or null if the collection was absent.\n */\nasync function splitCollection(\n parent: Record<string, Json>,\n containerKey: string, // e.g. 'channels'\n elementKey: string, // e.g. 'channel'\n root: string,\n serverDir: string, // dir holding configuration.json (markers are relative to it)\n targetFor: (name: unknown, slugName: string) => { jsonFile: string; resourceDir: string },\n usedSlugs: Set<string>,\n explodeResource: (\n el: Record<string, Json>,\n resourceDir: string,\n ) => Promise<Record<string, Json>>,\n): Promise<void> {\n const container = parent[containerKey];\n if (!isPlainObject(container)) return;\n const raw = container[elementKey];\n if (raw == null) return;\n\n const wasArray = Array.isArray(raw);\n const elements = asArray<Json>(raw);\n const refs: Json[] = [];\n\n // Suffixes for colliding names (\"Lab Feed\", \"LAB FEED\") are handed out by\n // name then id, not list order: the server's order can change (a restore\n // reorders it), which would move a resource to another directory.\n const byName = (el: Record<string, Json>) => `${slug(el['name']).toLowerCase()}\\u0000${String(el['id'] ?? '')}`;\n const slugs = new Map<Json, string>();\n for (const el of elements.filter(isPlainObject).sort((a, b) => (byName(a) < byName(b) ? -1 : byName(a) > byName(b) ? 1 : 0))) {\n slugs.set(el, uniqueSlug(slug(el['name']), usedSlugs));\n }\n\n for (const el of elements) {\n if (!isPlainObject(el)) {\n // Non-object element: keep inline (cannot meaningfully split).\n refs.push(el);\n continue;\n }\n const slugName = slugs.get(el)!;\n const { jsonFile, resourceDir } = targetFor(el['name'], slugName);\n const transformed = await explodeResource(el, resourceDir);\n await writeJson(jsonFile, transformed);\n refs.push({ '@ref': relPosix(serverDir, jsonFile) });\n }\n\n // Preserve object-vs-array shape of the element container.\n container[elementKey] = wasArray ? refs : (refs[0] as Json);\n}\n\nasync function explode(config: CanonicalConfig, opts: ExplodeOptions): Promise<void> {\n await mkdir(opts.root, { recursive: true });\n await explodeRoot.run(await realpath(opts.root), () => explodeInto(config, opts));\n}\n\nasync function explodeInto(config: CanonicalConfig, opts: ExplodeOptions): Promise<void> {\n const root = opts.root;\n const serverDir = path.join(root, 'server');\n const skeleton = deepClone(config) as Record<string, Json>;\n\n // 1. channels.channel[] -> channels/<slug>/channel.json\n if (isPlainObject(skeleton['channels'])) {\n const channelSlugs = new Set<string>();\n await splitCollection(\n skeleton,\n 'channels',\n 'channel',\n root,\n serverDir,\n (_name, slugName) => {\n const resourceDir = path.join(root, 'channels', slugName);\n return { jsonFile: path.join(resourceDir, 'channel.json'), resourceDir };\n },\n channelSlugs,\n async (el, resourceDir) => explodeChannelTree(el, resourceDir, new Set<string>()),\n );\n }\n\n // 2. codeTemplateLibraries.codeTemplateLibrary[] -> codeTemplates/<slug>/library.json\n if (isPlainObject(skeleton['codeTemplateLibraries'])) {\n const libSlugs = new Set<string>();\n await splitCollection(\n skeleton,\n 'codeTemplateLibraries',\n 'codeTemplateLibrary',\n root,\n serverDir,\n (_name, slugName) => {\n const resourceDir = path.join(root, 'codeTemplates', slugName);\n return { jsonFile: path.join(resourceDir, 'library.json'), resourceDir };\n },\n libSlugs,\n async (el, resourceDir) => explodeLibrary(el, resourceDir),\n );\n }\n\n // 3. channelGroups.channelGroup[] -> channelGroups/<slug>.json\n if (isPlainObject(skeleton['channelGroups'])) {\n const groupSlugs = new Set<string>();\n await splitCollection(\n skeleton,\n 'channelGroups',\n 'channelGroup',\n root,\n serverDir,\n (_name, slugName) => {\n const resourceDir = path.join(root, 'channelGroups');\n return { jsonFile: path.join(resourceDir, `${slugName}.json`), resourceDir };\n },\n groupSlugs,\n async (el, resourceDir) =>\n // group json lives in channelGroups/; sidecar code (rare) under same dir\n extractCode(el, {\n jsonDir: resourceDir,\n codeDir: resourceDir,\n friendly: null,\n prefixParts: ['channelGroup'],\n usedPaths: new Set<string>(),\n }) as Promise<Record<string, Json>>,\n );\n }\n\n // 4. Extract code in the remaining skeleton (e.g. globalScripts) and write it.\n const finalSkeleton = await extractCode(skeleton, {\n jsonDir: serverDir,\n codeDir: serverDir,\n friendly: null,\n prefixParts: [],\n usedPaths: new Set<string>(),\n });\n\n await writeJson(path.join(serverDir, 'configuration.json'), finalSkeleton);\n}\n\n/**\n * Explode a code template library: split-out resource. Each template's `code`\n * leaf -> `<slug(template name)>.js` next to library.json (resourceDir).\n */\nasync function explodeLibrary(\n library: Record<string, Json>,\n resourceDir: string,\n): Promise<Record<string, Json>> {\n const used = new Set<string>();\n const usedTemplateSlugs = new Set<string>();\n const out: Record<string, Json> = {};\n\n for (const [key, raw] of Object.entries(library)) {\n if (key === 'codeTemplates' && isPlainObject(raw)) {\n out[key] = await explodeLibraryTemplates(raw, resourceDir, usedTemplateSlugs, used);\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: resourceDir,\n codeDir: resourceDir,\n friendly: null,\n prefixParts: [key],\n usedPaths: used,\n });\n }\n return out;\n}\n\nasync function explodeLibraryTemplates(\n container: Record<string, Json>,\n resourceDir: string,\n usedTemplateSlugs: Set<string>,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n for (const [key, raw] of Object.entries(container)) {\n if (key === 'codeTemplate' && raw != null) {\n const wasArray = Array.isArray(raw);\n const templates = asArray<Json>(raw);\n const transformed: Json[] = [];\n for (const t of templates) {\n transformed.push(\n await explodeCodeTemplate(t, resourceDir, usedTemplateSlugs, usedPaths),\n );\n }\n out[key] = wasArray ? transformed : (transformed[0] as Json);\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: resourceDir,\n codeDir: resourceDir,\n friendly: null,\n prefixParts: ['codeTemplates', key],\n usedPaths,\n });\n }\n return out;\n}\n\nasync function explodeCodeTemplate(\n template: Json,\n resourceDir: string,\n usedTemplateSlugs: Set<string>,\n usedPaths: Set<string>,\n): Promise<Json> {\n if (!isPlainObject(template)) return template;\n const friendlyBase = uniqueSlug(slug(template['name']), usedTemplateSlugs);\n const out: Record<string, Json> = {};\n for (const [key, raw] of Object.entries(template)) {\n // In real Mirth data the body lives at `properties.code`; handle that and\n // (defensively) a `code`/`script` leaf directly on the template object.\n if (key === 'properties' && isPlainObject(raw)) {\n out[key] = await explodeTemplateProperties(raw, resourceDir, friendlyBase, usedPaths);\n continue;\n }\n if (CODE_KEY_SET.has(key) && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw;\n continue;\n }\n const filePath = resolveUnique(resourceDir, `${friendlyBase}.js`, usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(resourceDir, filePath) };\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: resourceDir,\n codeDir: resourceDir,\n friendly: null,\n prefixParts: ['codeTemplate', key],\n usedPaths,\n });\n }\n return out;\n}\n\n/**\n * Explode a code template's `properties` object, whose `code` leaf is the\n * template body -> friendly `<friendlyBase>.js` next to library.json.\n */\nasync function explodeTemplateProperties(\n properties: Record<string, Json>,\n resourceDir: string,\n friendlyBase: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n for (const [key, raw] of Object.entries(properties)) {\n if (CODE_KEY_SET.has(key) && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw;\n continue;\n }\n const filePath = resolveUnique(resourceDir, `${friendlyBase}.js`, usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(resourceDir, filePath) };\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: resourceDir,\n codeDir: resourceDir,\n friendly: null,\n prefixParts: ['codeTemplate', 'properties', key],\n usedPaths,\n });\n }\n return out;\n}\n\n// --- implode ---------------------------------------------------------------\n\n/**\n * Resolve a marker path relative to `jsonDir` and assert it stays inside the\n * working-tree `root`. Legitimate markers DO use `..` (e.g. `server/`'s config\n * references `../channelGroups/*.json`), so `..` is allowed — only escaping the\n * tree root is rejected. Working trees are shared/cloned git repos, so marker\n * values are attacker-influenceable input; without this check a crafted\n * `{\"@file\": \"../../../../etc/passwd\"}` would be read into the imploded config\n * (and, via `push`, uploaded to a live server).\n */\nfunction resolveWithinRoot(root: string, jsonDir: string, rel: string): string {\n const target = path.resolve(jsonDir, rel);\n if (target !== root && !target.startsWith(root + path.sep)) {\n throw new Error(`marker path escapes the working tree: ${rel}`);\n }\n return target;\n}\n\n/**\n * Read a marker target, re-checking containment on the real path: the text\n * check above can't see a symlink or junction inside the tree that points\n * outside it.\n */\nasync function readWithinRoot(root: string, target: string, rel: string): Promise<string> {\n const [realRoot, realTarget] = await Promise.all([realpath(root), realpath(target)]);\n if (realTarget !== realRoot && !realTarget.startsWith(realRoot + path.sep)) {\n throw new Error(`marker path escapes the working tree through a link: ${rel}`);\n }\n return readFile(realTarget, 'utf8');\n}\n\n/**\n * Recursively resolve markers in a parsed JSON value. `jsonDir` is the directory\n * of the JSON file this value came from (markers are relative to it); `root` is\n * the working-tree root that every marker target must stay within.\n */\nasync function resolveMarkers(value: Json, jsonDir: string, root: string): Promise<Json> {\n if (Array.isArray(value)) {\n const out: Json[] = [];\n for (const item of value) {\n // A collection member whose file is gone was deleted from the tree\n // (e.g. `rm -r channels/<name>`), so it is dropped, not an error.\n if (isRefMarker(item) && !existsSync(resolveWithinRoot(root, jsonDir, item['@ref']))) continue;\n out.push(await resolveMarkers(item, jsonDir, root));\n }\n return out;\n }\n\n if (isFileRef(value)) {\n const target = resolveWithinRoot(root, jsonDir, value['@file']);\n // Raw read, NO trimming — byte-identical round-trip.\n return readWithinRoot(root, target, value['@file']);\n }\n\n if (isRefMarker(value)) {\n const target = resolveWithinRoot(root, jsonDir, value['@ref']);\n const text = await readWithinRoot(root, target, value['@ref']);\n const parsed = parseJson<Json>(text, target);\n return resolveMarkers(parsed, path.dirname(target), root);\n }\n\n if (isPlainObject(value)) {\n const out: Record<string, Json> = {};\n for (const [k, v] of Object.entries(value)) {\n // Same for a one-member collection, which explode stores as a bare marker.\n if (isRefMarker(v) && !existsSync(resolveWithinRoot(root, jsonDir, v['@ref']))) continue;\n out[k] = await resolveMarkers(v, jsonDir, root);\n }\n return out;\n }\n\n return value;\n}\n\nasync function implode(opts: ExplodeOptions): Promise<CanonicalConfig> {\n const root = path.resolve(opts.root);\n const serverDir = path.join(root, 'server');\n const configPath = path.join(serverDir, 'configuration.json');\n const parsed = await readJson<Json>(configPath);\n const resolved = await resolveMarkers(parsed, serverDir, root);\n return resolved as CanonicalConfig;\n}\n\n// --- factory ---------------------------------------------------------------\n\nexport function createExplodeEngine(): ExplodeEngine {\n return { explode, implode };\n}\n","/**\n * Shared contracts for channelvault.\n *\n * The whole tool is organized around a single in-memory representation called\n * the **canonical config**: a plain JSON object tree that mirrors Mirth's\n * `serverConfiguration` document. Two adapters produce/consume it:\n *\n * - XML adapter (src/xml): backup .xml <-> canonical (dev / offline path)\n * - Mirth client (src/client): live server <-> canonical (GET/PUT /server/configuration)\n *\n * The explode engine (src/explode) projects a canonical config onto a\n * git-friendly directory tree and reverses it, with embedded JavaScript pulled\n * out into sidecar `.js` files.\n */\n\n/** A JSON value as produced by the XML adapter or the live API. */\nexport type Json = string | number | boolean | null | Json[] | { [k: string]: Json };\n\n/** A canonical config object (the `serverConfiguration` payload, unwrapped). */\nexport type CanonicalConfig = { [k: string]: Json };\n\n/**\n * Marker left in a `*.json` file in place of an extracted script/code leaf.\n *\n * During explode, a code-bearing string leaf (e.g. a transformer step's\n * `script`, or a code template's `code`) is written to a sidecar `.js` file and\n * the original string is replaced, in place, with `{ \"@file\": \"<relpath>\" }`.\n * During implode, any object whose only key is `@file` is replaced by the text\n * content of that file. The path is relative to the JSON file holding the marker.\n */\nexport interface FileRef {\n '@file': string;\n}\n\nexport function isFileRef(v: unknown): v is FileRef {\n return (\n typeof v === 'object' &&\n v !== null &&\n !Array.isArray(v) &&\n Object.keys(v).length === 1 &&\n typeof (v as Record<string, unknown>)['@file'] === 'string'\n );\n}\n\n/**\n * The set of leaf element keys whose string values are treated as JavaScript\n * and extracted to sidecar `.js` files. Detection is by key name plus a\n * non-trivial-content check (see explode engine).\n */\nexport const CODE_KEYS = ['script', 'code'] as const;\n\n/**\n * Channel-level script keys that live directly on a channel object (no nesting).\n * Extracted into `<channel>/scripts/<name>.js`.\n */\nexport const CHANNEL_SCRIPT_KEYS = [\n 'preprocessingScript',\n 'postprocessingScript',\n 'deployScript',\n 'undeployScript',\n] as const;\n\n// --- XML adapter contract -------------------------------------------------\n\nexport interface XmlAdapter {\n /** Parse a Mirth backup XML string into a canonical config. */\n parse(xml: string): CanonicalConfig;\n /** Serialize a canonical config back to Mirth backup XML. */\n build(config: CanonicalConfig): string;\n}\n\n// --- Explode engine contract ----------------------------------------------\n\nexport interface ExplodeOptions {\n /** Absolute path to the working tree root. */\n root: string;\n}\n\nexport interface ExplodeEngine {\n /** Write a canonical config out as a directory tree under `root`. */\n explode(config: CanonicalConfig, opts: ExplodeOptions): Promise<void>;\n /** Read a directory tree under `root` back into a canonical config. */\n implode(opts: ExplodeOptions): Promise<CanonicalConfig>;\n}\n\n// --- Mirth client contract ------------------------------------------------\n\nexport interface ClientConfig {\n host: string;\n port: number;\n username: string;\n password: string;\n /** default true */\n https?: boolean;\n /** default false; set true for self-signed certs */\n disableTlsCheck?: boolean;\n /**\n * default false. Put the server's response body in error messages. A body\n * can echo the credentials that were sent; it is decoded and has credential\n * fields redacted, but the caller must still scrub known secret values.\n */\n includeResponseBodies?: boolean;\n}\n\nexport interface ApiError {\n status: number;\n statusText: string;\n message: string;\n body?: unknown;\n}\n\nexport interface ApiResponse<T> {\n data: T | null;\n error: ApiError | null;\n}\n\nexport interface MirthClient {\n login(): Promise<void>;\n logout(): Promise<void>;\n isAuthenticated(): boolean;\n /** GET /server/configuration -> canonical config (whole-server snapshot). */\n getServerConfiguration(): Promise<CanonicalConfig>;\n /** PUT /server/configuration <- canonical config. */\n putServerConfiguration(config: CanonicalConfig): Promise<void>;\n}\n","import { readFile } from 'node:fs/promises';\n\n/** JSON.parse, naming the file in the error: a tree has hundreds of JSON files. */\nexport function parseJson<T = unknown>(text: string, file: string): T {\n try {\n return JSON.parse(text) as T;\n } catch (err) {\n throw new Error(`${file}: ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nexport async function readJson<T = unknown>(file: string): Promise<T> {\n return parseJson<T>(await readFile(file, 'utf8'), file);\n}\n","/**\n * XML canonical adapter for Mirth Connect \"Backup Config\" documents.\n *\n * Converts a Mirth `serverConfiguration` XML document to/from the canonical\n * config (a plain JSON object tree). `fast-xml-parser` v5 does the tokenizing in\n * its order-preserving mode; the conversion to the canonical object shape and\n * the serializer are ours, because fxp's object mode is lossy in ways a\n * round-trip test built on the same parser cannot see (it regroups interleaved\n * siblings, concatenates mixed-content text, and renames `__proto__`).\n *\n * Canonical shape (unchanged from the original fxp object-mode shape, so\n * existing exploded trees stay valid):\n *\n * - An element with no attributes and no child elements is its text, as a\n * STRING (`\"\"` when empty). Values are never coerced or trimmed: Mirth ids,\n * ports, `\"0B\"`, leading zeros and script-body whitespace all survive.\n * - Otherwise it is an object: child elements (and `#comment`) keyed by name in\n * first-appearance order, then `#text`, then attributes as `@_<name>`.\n * - Repeated names become arrays; `ALWAYS_ARRAY_TAGS` are arrays even when\n * single, so downstream code never special-cases \"one vs many\".\n * - Whitespace-only text beside child elements is indentation and is dropped.\n * - `#order` records the document order of an element's children ONLY when\n * the default order (keys in order, each array contiguous, `#text` last)\n * would differ from it — e.g. a transformer whose steps interleave\n * `JavaScriptStep` and `MapperStep`. It never appears for ordinary Mirth\n * output, and a stale hint (after hand-editing) degrades gracefully.\n *\n * Text fidelity: we own entity decode/encode. XML end-of-line handling (a\n * literal CRLF or CR in the document is a LF) and attribute-value\n * normalization (a literal tab/newline in an attribute is a space) are applied\n * as a conforming parser — Mirth's — would apply them, so the canonical value is\n * what Mirth actually reads. Characters those rules would destroy (CR, and tab\n * or newline inside attributes) are written back as character references.\n *\n * The acceptance criterion is a semantic, order-preserving round-trip:\n *\n * parse(build(parse(xml))) deep-equals parse(xml)\n *\n * plus document order of the rebuilt XML equal to the source's (see tests).\n */\nimport { XMLParser, XMLValidator } from 'fast-xml-parser';\nimport type { CanonicalConfig, Json, XmlAdapter } from '../types.js';\n\n/**\n * Well-known Mirth collection element tags that must ALWAYS be arrays, even\n * when a document contains only a single instance.\n */\nconst ALWAYS_ARRAY_TAGS: ReadonlySet<string> = new Set<string>([\n 'channel',\n 'connector',\n 'codeTemplate',\n 'codeTemplateLibrary',\n 'channelGroup',\n 'alert',\n 'rule',\n 'entry',\n 'string',\n // Fully-qualified JavaScript step / rule element names (live under <elements>).\n 'com.mirth.connect.plugins.javascriptstep.JavaScriptStep',\n 'com.mirth.connect.plugins.javascriptrule.JavaScriptRule',\n 'com.mirth.connect.plugins.mapper.MapperStep',\n 'com.mirth.connect.plugins.messagebuilder.MessageBuilderStep',\n]);\n\n/** The single top-level wrapper key of a Mirth backup document. */\nconst ROOT_KEY = 'serverConfiguration';\n\nconst TEXT_KEY = '#text';\nconst COMMENT_KEY = '#comment';\nconst CDATA_KEY = '#cdata';\n/** Document-order hint; `#` cannot start an XML name, so it cannot collide. */\nexport const ORDER_KEY = '#order';\nconst ATTR_PREFIX = '@_';\nconst ORDERED_ATTRS = ':@';\nconst INDENT = ' ';\n\n/** An fxp `preserveOrder` node: `{ <name>: children, ':@'?: attrs }`. */\ntype OrderedNode = Record<string, unknown>;\n\nfunction isWhitespaceOnly(s: string): boolean {\n return /^\\s*$/.test(s);\n}\n\n/** Named XML entities (the five predefined) -> their character. */\nconst NAMED_DECODE: Readonly<Record<string, string>> = {\n amp: '&',\n lt: '<',\n gt: '>',\n quot: '\"',\n apos: \"'\",\n};\n\n/**\n * Decode XML entities in a single left-to-right pass: the five predefined named\n * entities plus decimal (`&#10;`) and hex (`&#xd;`) numeric character\n * references.\n *\n * A single non-overlapping scan is what makes `&#xd;` and `&amp;#xd;`\n * distinguishable: `&amp;` is consumed as one token (-> `&`) and its output is\n * not re-scanned, so the trailing `#xd;` stays literal.\n */\nfunction decodeEntities(value: string): string {\n if (!value.includes('&')) return value;\n return value.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g, (whole, body: string) => {\n if (body[0] !== '#') return NAMED_DECODE[body] ?? whole;\n const code =\n body[1] === 'x' || body[1] === 'X' ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);\n if (!(code <= 0x10ffff)) {\n throw new Error(`XmlConfigAdapter.parse: invalid character reference ${whole}`);\n }\n return String.fromCodePoint(code);\n });\n}\n\nfunction charRef(ch: string): string {\n return `&#x${ch.charCodeAt(0).toString(16)};`;\n}\n\nconst ESCAPE: Readonly<Record<string, string>> = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&apos;',\n};\n\n/**\n * Encode text content. Escapes the same set fxp's builder did (so unchanged\n * values serialize byte-identically) and writes CR and the other C0 controls\n * except tab/LF as character references: a literal CR would be read back as LF.\n */\nfunction encodeText(value: string): string {\n // eslint-disable-next-line no-control-regex\n return value.replace(/[&<>\"'\\x00-\\x08\\x0b-\\x1f]/g, (ch) => ESCAPE[ch] ?? charRef(ch));\n}\n\n/** Encode an attribute value; tab and LF must be references there too. */\nfunction encodeAttr(value: string): string {\n // eslint-disable-next-line no-control-regex\n return value.replace(/[&<>\"'\\x00-\\x1f]/g, (ch) => ESCAPE[ch] ?? charRef(ch));\n}\n\n// --- parse -----------------------------------------------------------------\n\nfunction nodeName(node: OrderedNode): string {\n const name = Object.keys(node).find((k) => k !== ORDERED_ATTRS);\n if (name === undefined) throw new Error('XmlConfigAdapter.parse: empty node');\n return name;\n}\n\n/** Concatenated text of a `#comment` / `#cdata` node's children, undecoded. */\nfunction rawInnerText(children: unknown): string {\n return (children as OrderedNode[]).map((c) => String(c[TEXT_KEY] ?? '')).join('');\n}\n\n/** The child sequence the serializer emits for `obj` absent an `#order` hint. */\nfunction defaultOrder(obj: Record<string, Json>): string[] {\n const seq: string[] = [];\n for (const [key, value] of Object.entries(obj)) {\n if (key.startsWith(ATTR_PREFIX) || key === ORDER_KEY) continue;\n const count = Array.isArray(value) ? value.length : 1;\n for (let i = 0; i < count; i += 1) seq.push(key);\n }\n return seq;\n}\n\n/** Convert one element's ordered children + attributes to its canonical value. */\nfunction convertElement(children: OrderedNode[], attrs: Record<string, string> | undefined): Json {\n const hasElementChild = children.some((c) => {\n const n = nodeName(c);\n return n !== TEXT_KEY && n !== CDATA_KEY;\n });\n\n // Merge adjacent text/CDATA runs into text segments (CDATA is literal: no\n // entity decoding), and record the document order of what we keep.\n const groups = new Map<string, Json[]>();\n const order: string[] = [];\n const segments: string[] = [];\n let pending: string | null = null;\n const flushText = (): void => {\n if (pending === null) return;\n if (!hasElementChild || !isWhitespaceOnly(pending)) {\n segments.push(pending);\n order.push(TEXT_KEY);\n }\n pending = null;\n };\n\n for (const child of children) {\n const name = nodeName(child);\n if (name === TEXT_KEY) {\n pending = (pending ?? '') + decodeEntities(String(child[TEXT_KEY]));\n continue;\n }\n if (name === CDATA_KEY) {\n pending = (pending ?? '') + rawInnerText(child[CDATA_KEY]);\n continue;\n }\n flushText();\n // fxp renames this element to `#__proto__`; it cannot be an object key.\n if (name === '#__proto__') {\n throw new Error('XmlConfigAdapter.parse: unsupported element name <__proto__>');\n }\n const value =\n name === COMMENT_KEY\n ? rawInnerText(child[COMMENT_KEY])\n : convertElement(child[name] as OrderedNode[], child[ORDERED_ATTRS] as Record<string, string>);\n const group = groups.get(name);\n if (group) group.push(value);\n else groups.set(name, [value]);\n order.push(name);\n }\n flushText();\n\n const attrEntries = Object.entries(attrs ?? {});\n if (!hasElementChild && attrEntries.length === 0) {\n return segments.join('');\n }\n\n const obj: Record<string, Json> = {};\n for (const [name, values] of groups) {\n obj[name] = values.length > 1 || ALWAYS_ARRAY_TAGS.has(name) ? values : values[0]!;\n }\n if (segments.length === 1) obj[TEXT_KEY] = segments[0]!;\n else if (segments.length > 1) obj[TEXT_KEY] = segments;\n\n for (const [key, raw] of attrEntries) {\n if (key === `${ATTR_PREFIX}__proto__`) {\n throw new Error('XmlConfigAdapter.parse: unsupported attribute name __proto__');\n }\n // Attribute-value normalization: literal tab/LF (CRs are already LFs) read\n // as a space; character references were the way to keep them.\n obj[key] = decodeEntities(String(raw).replace(/[\\t\\n]/g, ' '));\n }\n\n const def = defaultOrder(obj);\n if (def.length !== order.length || def.some((k, i) => k !== order[i])) {\n obj[ORDER_KEY] = order;\n }\n return obj;\n}\n\nconst parser = new XMLParser({\n preserveOrder: true,\n ignoreAttributes: false,\n attributeNamePrefix: ATTR_PREFIX,\n parseTagValue: false,\n parseAttributeValue: false,\n trimValues: false,\n processEntities: false,\n commentPropName: COMMENT_KEY,\n cdataPropName: CDATA_KEY,\n});\n\n// --- build -----------------------------------------------------------------\n\n/**\n * The children of `obj` in emit order: honours an `#order` hint as far as it\n * matches the actual children, then appends anything it didn't mention in\n * default order. So adding, removing or renaming a child by hand never loses it.\n */\nfunction orderedChildren(obj: Record<string, Json>, where: string): Array<[string, Json]> {\n const queues = new Map<string, Json[]>();\n for (const [key, value] of Object.entries(obj)) {\n if (key.startsWith(ATTR_PREFIX) || key === ORDER_KEY) continue;\n queues.set(key, Array.isArray(value) ? [...value] : [value]);\n }\n const out: Array<[string, Json]> = [];\n const hint = obj[ORDER_KEY];\n if (hint !== undefined) {\n if (!Array.isArray(hint) || !hint.every((h) => typeof h === 'string')) {\n throw new Error(`XmlConfigAdapter.build: ${ORDER_KEY} under <${where}> must be an array of names`);\n }\n for (const name of hint as string[]) {\n const next = queues.get(name)?.shift();\n if (next !== undefined) out.push([name, next]);\n }\n }\n for (const [key, rest] of queues) {\n for (const value of rest) out.push([key, value]);\n }\n return out;\n}\n\nfunction scalar(value: Json): string {\n return value === null ? '' : String(value);\n}\n\nfunction serialize(name: string, value: Json, depth: number, pretty: boolean, out: string[]): void {\n const pad = pretty ? INDENT.repeat(depth) : '';\n const nl = pretty ? '\\n' : '';\n\n if (name === COMMENT_KEY) {\n const text = scalar(value);\n if (text.includes('--') || text.endsWith('-')) {\n throw new Error(`XmlConfigAdapter.build: comment text cannot contain \"--\": ${text}`);\n }\n out.push(`${pad}<!--${text}-->${nl}`);\n return;\n }\n if (name === TEXT_KEY) {\n out.push(encodeText(scalar(value)));\n return;\n }\n\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n out.push(`${pad}<${name}>${encodeText(scalar(value))}</${name}>${nl}`);\n return;\n }\n\n const attrs = Object.entries(value)\n .filter(([k]) => k.startsWith(ATTR_PREFIX))\n .map(([k, v]) => ` ${k.slice(ATTR_PREFIX.length)}=\"${encodeAttr(scalar(v))}\"`)\n .join('');\n const children = orderedChildren(value, name);\n const hasElementChild = children.some(([k]) => k !== TEXT_KEY);\n\n if (!hasElementChild) {\n const text = children.map(([, v]) => encodeText(scalar(v))).join('');\n out.push(`${pad}<${name}${attrs}>${text}</${name}>${nl}`);\n return;\n }\n\n // Mixed content can't be indented: the indentation would become part of its\n // text. Emit that element compactly.\n const mixed = children.some(([k]) => k === TEXT_KEY);\n const childPretty = pretty && !mixed;\n out.push(`${pad}<${name}${attrs}>${childPretty ? '\\n' : ''}`);\n for (const [key, child] of children) {\n serialize(key, child, depth + 1, childPretty, out);\n }\n out.push(`${childPretty ? pad : ''}</${name}>${nl}`);\n}\n\n// --- adapter ---------------------------------------------------------------\n\nexport class XmlConfigAdapter implements XmlAdapter {\n /** Parse a Mirth backup XML string into a canonical config. */\n parse(xml: string): CanonicalConfig {\n // XML end-of-line handling, which fxp does not apply.\n const normalized = xml.replace(/\\r\\n?/g, '\\n');\n if (/<!DOCTYPE/i.test(normalized.slice(0, normalized.search(/<[A-Za-z_]/)))) {\n // A DTD could declare entities we would not expand; Mirth never emits one.\n throw new Error('XmlConfigAdapter.parse: DOCTYPE declarations are not supported');\n }\n // fxp's parser accepts unclosed elements, so a truncated backup would read\n // as a smaller, \"valid\" configuration; validate the whole document first.\n const valid = XMLValidator.validate(normalized);\n if (valid !== true) {\n const { line, col, msg } = valid.err;\n throw new Error(`XmlConfigAdapter.parse: not well-formed XML at line ${line}, column ${col}: ${msg}`);\n }\n const nodes = parser.parse(normalized) as OrderedNode[];\n const root = nodes.find((n) => nodeName(n) === ROOT_KEY);\n if (root === undefined) {\n throw new Error(`XmlConfigAdapter.parse: expected a top-level <${ROOT_KEY}> element`);\n }\n const value = convertElement(root[ROOT_KEY] as OrderedNode[], root[ORDERED_ATTRS] as Record<string, string>);\n return (typeof value === 'object' && value !== null && !Array.isArray(value) ? value : {}) as CanonicalConfig;\n }\n\n /** Serialize a canonical config back to Mirth backup XML. */\n build(config: CanonicalConfig): string {\n const out: string[] = [];\n serialize(ROOT_KEY, config, 0, true, out);\n return out.join('');\n }\n}\n","/**\n * Live Mirth transport client.\n *\n * Talks to a running Mirth Connect (a.k.a. NextGen Connect / OIE / BridgeLink)\n * server over its REST API and produces/consumes the canonical config (the\n * unwrapped `serverConfiguration` document) — the same logical document the XML\n * adapter parses from a backup file.\n *\n * The transport (login, cookie jar, TLS bypass, 401 re-auth, single-flight\n * login) is ported from the proven `baseClient.ts` in the sibling\n * `integration-engine-api` project. We deliberately do NOT carry over the\n * OpenAPI-generated typing layers: payloads are opaque `CanonicalConfig` JSON.\n *\n * Wrapping behavior for the two endpoints:\n *\n * - GET /server/configuration returns a Jackson-style document wrapped in a\n * single top-level key (`serverConfiguration`), with `@version` / `@class`\n * metadata sprinkled throughout. `getServerConfiguration()` unwraps the\n * single top-level key and returns its contents.\n * - PUT /server/configuration expects the same wrapper, so\n * `putServerConfiguration()` re-wraps as `{ serverConfiguration: config }`.\n */\nimport { CookieJar } from 'tough-cookie';\nimport { Agent } from 'undici';\nimport { redactSecretsInText } from '../secrets/detect.js';\nimport { isSecretKey } from '../secrets/index.js';\nimport type { ApiError, CanonicalConfig, ClientConfig, MirthClient } from '../types.js';\n\n/** TLS verification failures, typically a self-signed or privately issued server certificate. */\nexport const UNTRUSTED_CERT_CODES: ReadonlySet<string> = new Set([\n 'DEPTH_ZERO_SELF_SIGNED_CERT',\n 'SELF_SIGNED_CERT_IN_CHAIN',\n 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',\n 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',\n // Not an expired certificate or a host-name mismatch: turning verification\n // off is the wrong advice for those, and their messages already say why.\n]);\n\n/**\n * fetch reports every network failure as \"fetch failed\" and keeps the reason\n * (ECONNREFUSED, a certificate error) in `cause`; surface it, with its code.\n */\nfunction connectionError(url: string, err: unknown): Error & { code?: string } {\n let cause = err instanceof Error ? (err.cause as (Error & { code?: string; errors?: unknown[] }) | undefined) : undefined;\n // Several addresses tried (IPv4 and IPv6): report the first attempt.\n if (cause instanceof AggregateError && cause.errors[0] instanceof Error) cause = cause.errors[0] as Error & { code?: string };\n const detail = cause?.message || (err instanceof Error ? err.message : String(err));\n const code = cause?.code;\n const error = new Error(\n `cannot reach ${new URL(url).origin}: ${detail}${code && !detail.includes(code) ? ` (${code})` : ''}`,\n { cause: err },\n ) as Error & { code?: string };\n error.code = code;\n return error;\n}\n\n/** Optional flags accepted by `putServerConfiguration` (Mirth query params). */\nexport interface PutServerConfigurationOptions {\n /** Redeploy all channels after applying the configuration. */\n deploy?: boolean;\n /** Overwrite the global configuration map. */\n overwriteConfigMap?: boolean;\n}\n\n/**\n * The public client type. It satisfies the declared {@link MirthClient}\n * contract but widens `putServerConfiguration` to accept the optional Mirth\n * query-param flags. The widened signature is structurally assignable to the\n * one-arg contract (the extra parameter is optional), so a `MirthClientExt`\n * is a valid `MirthClient` wherever the bare contract is expected.\n */\nexport interface MirthClientExt extends MirthClient {\n putServerConfiguration(config: CanonicalConfig, options?: PutServerConfigurationOptions): Promise<void>;\n /** GET /server/id: the installation's ID, which a configuration restore does not change (verified on 4.5.2). */\n getServerId(): Promise<string>;\n /** GET /server/configuration as the server's own XML (the Administrator's Backup Config document). */\n getServerConfigurationXml(): Promise<string>;\n /** PUT /server/configuration from backup XML, as the Administrator's Restore Config does. */\n putServerConfigurationXml(xml: string, options?: PutServerConfigurationOptions): Promise<void>;\n /** GET /channels/{id}, unwrapped; includes the tag and dependency data the server configuration omits. */\n getChannel(id: string): Promise<Record<string, unknown> | null>;\n /** PUT /channels/{id}; creates the channel if the id is new. */\n putChannel(channel: Record<string, unknown>): Promise<void>;\n /** Release pooled connections so the process can exit promptly. */\n close(): Promise<void>;\n deleteChannel(id: string): Promise<void>;\n /** PUT /codeTemplates/{id}; creates the template if the id is new. */\n putCodeTemplate(template: Record<string, unknown>): Promise<void>;\n deleteCodeTemplate(id: string): Promise<void>;\n /** PUT /codeTemplateLibraries: replaces the whole list (membership and library settings). */\n putCodeTemplateLibraries(libraries: Record<string, unknown>[]): Promise<void>;\n /** PUT /server/globalScripts, from the `globalScripts` value of a server configuration. */\n putGlobalScripts(globalScripts: unknown): Promise<void>;\n /** POST /channels/{id}/_deploy; throws if deployment fails. */\n deployChannel(id: string): Promise<void>;\n /** Ids of the channels currently deployed (GET /channels/statuses). */\n getDeployedChannelIds(): Promise<Set<string>>;\n}\n\n/** Internal HTTP verbs we use. */\ntype HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n\n/** Options for the low-level authenticated request helper. */\ninterface RequestOptions {\n /** Already-serialized request body. */\n body?: string;\n /** Query parameters appended to the URL. */\n query?: Record<string, unknown>;\n /** Additional headers merged over the defaults. */\n headers?: Record<string, string>;\n}\n\n/** Shape of the (unwrapped) Mirth login status payload we read. */\ninterface LoginStatusPayload {\n status?: string;\n message?: string | null;\n}\n\n/** The single top-level wrapper key of a Mirth backup / server config document. */\nconst SERVER_CONFIG_KEY = 'serverConfiguration';\n\n/**\n * Unwrap a Jackson-style single-key wrapper. Mirth wraps many responses in a\n * single top-level namespace key. If the value has exactly one top-level key we\n * unwrap it; otherwise we return it unchanged (defensive against the wrapper\n * being named differently or absent).\n */\nfunction unwrapSingleKey(value: Record<string, unknown>): unknown {\n const keys = Object.keys(value);\n if (keys.length === 1) {\n return value[keys[0] as string];\n }\n return value;\n}\n\n/**\n * MirthClient implementation. Created via {@link createMirthClient}.\n */\nclass MirthClientImpl implements MirthClientExt {\n private readonly config: ClientConfig;\n private readonly baseUrl: string;\n private readonly cookieJar: CookieJar;\n /** Our own pool (not the global one) so `close()` can release it. */\n private readonly dispatcher: Agent;\n\n private authenticated = false;\n /** Single in-flight login promise (concurrency guard). */\n private loginPromise: Promise<void> | null = null;\n\n constructor(config: ClientConfig) {\n this.config = config;\n const protocol = config.https !== false ? 'https' : 'http';\n this.baseUrl = `${protocol}://${config.host}:${config.port}/api`;\n this.cookieJar = new CookieJar();\n\n this.dispatcher = new Agent(config.disableTlsCheck ? { connect: { rejectUnauthorized: false } } : {});\n }\n\n isAuthenticated(): boolean {\n return this.authenticated;\n }\n\n /**\n * Establish a session. Concurrent calls share a single in-flight login.\n */\n async login(): Promise<void> {\n if (this.loginPromise) {\n return this.loginPromise;\n }\n\n this.loginPromise = (async () => {\n try {\n const loginUrl = `${this.baseUrl}/users/_login`;\n\n const body = new URLSearchParams({\n username: this.config.username,\n password: this.config.password,\n });\n\n const response = await this.send(loginUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'X-Requested-With': 'XMLHttpRequest',\n Accept: 'application/json',\n },\n body: body.toString(),\n });\n\n await this.storeCookies(response, this.baseUrl);\n\n if (!response.ok) {\n // Not the body: a login endpoint's error page can echo the request.\n await response.body?.cancel();\n throw new Error(`Login failed: HTTP ${response.status} ${response.statusText}`.trimEnd());\n }\n\n const result = (await response.json()) as Record<string, unknown>;\n\n // Mirth wraps the result, e.g.\n // { 'com.mirth.connect.model.LoginStatus': { status: 'SUCCESS', message: null } }\n const payload = unwrapSingleKey(result) as LoginStatusPayload;\n\n if (payload.status !== 'SUCCESS') {\n throw new Error(`Login failed: ${payload.status} - ${payload.message ?? 'Unknown error'}`);\n }\n\n this.authenticated = true;\n } finally {\n this.loginPromise = null;\n }\n })();\n\n return this.loginPromise;\n }\n\n /**\n * End the session and clear local auth state + cookies.\n */\n async logout(): Promise<void> {\n if (!this.authenticated) {\n return;\n }\n\n try {\n const logoutUrl = `${this.baseUrl}/users/_logout`;\n const cookieString = await this.cookieJar.getCookieString(logoutUrl);\n await this.send(logoutUrl, {\n method: 'POST',\n headers: {\n 'X-Requested-With': 'XMLHttpRequest',\n ...(cookieString ? { Cookie: cookieString } : {}),\n },\n });\n } finally {\n this.authenticated = false;\n await this.cookieJar.removeAllCookies();\n }\n }\n\n /**\n * GET /server/configuration -> canonical config.\n *\n * Requests JSON, parses it, and unwraps the single top-level\n * `serverConfiguration` key (defensively: any single-key wrapper is unwrapped;\n * a multi-key object is returned as-is).\n */\n async getServerConfiguration(): Promise<CanonicalConfig> {\n const response = await this.request('GET', '/server/configuration', {\n headers: { Accept: 'application/json' },\n });\n\n const json = (await response.json()) as Record<string, unknown>;\n return unwrapSingleKey(json) as CanonicalConfig;\n }\n\n /**\n * PUT /server/configuration <- canonical config.\n *\n * Re-wraps the canonical config as `{ serverConfiguration: config }` and\n * forwards the optional `deploy` / `overwriteConfigMap` flags as query params.\n */\n async putServerConfiguration(config: CanonicalConfig, options: PutServerConfigurationOptions = {}): Promise<void> {\n const query: Record<string, unknown> = {};\n if (options.deploy !== undefined) {\n query.deploy = options.deploy;\n }\n if (options.overwriteConfigMap !== undefined) {\n query.overwriteConfigMap = options.overwriteConfigMap;\n }\n\n const wrapped = { [SERVER_CONFIG_KEY]: config };\n\n await this.request('PUT', '/server/configuration', {\n query,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n },\n body: JSON.stringify(wrapped),\n });\n }\n\n async getServerId(): Promise<string> {\n // JSON is refused (406); the ID comes as plain text.\n const response = await this.request('GET', '/server/id', { headers: { Accept: 'text/plain' } });\n return (await response.text()).trim();\n }\n\n async getServerConfigurationXml(): Promise<string> {\n const response = await this.request('GET', '/server/configuration', { headers: { Accept: 'application/xml' } });\n return response.text();\n }\n\n async putServerConfigurationXml(xml: string, options: PutServerConfigurationOptions = {}): Promise<void> {\n await this.request('PUT', '/server/configuration', {\n query: { deploy: options.deploy, overwriteConfigMap: options.overwriteConfigMap },\n headers: { 'Content-Type': 'application/xml', Accept: 'application/json' },\n body: xml,\n });\n }\n\n // --- per-resource ---------------------------------------------------------\n // Override is on: Mirth does not reject a stale revision anyway (verified on\n // 4.5.2), so conflict detection happens in the push planner instead.\n\n async getChannel(id: string): Promise<Record<string, unknown> | null> {\n const response = await this.request('GET', `/channels/${encodeURIComponent(id)}`, {\n headers: { Accept: 'application/json' },\n });\n const text = await response.text();\n if (text.trim() === '') return null;\n return unwrapSingleKey(JSON.parse(text) as Record<string, unknown>) as Record<string, unknown>;\n }\n\n async close(): Promise<void> {\n await this.dispatcher.close();\n }\n\n async putChannel(channel: Record<string, unknown>): Promise<void> {\n await this.sendJson('PUT', `/channels/${encodeURIComponent(String(channel.id))}`, { channel }, { override: true });\n }\n\n async deleteChannel(id: string): Promise<void> {\n await this.request('DELETE', `/channels/${encodeURIComponent(id)}`);\n }\n\n async putCodeTemplate(template: Record<string, unknown>): Promise<void> {\n await this.sendJson('PUT', `/codeTemplates/${encodeURIComponent(String(template.id))}`, { codeTemplate: template }, { override: true });\n }\n\n async deleteCodeTemplate(id: string): Promise<void> {\n await this.request('DELETE', `/codeTemplates/${encodeURIComponent(id)}`);\n }\n\n async putCodeTemplateLibraries(libraries: Record<string, unknown>[]): Promise<void> {\n await this.sendJson('PUT', '/codeTemplateLibraries', { list: { codeTemplateLibrary: libraries } }, { override: true });\n }\n\n async putGlobalScripts(globalScripts: unknown): Promise<void> {\n await this.sendJson('PUT', '/server/globalScripts', { map: globalScripts });\n }\n\n async getDeployedChannelIds(): Promise<Set<string>> {\n const response = await this.request('GET', '/channels/statuses', { headers: { Accept: 'application/json' } });\n const text = await response.text();\n const ids = new Set<string>();\n // Undeployed channels have no status entry; collect every channelId present.\n for (const m of text.matchAll(/\"channelId\"\\s*:\\s*\"([^\"]+)\"/g)) ids.add(m[1]!);\n return ids;\n }\n\n async deployChannel(id: string): Promise<void> {\n await this.request('POST', `/channels/${encodeURIComponent(id)}/_deploy`, { query: { returnErrors: true } });\n }\n\n /** Send a JSON body; Mirth answers some updates with `{\"boolean\": false}` instead of an error status. */\n private async sendJson(method: HttpMethod, path: string, body: unknown, query?: Record<string, unknown>): Promise<void> {\n const response = await this.request(method, path, {\n query,\n headers: { 'Content-Type': 'application/json', Accept: 'application/json' },\n body: JSON.stringify(body),\n });\n const text = await response.text();\n if (/^\\s*\\{\\s*\"boolean\"\\s*:\\s*false\\s*\\}\\s*$/.test(text)) {\n throw new Error(`${method} ${path}: the server refused the update`);\n }\n }\n\n // --- internal transport ---------------------------------------------------\n\n /**\n * Make an authenticated request. Ensures login, attaches/stores cookies, and\n * on a 401 while authenticated resets auth, re-logs in once, and retries.\n * Throws an {@link ApiError}-shaped error on a non-2xx response.\n */\n private async request(method: HttpMethod, path: string, options: RequestOptions = {}, isRetry = false): Promise<Response> {\n if (!this.authenticated) {\n await this.login();\n }\n\n const url = this.buildUrl(path, options.query);\n\n const headers: Record<string, string> = {\n 'X-Requested-With': 'XMLHttpRequest',\n ...options.headers,\n };\n\n const cookieString = await this.cookieJar.getCookieString(url);\n if (cookieString) {\n headers.Cookie = cookieString;\n }\n\n const response = await this.send(url, { method, headers, body: options.body });\n\n await this.storeCookies(response, url);\n\n // 401 while authenticated -> reset auth, re-login once, retry exactly once.\n if (response.status === 401 && this.authenticated && !isRetry) {\n this.authenticated = false;\n await this.login();\n return this.request(method, path, options, true);\n }\n\n if (!response.ok) {\n throw await this.toApiError(response);\n }\n\n return response;\n }\n\n /** fetch through this client's pool, with network failures explained. */\n private async send(url: string, init: RequestInit): Promise<Response> {\n try {\n return await fetch(url, {\n ...init,\n // @ts-expect-error - dispatcher is a Node.js/undici specific option\n dispatcher: this.dispatcher,\n });\n } catch (err) {\n throw connectionError(url, err);\n }\n }\n\n /** Build an absolute URL with an optional query string. */\n private buildUrl(path: string, query?: Record<string, unknown>): string {\n const url = `${this.baseUrl}${path}`;\n if (!query || Object.keys(query).length === 0) {\n return url;\n }\n\n const searchParams = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) {\n continue;\n }\n searchParams.append(key, String(value));\n }\n\n const qs = searchParams.toString();\n return qs ? `${url}?${qs}` : url;\n }\n\n /** Persist any `set-cookie` from a response into the jar. */\n private async storeCookies(response: Response, url: string): Promise<void> {\n // One entry per header: get('set-cookie') joins them with \", \", which also\n // appears inside a cookie's Expires date.\n for (const cookie of response.headers.getSetCookie()) {\n await this.cookieJar.setCookie(cookie, url);\n }\n }\n\n /** Build an ApiError-shaped Error from a non-2xx response. */\n private async toApiError(response: Response): Promise<Error & ApiError> {\n let body: unknown;\n try {\n body = await response.text();\n } catch {\n // ignore body read errors\n }\n\n // An error body can echo the payload sent, credentials included, in any\n // form (escaped, truncated, reformatted), so no redaction of it is\n // complete: it is left out unless asked for. When included it is whole and\n // unnormalized, so the caller's scrub of known values can still match.\n const text = typeof body === 'string' ? redactSecretsInText(readableBody(body)).trim() : '';\n const reason =\n text === '' ? '' : this.config.includeResponseBodies ? `: ${text}` : ' (server response withheld; it may echo credentials)';\n const message = `HTTP ${response.status}: ${response.statusText}${reason}`;\n const error = new Error(message) as Error & ApiError;\n error.status = response.status;\n error.statusText = response.statusText;\n error.message = message;\n error.body = text;\n return error;\n }\n}\n\nconst XML_ENTITIES: Readonly<Record<string, string>> = { amp: '&', lt: '<', gt: '>', quot: '\"', apos: \"'\" };\n\n/**\n * An error body as the text a person reads: JSON as its decoded values, XML as\n * its decoded text. Anything that redacts by value (the CLI knows the secrets\n * sent) then sees a secret as it was sent, not escaped as `\\\"` or `&amp;`.\n * Credential fields are replaced while their names are still known.\n */\nexport function readableBody(body: string): string {\n const trimmed = body.trim();\n // Any JSON value: a bare string can carry \\u escapes too.\n if (/^[[{\"]/.test(trimmed)) {\n try {\n return flattenJson(JSON.parse(trimmed) as unknown);\n } catch {\n // not JSON after all\n }\n }\n if (!trimmed.startsWith('<')) return trimmed;\n // Mirth's HTML error pages say only \"Request failed.\", so they add nothing.\n if (/^<(!doctype|html)/i.test(trimmed)) return '';\n // A marker that survives removing the tags.\n const REDACTED = '\\u0000redacted\\u0000';\n return trimmed\n .replace(/<([\\w.:-]+)>[^<]*<\\/\\1>/g, (whole, key: string) => (isSecretKey(key) ? ` ${key}: ${REDACTED} ` : whole))\n .replace(/<[^>]*>/g, ' ')\n .split(REDACTED)\n .join('<redacted>')\n .replace(/&(#x[0-9a-f]+|#[0-9]+|amp|lt|gt|quot|apos);/gi, (whole, e: string) =>\n e[0] === '#'\n ? String.fromCodePoint(e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10))\n : (XML_ENTITIES[e.toLowerCase()] ?? whole),\n );\n}\n\nfunction flattenJson(value: unknown, key = ''): string {\n if (typeof value === 'string') return key !== '' && isSecretKey(key) && value !== '' ? '<redacted>' : value;\n if (Array.isArray(value)) return value.map((v) => flattenJson(v, key)).join('; ');\n if (value !== null && typeof value === 'object') {\n return Object.entries(value).map(([k, v]) => `${k}: ${flattenJson(v, k)}`).join(', ');\n }\n return String(value);\n}\n\n/**\n * Factory for the live Mirth transport client.\n */\nexport function createMirthClient(config: ClientConfig): MirthClientExt {\n return new MirthClientImpl(config);\n}\n","/**\n * Find secrets that the key-name rules in `templatize` miss: credentials\n * embedded in URLs and connection strings, authorization headers, password\n * assignments in scripts, private keys and well-known token formats.\n *\n * Findings are reported by location and kind only; a secret value is never\n * printed. `extract` replaces just the secret part of each string with an\n * `{{env:NAME}}` placeholder, so the surrounding script or URL stays readable.\n */\nimport { createHash } from 'node:crypto';\n\nimport { CHANNEL_SCRIPT_KEYS, CODE_KEYS, type CanonicalConfig } from '../types.js';\nimport { derivedName, hasPlaceholder, isSecretKey, mapLeaves, placeholder, type Env, type Leaf } from './index.js';\n\nexport type SecretKind =\n | 'private-key'\n | 'url-credentials'\n | 'connection-string'\n | 'authorization-header'\n | 'db-connection-call'\n | 'assignment'\n | 'setter-call'\n | 'aws-access-key'\n | 'jwt'\n | 'github-token'\n | 'slack-token';\n\n/** A secret's position in a string. */\ninterface Span {\n start: number;\n end: number;\n}\n\ninterface Rule {\n kind: SecretKind;\n /** Suffix for the env variable name. */\n suffix: string;\n /** `script`: the value is JavaScript (a step, template or channel script). */\n spans(value: string, script: boolean): Span[];\n}\n\n/** Spans of capture group `group` (0 = whole match) of every match of `re`. */\nfunction regexSpans(re: RegExp, group: number): (value: string) => Span[] {\n return (value) => {\n const out: Span[] = [];\n for (const m of value.matchAll(re)) {\n const secret = m[group];\n if (secret === undefined) continue;\n // The secret is the last occurrence of its text within the match.\n const start = m.index + m[0].lastIndexOf(secret);\n out.push({ start, end: start + secret.length });\n }\n return out;\n };\n}\n\n/**\n * The fourth argument of `createDatabaseConnection(driver, url, user, password)`\n * when it is a string literal. Arguments are split at top-level commas, so\n * calls like `$('driver')` in earlier arguments don't throw it off.\n */\nfunction dbConnectionSpans(value: string): Span[] {\n const out: Span[] = [];\n for (const m of value.matchAll(/createDatabaseConnection\\s*\\(/g)) {\n let depth = 0;\n let quote: string | null = null;\n let argStart = m.index + m[0].length;\n const args: Span[] = [];\n for (let i = argStart; i < value.length; i += 1) {\n const c = value[i]!;\n if (quote) {\n if (c === '\\\\') i += 1;\n else if (c === quote) quote = null;\n continue;\n }\n if (c === '\"' || c === \"'\") quote = c;\n else if (c === '(' || c === '[' || c === '{') depth += 1;\n else if ((c === ')' || c === ']' || c === '}') && depth > 0) depth -= 1;\n else if ((c === ',' && depth === 0) || c === ')') {\n args.push({ start: argStart, end: i });\n argStart = i + 1;\n if (c === ')') break;\n }\n }\n const pw = args[3];\n if (!pw) continue;\n const literal = /^\\s*([\"'])(.+)\\1\\s*$/s.exec(value.slice(pw.start, pw.end));\n if (literal) {\n const start = value.indexOf(literal[2]!, pw.start);\n out.push({ start, end: start + literal[2]!.length });\n }\n }\n return out;\n}\n\n/**\n * The tail of `name = 'literal'` / `name: \"literal\"`: an optional default-value\n * prefix (`name || `, `name ?? `), then a quoted literal of 4+ characters on one\n * line. Braces are excluded so `${var}` templates and placeholders don't match. A\n * literal with spaces must also hold a digit or symbol, so prose such as\n * `secret = 'Not configured yet'` is not a secret.\n */\nconst ASSIGNED = String.raw`[\"']?\\s*[:=]\\s*(?:[\\w$.[\\]'\"]+\\s*(?:\\|\\||\\?\\?)\\s*)?([\"'])((?=\\S)(?:[^\"'{}\\s]{4,}|(?=[^\"'{}\\n]*[0-9@#$%^&*+=~|\\\\/<>_])[^\"'{}\\n]{4,}))\\1`;\n\n/** A connection-string value: up to the next delimiter, without surrounding spaces. */\nconst CONN_VALUE = String.raw`([^;&'\"\\s](?:[^;&'\"\\n]*[^;&'\"\\s])?)`;\n\n/**\n * String literals and comments of a script: where a connection string can\n * appear as text. Regex literals are not recognised, so a quote inside one\n * can shift what counts as a literal.\n */\nfunction textSpans(code: string): Span[] {\n const out: Span[] = [];\n let i = 0;\n while (i < code.length) {\n const c = code[i]!;\n const next = code[i + 1];\n if (c === '/' && (next === '/' || next === '*')) {\n const close = next === '/' ? code.indexOf('\\n', i) : code.indexOf('*/', i + 2);\n const end = close < 0 ? code.length : close;\n out.push({ start: i + 2, end });\n i = end + 2;\n } else if (c === '\"' || c === \"'\" || c === '`') {\n let j = i + 1;\n while (j < code.length && code[j] !== c && (c === '`' || code[j] !== '\\n')) j += code[j] === '\\\\' ? 2 : 1;\n out.push({ start: i + 1, end: Math.min(j, code.length) });\n i = j + 1;\n } else {\n i += 1;\n }\n }\n return out;\n}\n\n/** Apply `spans` to a whole data value, but only to the text parts of a script. */\nfunction outsideCode(spans: (value: string) => Span[]): (value: string, script: boolean) => Span[] {\n return (value, script) =>\n script\n ? textSpans(value).flatMap((t) => spans(value.slice(t.start, t.end)).map((s) => ({ start: s.start + t.start, end: s.end + t.start })))\n : spans(value);\n}\n\n// Earlier rules win where spans overlap: a private key block may contain text\n// other rules match, and `token = 'ghp_…'` is one secret, not two.\nconst RULES: Rule[] = [\n {\n kind: 'private-key',\n suffix: 'PRIVATE_KEY',\n spans: regexSpans(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, 0),\n },\n { kind: 'aws-access-key', suffix: 'AWS_ACCESS_KEY', spans: regexSpans(/\\b(?:AKIA|ASIA)[0-9A-Z]{16}\\b/g, 0) },\n { 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) },\n { kind: 'github-token', suffix: 'TOKEN', spans: regexSpans(/\\b(?:ghp|gho|ghs|ghu|github_pat)_[A-Za-z0-9_]{20,}/g, 0) },\n { kind: 'slack-token', suffix: 'TOKEN', spans: regexSpans(/\\bxox[abprs]-[A-Za-z0-9-]{10,}/g, 0) },\n // user:password@host. The user part stops at ';', '?' and '&' so a JDBC\n // parameter like `user=svc@srv` is not mistaken for credentials.\n { kind: 'url-credentials', suffix: 'PASSWORD', spans: regexSpans(/\\b[a-z][a-z0-9+.-]*:\\/\\/[^\\s:/@'\";?&]+:([^\\s@'\"/;?&]+)@/gi, 1) },\n // Drivers trim around `=` and the value, so spaces are allowed there. In a\n // script only string literals and comments are searched: `pwd=$('x')` is code.\n {\n kind: 'connection-string',\n suffix: 'PASSWORD',\n spans: outsideCode(regexSpans(new RegExp(String.raw`[;?&]\\s*(?:password|pwd)\\s*=\\s*${CONN_VALUE}`, 'gi'), 1)),\n },\n // Leading the whole value (`Password=…;Server=…`), when another key=value follows.\n {\n kind: 'connection-string',\n suffix: 'PASSWORD',\n spans: outsideCode(regexSpans(new RegExp(String.raw`^\\s*(?:password|pwd)\\s*=\\s*${CONN_VALUE}(?=\\s*;\\s*[\\w ]+=)`, 'gi'), 1)),\n },\n // Case-sensitive, and the credential must contain a digit or a base64/token\n // symbol, so prose like \"Basic authentication\" does not match.\n {\n kind: 'authorization-header',\n suffix: 'TOKEN',\n spans: regexSpans(/\\b(?:Basic|Bearer)\\s+((?=[A-Za-z0-9+/=._~-]*[0-9+/=])[A-Za-z0-9+/=._~-]{12,})/g, 1),\n },\n { kind: 'db-connection-call', suffix: 'DB_PASSWORD', spans: dbConnectionSpans },\n // name = 'literal' where the name ends in a secret word: password, dbPassword,\n // db_password, DB_PASSWORD, apiKey, authToken… (not tokenizer, not ==).\n // Also the default-value idiom: apiKey = apiKey || 'literal' (or ??).\n {\n kind: 'assignment',\n suffix: 'PASSWORD',\n spans: regexSpans(new RegExp(`(?<![\\\\w$])[\\\\w$]*?(?:password|passwd|pwd|secret|api[_-]?key|access[_-]?key|token)${ASSIGNED}`, 'gi'), 2),\n },\n // `pass` as a whole name or a word boundary within one (pass, dbPass,\n // DB_PASS, sftp_pass), case-sensitive so bypass and compass don't match,\n // and not after words that make it an ordinary noun (byPass, firstPass).\n {\n kind: 'assignment',\n suffix: 'PASSWORD',\n 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),\n },\n // conn.setPassword('literal'), props.setApiKey(\"literal\")…\n {\n kind: 'setter-call',\n suffix: 'PASSWORD',\n spans: regexSpans(/\\bset[A-Za-z]*(?:Password|Passwd|Passphrase|Secret|Token|ApiKey)\\s*\\(\\s*([\"'])([^\"'\\n]{4,})\\1\\s*\\)/g, 2),\n },\n];\n\n/** A Mirth `${variable}` or one of our placeholders is a reference, not a secret. */\nfunction isReference(secret: string): boolean {\n return secret.includes('${') || hasPlaceholder(secret);\n}\n\nexport interface Finding {\n location: string;\n kind: SecretKind;\n /** Where it is, for people: enclosing channel/connector names and the field. */\n where: string;\n /** Identifies the surrounding text (secret removed), for allow entries. */\n context: string;\n}\n\n/**\n * A known false positive. `context` ties it to the surrounding text as well as\n * the location, so an entry for a transformer step at index 2 stops matching\n * if a different step moves into that index.\n */\nexport interface AllowEntry {\n location: string;\n kind: SecretKind;\n context: string;\n note?: string;\n}\n\nexport type ScanMode = 'find' | 'extract' | 'redact';\n\nexport interface ScanResult {\n config: CanonicalConfig;\n findings: Finding[];\n /** extract mode: values for the env file (only ones it doesn't already hold). Never print these. */\n envUpdates: Record<string, string>;\n}\n\ninterface Hit extends Span {\n rule: Rule;\n}\n\n/** Every secret span in `value`, earlier rules winning overlaps, in position order. */\nfunction hitsIn(value: string, script = false): Hit[] {\n const taken: Hit[] = [];\n for (const rule of RULES) {\n for (const span of rule.spans(value, script)) {\n if (span.end <= span.start || isReference(value.slice(span.start, span.end))) continue;\n if (taken.some((t) => span.start < t.end && t.start < span.end)) continue;\n taken.push({ ...span, rule });\n }\n }\n return taken.sort((a, b) => a.start - b.start);\n}\n\nconst SCRIPT_KEYS: ReadonlySet<string> = new Set<string>([...CODE_KEYS, ...CHANNEL_SCRIPT_KEYS]);\n\n/** Script leaves: step, template and channel code, and the global scripts. */\nfunction isScript(leaf: Leaf): boolean {\n return SCRIPT_KEYS.has(leaf.key) || leaf.section === 'globalScripts';\n}\n\n/** `value` with every secret a rule recognises replaced by a marker, for messages. */\nexport function redactSecretsInText(text: string): string {\n // Credential fields echoed as JSON (\"passcode\": \"…\") or XML (<keyPW>…</keyPW>),\n // by the field names `templatize` extracts, then the value rules.\n const value = text\n .replace(/(\"([\\w.-]+)\"\\s*:\\s*\")((?:[^\"\\\\]|\\\\.)+)\"/g, (whole, head: string, key: string) => (isSecretKey(key) ? `${head}<redacted>\"` : whole))\n .replace(/<([\\w.:-]+)>([^<]+)<\\/\\1>/g, (whole, key: string) => (isSecretKey(key) ? `<${key}><redacted></${key}>` : whole));\n let out = '';\n let at = 0;\n for (const h of hitsIn(value)) {\n out += `${value.slice(at, h.start)}<redacted ${h.rule.kind}>`;\n at = h.end;\n }\n return out + value.slice(at);\n}\n\n/** Hash of the string with every secret removed: stable while its text is, and holds no secret. */\nfunction contextOf(value: string, hits: Hit[]): string {\n let redacted = '';\n let at = 0;\n for (const h of hits) {\n redacted += `${value.slice(at, h.start)}\\u0000${h.rule.kind}\\u0000`;\n at = h.end;\n }\n redacted += value.slice(at);\n return createHash('sha256').update(redacted).digest('hex').slice(0, 16);\n}\n\n/**\n * Scan every string leaf. `find` reports only; `extract` swaps each secret\n * for a placeholder and returns the values; `redact` swaps it for a marker\n * (for display, e.g. in `diff`).\n */\nexport function scanSecrets(config: CanonicalConfig, opts: { mode: ScanMode; allow?: AllowEntry[]; env?: Env }): ScanResult {\n const allowed = new Set((opts.allow ?? []).map((a) => `${a.location}#${a.kind}#${a.context}`));\n const env = opts.env ?? {};\n const findings: Finding[] = [];\n const envUpdates: Record<string, string> = {};\n const assigned = new Map<string, string>(); // name -> value, this run\n\n // Names placeholders already use belong to their locations; each new\n // placeholder gets its own name, so rotating one secret never changes another.\n const inUse = new Set<string>();\n mapLeaves(config, (value) => {\n for (const m of value.matchAll(/\\{\\{env:([A-Za-z_][A-Za-z0-9_]*)\\}\\}/g)) inUse.add(m[1]!);\n return value;\n });\n const nameFor = (leaf: Leaf, rule: Rule, value: string): string => {\n const base = `${derivedName(leaf)}__${rule.suffix}`;\n for (let n = 1; ; n += 1) {\n const name = n === 1 ? base : `${base}_${n}`;\n if (assigned.has(name) || inUse.has(name)) continue;\n if (env[name] === undefined || env[name] === value) {\n assigned.set(name, value);\n // A value the environment already holds (the file, or CI's process\n // environment) is not written to the file again.\n if (env[name] !== value) envUpdates[name] = value;\n return name;\n }\n }\n };\n\n const out = mapLeaves(config, (value, leaf) => {\n const hits = hitsIn(value, isScript(leaf));\n if (hits.length === 0) return value;\n const context = contextOf(value, hits);\n let result = '';\n let at = 0;\n for (const h of hits) {\n if (allowed.has(`${leaf.location}#${h.rule.kind}#${context}`)) continue;\n findings.push({ location: leaf.location, kind: h.rule.kind, where: [...leaf.labels, leaf.key].join(' › '), context });\n if (opts.mode === 'find') continue;\n const secret = value.slice(h.start, h.end);\n const replacement = opts.mode === 'extract' ? placeholder(nameFor(leaf, h.rule, secret)) : `<redacted ${h.rule.kind}>`;\n result += value.slice(at, h.start) + replacement;\n at = h.end;\n }\n return opts.mode === 'find' ? value : result + value.slice(at);\n });\n\n return { config: out, findings, envUpdates };\n}\n\n/**\n * Known secret values that still appear verbatim somewhere in `config`: a\n * repeat no rule recognised (a default argument, a URL fragment). Values\n * shorter than 8 characters are skipped; short ones such as a database name\n * reused as a password match too much ordinary text.\n */\nexport function findEchoes(config: CanonicalConfig, secrets: Env): Array<{ name: string; where: string }> {\n const values = Object.entries(secrets).filter((e): e is [string, string] => typeof e[1] === 'string' && e[1].length >= 8);\n const out: Array<{ name: string; where: string }> = [];\n if (values.length === 0) return out;\n mapLeaves(config, (value, leaf) => {\n for (const [name, secret] of values) {\n if (value.includes(secret)) out.push({ name, where: [...leaf.labels, leaf.key].join(' › ') });\n }\n return value;\n });\n return out;\n}\n\nexport function formatFindings(findings: Finding[]): string {\n return findings\n .map((f) => ` ${f.kind.padEnd(20)} ${f.where}\\n ${''.padEnd(20)} at ${f.location} context ${f.context}`)\n .join('\\n');\n}\n","/**\n * Keep secrets and per-environment values out of the working tree.\n *\n * A string in the tree may contain `{{env:NAME}}` placeholders. `render`\n * replaces them from an environment (a `.env` file plus `process.env`) before\n * anything is sent to Mirth or written as XML. `templatize` goes the other way\n * on `pull`/`explode`: it swaps credential values for placeholders, returning\n * the values so the caller can store them in `.env`.\n *\n * The syntax is not Mirth's `${...}`, which connector fields already use for\n * Velocity variables (`${message.encodedData}`).\n */\nimport type { CanonicalConfig, Json } from '../types.js';\n\nexport type Env = Readonly<Record<string, string | undefined>>;\n\nconst PLACEHOLDER = /\\{\\{env:([A-Za-z_][A-Za-z0-9_]*)\\}\\}/g;\n\n/**\n * Credential-bearing keys: `password`, `smtpPassword`, `passPhrase`, `apiToken`,\n * and the DICOM connector's `passcode`, `keyPW`, `keyStorePW`, `trustStorePW`.\n */\nconst SECRET_KEY = /(password|passwd|passphrase|passcode|secret|token|pw|pwd|(?:api|access|secret|private)[_-]?key)$/i;\n\n/** Mirth's configuration-map entry value holder (XML and live shapes). */\nconst CONFIG_PROPERTY = 'com.mirth.connect.util.ConfigurationProperty';\n\nexport function placeholder(name: string): string {\n return `{{env:${name}}}`;\n}\n\nexport function hasPlaceholder(value: string): boolean {\n PLACEHOLDER.lastIndex = 0;\n return PLACEHOLDER.test(value);\n}\n\n/** Fill every placeholder in `value`; names with no value are collected in `missing`. */\nfunction fill(value: string, env: Env, missing: Set<string>): string {\n return value.replace(PLACEHOLDER, (whole, name: string) => {\n const v = env[name];\n if (v === undefined) {\n missing.add(name);\n return whole;\n }\n return v;\n });\n}\n\n/**\n * Replace every placeholder in the config. Throws, naming every missing\n * variable, rather than sending a literal `{{env:…}}` to a server.\n */\nexport function render(config: CanonicalConfig, env: Env): CanonicalConfig {\n const missing = new Set<string>();\n const walk = (node: Json): Json => {\n if (typeof node === 'string') return fill(node, env, missing);\n if (Array.isArray(node)) return node.map(walk);\n if (node && typeof node === 'object') {\n const out: Record<string, Json> = {};\n for (const [k, v] of Object.entries(node)) out[k] = walk(v);\n return out;\n }\n return node;\n };\n const out = walk(config) as CanonicalConfig;\n if (missing.size > 0) {\n throw new Error(\n `missing values for ${[...missing].sort().join(', ')} (set them in the env file or the environment)`,\n );\n }\n return out;\n}\n\n// --- locations -------------------------------------------------------------\n\ntype Segment = string;\n\n/**\n * A stable address for a value: array elements are identified by `id` or\n * `metaDataId` when they have one, so reordering or adding channels does not\n * move an existing placeholder to a different value.\n */\nfunction elementSegment(el: Json, index: number): Segment {\n if (el && typeof el === 'object' && !Array.isArray(el)) {\n const id = el['id'] ?? el['metaDataId'];\n if (typeof id === 'string' || typeof id === 'number') return `[${String(id)}]`;\n }\n return `[${index}]`;\n}\n\nexport interface Leaf {\n location: string;\n key: string;\n /** `name`s of enclosing objects (channel, connector), outermost first. */\n labels: string[];\n /** Top-level section the leaf lives in (`serverSettings`, `channels`, …). */\n section: string;\n /** The configuration-map key when this leaf is a map entry's value. */\n configMapKey?: string;\n}\n\n/** Visit every string leaf, allowing the visitor to replace it. */\nexport function mapLeaves(config: CanonicalConfig, visit: (value: string, leaf: Leaf) => string): CanonicalConfig {\n const walk = (node: Json, key: string, path: Segment[], labels: string[], section: string, cmKey?: string): Json => {\n if (typeof node === 'string') {\n return visit(node, { location: path.join('/'), key, labels, section, configMapKey: cmKey });\n }\n if (Array.isArray(node)) {\n return node.map((el, i) => walk(el, key, [...path.slice(0, -1), `${path[path.length - 1]}${elementSegment(el, i)}`], labels, section, cmKey));\n }\n if (node && typeof node === 'object') {\n const name = node['name'];\n const inner = typeof name === 'string' && name.trim() !== '' ? [...labels, name] : labels;\n // A configuration-map entry: { string: key | [key], ConfigurationProperty: { value, comment } }.\n const entryKey = node['string'];\n const mapKey =\n section === 'configurationMap' && CONFIG_PROPERTY in node\n ? typeof entryKey === 'string'\n ? entryKey\n : Array.isArray(entryKey) && typeof entryKey[0] === 'string'\n ? entryKey[0]\n : undefined\n : cmKey;\n const out: Record<string, Json> = {};\n for (const [k, v] of Object.entries(node)) {\n out[k] = walk(v, k, [...path, k], inner, section || k, mapKey);\n }\n return out;\n }\n return node;\n };\n return walk(config, '', [], [], '') as CanonicalConfig;\n}\n\n/** A field name that holds a credential (see {@link SECRET_KEY}). */\nexport function isSecretKey(key: string): boolean {\n return SECRET_KEY.test(key);\n}\n\nfunction isSecret(leaf: Leaf): boolean {\n if (leaf.section === 'configurationMap') return leaf.configMapKey !== undefined && leaf.key === 'value';\n return SECRET_KEY.test(leaf.key);\n}\n\nexport function envName(parts: string[]): string {\n return parts\n .map((p) => p.toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, ''))\n .filter(Boolean)\n .join('__')\n .replace(/^(?=[0-9])/, '_');\n}\n\nexport function derivedName(leaf: Leaf): string {\n if (leaf.configMapKey !== undefined) return envName(['CONFIG_MAP', leaf.configMapKey]);\n const context = leaf.labels.length > 0 ? leaf.labels : [leaf.section];\n return envName([...context, leaf.key]);\n}\n\n/**\n * Replace every literal credential (by field name, as `templatize` finds them)\n * with a marker, for display. `diff` uses it so a password typed into the\n * tree by hand is never printed.\n */\nexport function redactKnownSecrets(config: CanonicalConfig): CanonicalConfig {\n return mapLeaves(config, (value, leaf) => (isSecret(leaf) && value !== '' && !hasPlaceholder(value) ? '<redacted>' : value));\n}\n\n// --- templatize ------------------------------------------------------------\n\nexport interface TemplatizeResult {\n config: CanonicalConfig;\n /** Values to write to the env file (new or changed on the server). Never print these. */\n envUpdates: Record<string, string>;\n /** Human-readable notes: placeholders dropped, secrets updated from the server. */\n notes: string[];\n}\n\n/** Placeholder-bearing strings in a previously pulled (un-rendered) tree, by location. */\nfunction templatesOf(config: CanonicalConfig | null): Map<string, string> {\n const out = new Map<string, string>();\n if (config) {\n mapLeaves(config, (value, leaf) => {\n if (hasPlaceholder(value)) out.set(leaf.location, value);\n return value;\n });\n }\n return out;\n}\n\n/**\n * Read `value` as `template` with its placeholders filled in: returns each\n * placeholder's value, or null if the text around them differs. A name used\n * twice must match the same text both times.\n */\nfunction matchTemplate(template: string, value: string): Map<string, string> | null {\n const names: string[] = [];\n let pattern = '^';\n let at = 0;\n for (const m of template.matchAll(PLACEHOLDER)) {\n pattern += template.slice(at, m.index).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const seen = names.indexOf(m[1]!);\n if (seen >= 0) {\n pattern += `\\\\${seen + 1}`;\n } else {\n names.push(m[1]!);\n pattern += '([\\\\s\\\\S]*?)';\n }\n at = m.index + m[0].length;\n }\n pattern += `${template.slice(at).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}$`;\n const match = new RegExp(pattern).exec(value);\n return match ? new Map(names.map((n, i) => [n, match[i + 1]!])) : null;\n}\n\n/**\n * Replace credentials in a freshly fetched config with placeholders.\n *\n * `previous` is the existing tree (un-rendered), so placeholders the user\n * added by hand survive a re-pull as long as they still render to what the\n * server holds. `env` is what they render with.\n */\nexport function templatize(remote: CanonicalConfig, previous: CanonicalConfig | null, env: Env): TemplatizeResult {\n const templates = templatesOf(previous);\n const envUpdates: Record<string, string> = {};\n const notes: string[] = [];\n const assigned = new Map<string, string>(); // name -> value, this run\n const reserved = new Set<string>();\n for (const t of templates.values()) {\n for (const m of t.matchAll(PLACEHOLDER)) reserved.add(m[1]!);\n }\n\n /** A name no location uses yet, bound to `value`. Placeholders are never shared between locations. */\n const fresh = (base: string, value: string): string => {\n let name = base;\n for (let n = 2; assigned.has(name) || reserved.has(name); n += 1) name = `${base}_${n}`;\n assigned.set(name, value);\n if (env[name] !== value) envUpdates[name] = value;\n return name;\n };\n\n /**\n * Bind this location's placeholder values. A name another location already\n * holds with a different value (a shared placeholder whose credentials have\n * diverged) is split off under a new name, so rotating one credential never\n * changes another.\n */\n const bind = (template: string, values: Map<string, string>, rotated: boolean): string => {\n let out = template;\n for (const [name, value] of values) {\n const bound = assigned.get(name);\n if (bound !== undefined && bound !== value) {\n reserved.delete(name);\n const renamed = fresh(name, value);\n out = out.split(placeholder(name)).join(placeholder(renamed));\n notes.push(`${renamed}: split from ${name}, which another location holds with a different value`);\n continue;\n }\n assigned.set(name, value);\n if (env[name] !== value) {\n envUpdates[name] = value;\n if (rotated) notes.push(`${name}: server value differs from the env file; env file updated`);\n }\n }\n return out;\n };\n const envValues = (template: string): Map<string, string> =>\n new Map([...template.matchAll(PLACEHOLDER)].map((m) => [m[1]!, env[m[1]!]!] as const));\n\n const config = mapLeaves(remote, (value, leaf) => {\n const template = templates.get(leaf.location);\n if (template !== undefined) {\n const missing = new Set<string>();\n if (fill(template, env, missing) === value && missing.size === 0) return bind(template, envValues(template), false);\n // Same text around the placeholders, new values (a rotated secret):\n // keep the template and take the new values.\n const captured = matchTemplate(template, value);\n if (captured) return bind(template, captured, true);\n // Text edited elsewhere, secrets unchanged: put the placeholders back\n // where their values still appear. Lossless, since rendering restores\n // exactly this text.\n let restored = value;\n for (const m of template.matchAll(PLACEHOLDER)) {\n const v = env[m[1]!];\n if (v !== undefined && v.length >= 4) restored = restored.split(v).join(placeholder(m[1]!));\n }\n if (restored !== value) return bind(restored, envValues(restored), false);\n notes.push(`${leaf.location}: placeholder no longer matches the server; replaced with the server value`);\n return value;\n }\n if (isSecret(leaf) && value !== '' && !hasPlaceholder(value)) {\n return placeholder(fresh(derivedName(leaf), value));\n }\n return value;\n });\n\n return { config, envUpdates, notes };\n}\n","/**\n * Scoped push: work out which channels, code templates, libraries and global\n * scripts differ between the working tree and the server, and send only\n * those, one resource at a time. Everything else in the server configuration\n * (settings, configuration map, groups, alerts) is left alone and reported if\n * it differs.\n *\n * Both configs are in the live (Jackson JSON) shape, and the local one has its\n * `{{env:…}}` placeholders already rendered.\n */\nimport { createHash } from 'node:crypto';\n\nimport type { CanonicalConfig, Json } from '../types.js';\n\ntype Obj = Record<string, Json>;\n\nconst isObj = (v: unknown): v is Obj => typeof v === 'object' && v !== null && !Array.isArray(v);\n\n/** Jackson writes a one-element list as a bare object; normalize to an array. */\nexport function list(v: Json | undefined): Obj[] {\n if (v == null || v === '') return [];\n return (Array.isArray(v) ? v : [v]).filter(isObj);\n}\n\nexport function channelsOf(c: CanonicalConfig): Obj[] {\n return isObj(c['channels']) ? list(c['channels']['channel']) : [];\n}\n\nexport function librariesOf(c: CanonicalConfig): Obj[] {\n return isObj(c['codeTemplateLibraries']) ? list(c['codeTemplateLibraries']['codeTemplateLibrary']) : [];\n}\n\nexport function templatesOf(library: Obj): Obj[] {\n return isObj(library['codeTemplates']) ? list(library['codeTemplates']['codeTemplate']) : [];\n}\n\nconst idOf = (o: Obj): string => String(o['id']);\nconst nameOf = (o: Obj): string => String(o['name'] ?? o['id']);\nconst revisionOf = (o: Obj): number => Number(o['revision'] ?? 0);\n\n/**\n * Mirth rewrites every line ending (CRLF, and a lone CR too) as LF when it\n * saves a channel (seen on 4.5.2), so a line-ending-only difference can never\n * be pushed and would otherwise re-appear on every run.\n */\nexport function normalizeEol(s: string): string {\n return s.replace(/\\r\\n?/g, '\\n');\n}\n\n/** `normalizeEol` applied to every string in a config (for display, e.g. `diff`). */\nexport function normalizeEolDeep<T extends Json>(value: T): T {\n if (typeof value === 'string') return normalizeEol(value) as T;\n if (Array.isArray(value)) return value.map((v) => normalizeEolDeep(v)) as T;\n if (isObj(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, normalizeEolDeep(v)])) as T;\n return value;\n}\n\n/** Key-order-insensitive structural equality, ignoring line-ending style. */\nfunction same(a: Json | undefined, b: Json | undefined): boolean {\n if (a === b) return true;\n if (typeof a === 'string' && typeof b === 'string') return normalizeEol(a) === normalizeEol(b);\n if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((x, i) => same(x, b[i]));\n if (isObj(a) && isObj(b)) {\n const ka = Object.keys(a);\n return ka.length === Object.keys(b).length && ka.every((k) => k in b && same(a[k], b[k]));\n }\n return false;\n}\n\n/** Drop the fields Mirth changes on every save, so they never count as a change. */\nfunction stripVolatile(o: Obj): Obj {\n const out: Obj = { ...o };\n delete out['revision'];\n delete out['lastModified'];\n // Of exportData, compare only the channel's own metadata. Its tags and\n // dependency links are carried over from the server on push, and Mirth\n // flips them between absent and null in GET /server/configuration after\n // unrelated saves (seen on 4.5.2).\n const exportData = out['exportData'];\n if (isObj(exportData)) {\n const metadata = isObj(exportData['metadata']) ? { ...exportData['metadata'] } : undefined;\n if (metadata) {\n delete metadata['lastModified'];\n delete metadata['userId'];\n }\n out['exportData'] = metadata ? { metadata } : {};\n }\n return out;\n}\n\nconst groupsOf = (c: CanonicalConfig): Obj[] => (isObj(c['channelGroups']) ? list(c['channelGroups']['channelGroup']) : []);\n\n/**\n * `c` without the fields Mirth changes on every save (revisions, timestamps),\n * so a comparison sees content only. Mirth bumps them on a restore, and on a\n * save in the Administrator even when nothing changed.\n */\nexport function withoutVolatile(c: CanonicalConfig): CanonicalConfig {\n const out = structuredClone(c);\n const strip = (o: Obj): void => {\n delete o['revision'];\n delete o['lastModified'];\n const md = isObj(o['exportData']) ? o['exportData']['metadata'] : undefined;\n if (isObj(md)) {\n delete md['lastModified'];\n delete md['userId'];\n }\n };\n for (const ch of channelsOf(out)) strip(ch);\n for (const lib of librariesOf(out)) {\n strip(lib);\n for (const t of templatesOf(lib)) strip(t);\n }\n for (const g of groupsOf(out)) {\n strip(g);\n // A group lists its channels with their revisions too.\n for (const member of isObj(g['channels']) ? list(g['channels']['channel']) : []) delete member['revision'];\n }\n return out;\n}\n\n/** Resources the server holds at a newer revision than `tree` (a pull would update their baseline). */\nexport function newerOnServer(tree: CanonicalConfig, server: CanonicalConfig): string[] {\n const out: string[] = [];\n const compare = (kind: string, local: Obj[], remote: Obj[]) => {\n const mine = new Map(local.map((o) => [idOf(o), revisionOf(o)]));\n for (const r of remote) {\n const rev = mine.get(idOf(r));\n if (rev !== undefined && revisionOf(r) > rev) out.push(`${kind} \"${nameOf(r)}\"`);\n }\n };\n compare('channel', channelsOf(tree), channelsOf(server));\n compare('library', librariesOf(tree), librariesOf(server));\n compare('code template', librariesOf(tree).flatMap(templatesOf), librariesOf(server).flatMap(templatesOf));\n compare('channel group', groupsOf(tree), groupsOf(server));\n return out;\n}\n\n/** A library's own settings and membership, without its templates' contents. */\nfunction libraryShape(lib: Obj): Obj {\n const out = stripVolatile(lib);\n out['codeTemplates'] = templatesOf(lib).map(idOf);\n return out;\n}\n\n// --- plan -------------------------------------------------------------------\n\nexport type Op = 'create' | 'update' | 'delete';\n\nexport interface Change {\n kind: 'channel' | 'library' | 'codeTemplate' | 'globalScripts';\n op: Op;\n id: string;\n /** Display name: channel name, `library/template`, or `global scripts`. */\n label: string;\n}\n\nexport interface Plan {\n changes: Change[];\n /** Resources the server changed since the tree was pulled. */\n conflicts: string[];\n /** Server resources the tree never had (created since the last pull): left alone, not deleted. */\n serverOnly: string[];\n /** Top-level sections that differ but that scoped push does not send. */\n notPushed: string[];\n /** Channels to redeploy with --deploy: changed ones and users of changed libraries. */\n deployIds: string[];\n}\n\nexport interface Scope {\n /** Channel names or ids; undefined = all. */\n channels?: string[];\n /** Library names or ids; undefined = all. */\n libraries?: string[];\n globalScripts?: boolean;\n}\n\n/**\n * Resource ids the tree held when it was last pulled. A server resource the\n * tree lacks is a local deletion only if the tree once had it; otherwise it\n * was created on the server since the pull, and deleting it would destroy\n * someone else's work.\n */\nexport interface Known {\n /** id -> revision when last synced (null: unknown, from an older tree). */\n channels: Record<string, number | null>;\n libraries: Record<string, number | null>;\n codeTemplates: Record<string, number | null>;\n /** Hash of the global scripts when last synced; they carry no revision. */\n globalScripts?: string;\n}\n\nexport function hashGlobalScripts(c: CanonicalConfig): string {\n return createHash('sha256').update(JSON.stringify(normalizeEolDeep((c['globalScripts'] ?? null) as Json))).digest('hex');\n}\n\n/** The sync baseline for a config: every resource's revision, plus the global scripts' hash. */\nexport function resourceIds(c: CanonicalConfig): Known {\n const libs = librariesOf(c);\n const revs = (items: Obj[]) => Object.fromEntries(items.map((o) => [idOf(o), revisionOf(o)]));\n return {\n channels: revs(channelsOf(c)),\n libraries: revs(libs),\n codeTemplates: revs(libs.flatMap(templatesOf)),\n globalScripts: hashGlobalScripts(c),\n };\n}\n\n/** Accept the older id-list form of the baseline (no revisions). */\nexport function knownFrom(raw: unknown): Known | undefined {\n if (!isObj(raw as Json)) return undefined;\n const r = raw as Record<string, unknown>;\n const map = (v: unknown): Record<string, number | null> =>\n Array.isArray(v) ? Object.fromEntries(v.map((id) => [String(id), null])) : ((v ?? {}) as Record<string, number | null>);\n return {\n channels: map(r['channels']),\n libraries: map(r['libraries']),\n codeTemplates: map(r['codeTemplates']),\n globalScripts: typeof r['globalScripts'] === 'string' ? r['globalScripts'] : undefined,\n };\n}\n\n/**\n * The baseline after a push: resources the push wrote take the server's new\n * revision, created ones join, deleted ones leave; everything else keeps its\n * old baseline, so a colleague's unpulled change still reads as a conflict.\n */\nexport function knownAfterPush(known: Known, applied: Change[], touched: Set<string>, fresh: CanonicalConfig): Known {\n const now = resourceIds(fresh);\n const next: Known = {\n channels: { ...known.channels },\n libraries: { ...known.libraries },\n codeTemplates: { ...known.codeTemplates },\n globalScripts: known.globalScripts,\n };\n const key = { channel: 'channels', library: 'libraries', codeTemplate: 'codeTemplates' } as const;\n for (const c of applied) {\n if (c.kind === 'globalScripts') {\n next.globalScripts = now.globalScripts;\n } else if (c.op === 'delete') {\n delete next[key[c.kind]][c.id];\n }\n }\n for (const k of ['channels', 'libraries', 'codeTemplates'] as const) {\n for (const id of touched) if (id in now[k]) next[k][id] = now[k][id]!;\n }\n return next;\n}\n\n/** The server-configuration sections scoped push handles. */\nconst HANDLED = new Set(['channels', 'codeTemplateLibraries', 'globalScripts', 'date']);\n\nfunction selectedBy(names: string[] | undefined, what: string, local: Obj[], remote: Obj[]): (o: Obj) => boolean {\n if (names === undefined) return () => true;\n const known = [...local, ...remote];\n for (const n of names) {\n if (!known.some((o) => nameOf(o) === n || idOf(o) === n)) throw new Error(`no ${what} named \"${n}\" in the tree or on the server`);\n }\n return (o) => names.includes(nameOf(o)) || names.includes(idOf(o));\n}\n\n/**\n * With --library, the library list sent mixes the tree's in-scope libraries\n * with the server's others, so a template moved across that boundary would end\n * up in two libraries or in none. Refuse instead.\n */\nfunction assertNoMovesAcrossScope(ll: Obj[], rl: Obj[], inScope: (o: Obj) => boolean): void {\n const owner = (libs: Obj[]) => new Map(libs.flatMap((l) => templatesOf(l).map((t) => [idOf(t), l] as const)));\n const localOwner = owner(ll);\n for (const [id, r] of owner(rl)) {\n const l = localOwner.get(id);\n if (l && idOf(l) !== idOf(r) && inScope(l) !== inScope(r)) {\n throw new Error(\n `code template \"${nameOf(templatesOf(l).find((t) => idOf(t) === id)!)}\" moved from \"${nameOf(r)}\" to \"${nameOf(l)}\"; include both with --library`,\n );\n }\n }\n}\n\n/**\n * Libraries whose tree copy matched the server before a push. The library-list\n * PUT bumps every library's revision; copying the new revision into these is\n * safe, but copying it into a stale library would hide a real conflict.\n */\nexport function librariesInSync(local: CanonicalConfig, remote: CanonicalConfig): string[] {\n const rl = new Map(librariesOf(remote).map((l) => [idOf(l), l]));\n return librariesOf(local)\n .filter((l) => {\n const r = rl.get(idOf(l));\n return r !== undefined && revisionOf(r) === revisionOf(l) && same(libraryShape(l), libraryShape(r));\n })\n .map(idOf);\n}\n\n/** Channels a library's code is available to, per its include/enable/disable settings. */\nfunction channelsUsing(lib: Obj, allChannelIds: string[]): string[] {\n const ids = (v: Json | undefined): string[] =>\n isObj(v) ? (Array.isArray(v['string']) ? v['string'] : v['string'] != null ? [v['string']] : []).map(String) : [];\n if (lib['includeNewChannels'] === true) {\n const disabled = new Set(ids(lib['disabledChannelIds']));\n return allChannelIds.filter((id) => !disabled.has(id));\n }\n const enabled = new Set(ids(lib['enabledChannelIds']));\n return allChannelIds.filter((id) => enabled.has(id));\n}\n\n/** Groups of `items` sharing a key, for the keys held more than once. */\nfunction duplicates(items: Obj[], key: (o: Obj) => string): Array<[string, Obj[]]> {\n const groups = new Map<string, Obj[]>();\n for (const o of items) groups.set(key(o), [...(groups.get(key(o)) ?? []), o]);\n return [...groups].filter(([, group]) => group.length > 1);\n}\n\n/**\n * A copied channel or library directory keeps its source's id, and every save\n * addresses resources by id, so pushing it would overwrite the original.\n */\nfunction assertUniqueIds(local: CanonicalConfig): void {\n const libs = librariesOf(local);\n const problems = [\n ...duplicates(channelsOf(local), idOf).map(([id, g]) => `channels ${g.map((o) => `\"${nameOf(o)}\"`).join(', ')} share id ${id}`),\n ...duplicates(libs, idOf).map(([id, g]) => `libraries ${g.map((o) => `\"${nameOf(o)}\"`).join(', ')} share id ${id}`),\n ...duplicates(libs.flatMap(templatesOf), idOf).map(([id, g]) => `code templates ${g.map((o) => `\"${nameOf(o)}\"`).join(', ')} share id ${id}`),\n ];\n if (problems.length > 0) {\n throw new Error(`the tree holds duplicate ids (a copied directory keeps its source's id):\\n ${problems.join('\\n ')}\\ngive each copy a new id (a UUID) before pushing`);\n }\n}\n\n/**\n * `wholeReplace`: the plan is for one PUT of the whole configuration\n * (`--whole-server`, `restore`), not a sequence of per-resource saves.\n */\nexport function planPush(\n local: CanonicalConfig,\n remote: CanonicalConfig,\n scope: Scope = {},\n known?: Known,\n opts: { wholeReplace?: boolean } = {},\n): Plan {\n assertUniqueIds(local);\n const everything = scope.channels === undefined && scope.libraries === undefined && scope.globalScripts === undefined;\n const channelScope = everything || scope.channels !== undefined;\n const libraryScope = everything || scope.libraries !== undefined;\n const changes: Change[] = [];\n const conflicts: string[] = [];\n const deploy = new Set<string>();\n const serverOnly: string[] = [];\n /** A server resource missing from the tree: a planned delete, unless the tree never had it. */\n const missingLocally = (\n kind: 'channel' | 'library' | 'codeTemplate',\n r: Obj,\n label: string,\n baseline?: Record<string, number | null>,\n ): void => {\n const what = `${kind === 'codeTemplate' ? 'code template' : kind} \"${label}\"`;\n if (baseline && !(idOf(r) in baseline)) {\n serverOnly.push(what);\n return;\n }\n // Deleted locally, but edited on the server since the last pull: the\n // delete would discard someone else's work, so it is a conflict too.\n const pulled = baseline?.[idOf(r)];\n if (pulled != null && revisionOf(r) > pulled) {\n conflicts.push(`${what} changed on the server since the last pull (revision ${revisionOf(r)}, pulled ${pulled}); deleting it would discard that`);\n }\n changes.push({ kind, op: 'delete', id: idOf(r), label });\n };\n\n // Channels\n if (channelScope) {\n const lc = channelsOf(local);\n const rc = channelsOf(remote);\n const inScope = selectedBy(scope.channels, 'channel', lc, rc);\n const remoteById = new Map(rc.map((c) => [idOf(c), c]));\n const localIds = new Set(lc.map(idOf));\n for (const c of lc.filter(inScope)) {\n const r = remoteById.get(idOf(c));\n if (!r) {\n changes.push({ kind: 'channel', op: 'create', id: idOf(c), label: nameOf(c) });\n } else if (!same(stripVolatile(c), stripVolatile(r))) {\n changes.push({ kind: 'channel', op: 'update', id: idOf(c), label: nameOf(c) });\n if (revisionOf(r) > revisionOf(c)) conflicts.push(`channel \"${nameOf(c)}\" (server revision ${revisionOf(r)}, tree ${revisionOf(c)})`);\n } else {\n continue;\n }\n deploy.add(idOf(c));\n }\n for (const r of rc.filter(inScope)) {\n if (!localIds.has(idOf(r))) missingLocally('channel', r, nameOf(r), known?.channels);\n }\n }\n\n // The channels as they will be after this push: the server's, minus planned\n // deletes, with the tree's copy where the push writes one. Redeploys are\n // computed from these, so a channel created on the server since the pull,\n // or outside --channel, still gets a changed library's new code.\n const deletedChannels = new Set(changes.filter((c) => c.kind === 'channel' && c.op === 'delete').map((c) => c.id));\n const writtenChannels = new Set(changes.filter((c) => c.kind === 'channel' && c.op !== 'delete').map((c) => c.id));\n const effective = new Map<string, Obj>();\n for (const r of channelsOf(remote)) if (!deletedChannels.has(idOf(r))) effective.set(idOf(r), r);\n for (const l of channelsOf(local)) if (writtenChannels.has(idOf(l))) effective.set(idOf(l), l);\n // A saved channel may not take a name another channel holds, on the server\n // now or after the push (a tree channel beside a same-named server channel\n // with another id, as when servers were set up separately). Saves run before\n // deletes and one at a time, so a name freed by a delete or rename in the\n // same push is still taken when the save runs. Case-insensitive, to be safe.\n // A whole replace lands at once, so only the result must be free of clashes.\n // Only a save that introduces a name (a new channel or a rename) is checked:\n // two channels that already share a name on the server (Mirth allows\n // \"Lab Feed\" beside \"LAB FEED\") can still each be updated.\n const nameKey = (c: Obj) => nameOf(c).toLowerCase();\n const remoteNames = new Map(channelsOf(remote).map((c) => [idOf(c), nameKey(c)]));\n const introducesName = (c: Obj) => writtenChannels.has(idOf(c)) && remoteNames.get(idOf(c)) !== nameKey(c);\n const during = opts.wholeReplace ? [] : channelsOf(remote);\n const holders = [...new Map([...during, ...effective.values()].map((c) => [`${idOf(c)}\\n${nameKey(c)}`, c])).values()];\n const clashes = duplicates(holders, nameKey).filter(([, g]) => g.some(introducesName));\n if (clashes.length > 0) {\n throw new Error(\n `the push would save a channel under a name another channel holds:\\n ` +\n clashes.map(([, g]) => `\"${nameOf(g[0]!)}\": ids ${[...new Set(g.map(idOf))].join(', ')}`).join('\\n ') +\n `\\nrename one of them, or delete or rename the other in a push of its own first`,\n );\n }\n\n // Code templates and libraries\n if (libraryScope) {\n const ll = librariesOf(local);\n const rl = librariesOf(remote);\n const inScope = selectedBy(scope.libraries, 'library', ll, rl);\n if (scope.libraries !== undefined) assertNoMovesAcrossScope(ll, rl, inScope);\n const remoteLibById = new Map(rl.map((l) => [idOf(l), l]));\n const remoteTemplates = new Map(rl.flatMap((l) => templatesOf(l).map((t) => [idOf(t), t] as const)));\n const localTemplateIds = new Set(ll.flatMap((l) => templatesOf(l).map(idOf)));\n const allChannelIds = [...effective.keys()];\n\n for (const lib of ll.filter(inScope)) {\n const r = remoteLibById.get(idOf(lib));\n let touched = false;\n if (!r || !same(libraryShape(lib), libraryShape(r))) {\n changes.push({ kind: 'library', op: r ? 'update' : 'create', id: idOf(lib), label: nameOf(lib) });\n touched = true;\n if (r && revisionOf(r) > revisionOf(lib)) conflicts.push(`library \"${nameOf(lib)}\" (server revision ${revisionOf(r)}, tree ${revisionOf(lib)})`);\n }\n for (const t of templatesOf(lib)) {\n const rt = remoteTemplates.get(idOf(t));\n const label = `${nameOf(lib)}/${nameOf(t)}`;\n if (!rt) {\n changes.push({ kind: 'codeTemplate', op: 'create', id: idOf(t), label });\n } else if (!same(stripVolatile(t), stripVolatile(rt))) {\n changes.push({ kind: 'codeTemplate', op: 'update', id: idOf(t), label });\n if (revisionOf(rt) > revisionOf(t)) conflicts.push(`code template \"${label}\" (server revision ${revisionOf(rt)}, tree ${revisionOf(t)})`);\n } else {\n continue;\n }\n touched = true;\n }\n // Channels using it before or after the push both need a redeploy: one\n // losing access to the library must stop running its old code too.\n if (touched) {\n for (const id of channelsUsing(lib, allChannelIds)) deploy.add(id);\n if (r) for (const id of channelsUsing(r, allChannelIds)) deploy.add(id);\n }\n }\n for (const r of rl.filter(inScope)) {\n if (!ll.some((l) => idOf(l) === idOf(r))) {\n const before = changes.length;\n missingLocally('library', r, nameOf(r), known?.libraries);\n if (changes.length > before) for (const id of channelsUsing(r, allChannelIds)) deploy.add(id);\n }\n for (const t of templatesOf(r)) {\n if (!localTemplateIds.has(idOf(t))) missingLocally('codeTemplate', t, `${nameOf(r)}/${nameOf(t)}`, known?.codeTemplates);\n }\n }\n }\n\n // Global scripts\n if ((everything || scope.globalScripts === true) && !same(local['globalScripts'], remote['globalScripts'])) {\n changes.push({ kind: 'globalScripts', op: 'update', id: 'globalScripts', label: 'global scripts' });\n // No revision to compare, so compare against the hash taken at the last sync.\n if (known?.globalScripts && hashGlobalScripts(remote) !== known.globalScripts) {\n conflicts.push('global scripts changed on the server since the last pull');\n }\n }\n\n const notPushed = everything\n ? [...new Set([...Object.keys(local), ...Object.keys(remote)])]\n .filter((k) => !HANDLED.has(k) && !k.startsWith('@') && !same(local[k], remote[k]))\n .sort()\n : [];\n\n // Only enabled channels that will exist after the push can be deployed.\n const enabled = new Set(\n [...effective.values()]\n .filter((c) => {\n const md = isObj(c['exportData']) ? c['exportData']['metadata'] : undefined;\n return !(isObj(md) && md['enabled'] === false);\n })\n .map(idOf),\n );\n\n return {\n changes,\n conflicts,\n serverOnly,\n notPushed,\n deployIds: [...deploy].filter((id) => enabled.has(id)),\n };\n}\n\n/**\n * The full library list to send when the plan has library changes (Mirth only\n * replaces the whole list): the tree's version of each library in scope and the\n * server's version of the rest, so a scoped push never touches other libraries.\n */\nexport function librariesToSend(local: CanonicalConfig, remote: CanonicalConfig, scope: Scope, plan: Plan): Obj[] {\n const ll = librariesOf(local);\n const rl = librariesOf(remote);\n const inScope =\n scope.libraries === undefined ? () => true : (o: Obj) => scope.libraries!.includes(nameOf(o)) || scope.libraries!.includes(idOf(o));\n // Start from the server's list: a library leaves it only through a planned\n // (and approved) delete, so one created on the server since the pull survives.\n const deleted = new Set(plan.changes.filter((c) => c.kind === 'library' && c.op === 'delete').map((c) => c.id));\n const localById = new Map(ll.map((l) => [idOf(l), l]));\n const out: Obj[] = [];\n for (const r of rl) {\n if (deleted.has(idOf(r))) continue;\n const l = localById.get(idOf(r));\n out.push(l && inScope(l) ? l : r);\n }\n for (const l of ll) if (inScope(l) && !rl.some((r) => idOf(r) === idOf(l))) out.push(l);\n return out;\n}\n\n/**\n * Planned resources whose server copy changed between `before` (what the plan\n * was made from) and `after`. Run after the confirmation prompt: an edit made\n * in the Administrator while it was open must not be overwritten.\n */\nexport function changedSince(plan: Plan, before: CanonicalConfig, after: CanonicalConfig): string[] {\n const out: string[] = [];\n const libs = (c: CanonicalConfig) => new Map(librariesOf(c).map((l) => [idOf(l), l]));\n const [lb, la] = [libs(before), libs(after)];\n for (const c of plan.changes) {\n let a: Obj | undefined;\n let b: Obj | undefined;\n if (c.kind === 'channel') [b, a] = [findChannel(before, c.id), findChannel(after, c.id)];\n else if (c.kind === 'codeTemplate') [b, a] = [findTemplate(before, c.id), findTemplate(after, c.id)];\n else if (c.kind === 'library') [b, a] = [lb.get(c.id), la.get(c.id)];\n else if (!same(before['globalScripts'], after['globalScripts'])) out.push('global scripts');\n if (c.kind === 'globalScripts') continue;\n const existed = b !== undefined;\n const exists = a !== undefined;\n if (existed !== exists || (a && b && revisionOf(a) !== revisionOf(b))) out.push(`${c.kind} \"${c.label}\"`);\n }\n // The library-list save replaces every library, not just the planned ones:\n // any library added, removed or changed meanwhile would be reverted.\n if (plan.changes.some((c) => c.kind === 'library')) {\n const shape = (m: Map<string, Obj>) => [...m].map(([id, l]) => `${id}@${revisionOf(l)}`).sort().join(',');\n if (shape(lb) !== shape(la)) out.push('code template libraries (the library list is saved as a whole)');\n }\n return [...new Set(out)];\n}\n\n/** Two server configurations hold the same data (ignoring the export `date`, which every GET changes). */\nexport function sameServerConfig(a: CanonicalConfig, b: CanonicalConfig): boolean {\n const { date: _a, ...ra } = a;\n const { date: _b, ...rb } = b;\n return same(ra as Json, rb as Json);\n}\n\n/** Only adopt a save's revision while the server still holds the content sent. */\nexport function savedChangeMatches(change: Change, local: CanonicalConfig, remote: CanonicalConfig): boolean {\n if (change.kind === 'globalScripts') return same(local['globalScripts'], remote['globalScripts']);\n const find = (config: CanonicalConfig): Obj | undefined => change.kind === 'channel'\n ? findChannel(config, change.id)\n : change.kind === 'codeTemplate'\n ? findTemplate(config, change.id)\n : librariesOf(config).find(l => idOf(l) === change.id);\n const after = find(remote);\n if (change.op === 'delete') return after === undefined;\n const sent = find(local);\n if (!sent || !after) return false;\n const shape = change.kind === 'library' ? libraryShape : stripVolatile;\n return same(shape(sent), shape(after));\n}\n\n/** Find a code template by id in a config. */\nexport function findTemplate(c: CanonicalConfig, id: string): Obj | undefined {\n for (const lib of librariesOf(c)) for (const t of templatesOf(lib)) if (idOf(t) === id) return t;\n return undefined;\n}\n\n/** Find a channel by id in a config. */\nexport function findChannel(c: CanonicalConfig, id: string): Obj | undefined {\n return channelsOf(c).find((ch) => idOf(ch) === id);\n}\n","/**\n * Carry out a push plan against a server, and afterwards copy the server's new\n * revision numbers back into the tree so the next push compares like with like.\n */\nimport { readdir, writeFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport * as path from 'node:path';\n\nimport type { MirthClientExt } from '../client/index.js';\nimport { readJson } from '../json.js';\nimport type { CanonicalConfig, Json } from '../types.js';\nimport {\n findChannel,\n findTemplate,\n librariesInSync,\n librariesOf,\n librariesToSend,\n list,\n type Change,\n type Plan,\n type Scope,\n} from './index.js';\n\ntype Obj = Record<string, Json>;\n\nexport interface ApplyResult {\n applied: Change[];\n /** The change that failed, if any; nothing after it was attempted. */\n failed?: { change: Change; error: string };\n /** Ids whose revision the server now holds (for refreshing the tree). */\n touchedIds: Set<string>;\n}\n\n/** Order matters: templates exist before a library lists them, and leave a library before deletion. */\nconst ORDER: Array<[Change['kind'], Change['op'][]]> = [\n ['codeTemplate', ['create', 'update']],\n ['library', ['create', 'update', 'delete']],\n ['codeTemplate', ['delete']],\n ['channel', ['create', 'update']],\n ['channel', ['delete']],\n ['globalScripts', ['update']],\n];\n\nexport async function applyPlan(\n client: MirthClientExt,\n plan: Plan,\n local: CanonicalConfig,\n remote: CanonicalConfig,\n scope: Scope,\n opts: { force?: boolean } = {},\n): Promise<ApplyResult> {\n const applied: Change[] = [];\n const touchedIds = new Set<string>();\n let librariesSent = false;\n\n for (const [kind, ops] of ORDER) {\n for (const change of plan.changes.filter((c) => c.kind === kind && ops.includes(c.op))) {\n try {\n if (kind === 'library') {\n // One PUT replaces the whole list and bumps every library's revision.\n if (!librariesSent) {\n const inSync = librariesInSync(local, remote);\n await client.putCodeTemplateLibraries(librariesToSend(local, remote, scope, plan));\n librariesSent = true;\n // Take the server's new revision only where the tree now holds what\n // was sent; a stale out-of-scope library must keep its old revision\n // so the next push still sees its conflict.\n const sentFromTree = librariesOf(local).filter(\n (l) => scope.libraries === undefined || scope.libraries.includes(String(l['name'])) || scope.libraries.includes(String(l['id'])),\n );\n for (const l of sentFromTree) touchedIds.add(String(l['id']));\n for (const id of inSync) touchedIds.add(id);\n }\n } else if (kind === 'codeTemplate' && change.op === 'delete') {\n await client.deleteCodeTemplate(change.id);\n } else if (kind === 'codeTemplate') {\n await client.putCodeTemplate(findTemplate(local, change.id)!);\n } else if (kind === 'channel' && change.op === 'delete') {\n await client.deleteChannel(change.id);\n } else if (kind === 'channel') {\n await client.putChannel(\n await withServerAssociations(client, findChannel(local, change.id)!, change.op, findChannel(remote, change.id), opts.force === true),\n );\n } else {\n await client.putGlobalScripts(local['globalScripts']);\n }\n } catch (err) {\n return { applied, failed: { change, error: err instanceof Error ? err.message : String(err) }, touchedIds };\n }\n applied.push(change);\n touchedIds.add(change.id);\n }\n }\n return { applied, touchedIds };\n}\n\n/**\n * Saving a channel replaces its tag and dependency links with whatever the\n * payload carries, and the server configuration we pulled omits them, so a\n * plain PUT would silently untag the channel (seen on 4.5.2). Carry the\n * server's current links over; push only syncs the channel itself.\n */\nconst ASSOCIATIONS = ['channelTags', 'dependentIds', 'dependencyIds'];\n\nasync function withServerAssociations(\n client: MirthClientExt,\n channel: Obj,\n op: Change['op'],\n planned: Obj | undefined,\n force: boolean,\n): Promise<Obj> {\n if (op !== 'update') return channel;\n const server = await client.getChannel(String(channel['id']));\n // Last check before the save (Mirth itself does not reject a stale\n // revision): someone saved this channel after the plan was made.\n const [now, then] = [Number(server?.['revision'] ?? 0), Number(planned?.['revision'] ?? 0)];\n if (!force && now > then) {\n throw new Error(`changed on the server during the push (revision ${now}, planned against ${then}); pull and try again`);\n }\n const serverExport = server?.['exportData'] as Obj | undefined;\n if (!serverExport) return channel;\n const exportData: Obj = { ...((channel['exportData'] as Obj | undefined) ?? {}) };\n for (const key of ASSOCIATIONS) if (key in serverExport) exportData[key] = serverExport[key]!;\n return { ...channel, exportData };\n}\n\nexport async function deployChannels(\n client: MirthClientExt,\n ids: string[],\n nameOf: (id: string) => string,\n): Promise<Array<{ name: string; error: string }>> {\n const failures: Array<{ name: string; error: string }> = [];\n for (const id of ids) {\n try {\n await client.deployChannel(id);\n } catch (err) {\n failures.push({ name: nameOf(id), error: err instanceof Error ? err.message : String(err) });\n }\n }\n return failures;\n}\n\n// --- refresh revisions in the tree ------------------------------------------\n\nfunction copyVersionFields(target: Obj, source: Obj | undefined): boolean {\n if (!source) return false;\n let changed = false;\n for (const key of ['revision', 'lastModified'] as const) {\n if (key in source && JSON.stringify(target[key]) !== JSON.stringify(source[key])) {\n target[key] = source[key]!;\n changed = true;\n }\n }\n const tm = (target['exportData'] as Obj | undefined)?.['metadata'] as Obj | undefined;\n const sm = (source['exportData'] as Obj | undefined)?.['metadata'] as Obj | undefined;\n if (tm && sm && 'lastModified' in sm && JSON.stringify(tm['lastModified']) !== JSON.stringify(sm['lastModified'])) {\n tm['lastModified'] = sm['lastModified']!;\n changed = true;\n }\n return changed;\n}\n\nasync function jsonFiles(dir: string, name: string): Promise<string[]> {\n if (!existsSync(dir)) return [];\n const entries = await readdir(dir, { withFileTypes: true });\n return entries.filter((e) => e.isDirectory()).map((e) => path.join(dir, e.name, name)).filter((f) => existsSync(f));\n}\n\n/**\n * Copy `revision`/`lastModified` from `server` into the tree's JSON for the\n * given ids. Only those fields change; files are rewritten in the format the\n * explode engine uses, so nothing else shows up in git.\n */\nexport async function refreshRevisions(root: string, server: CanonicalConfig, ids: Set<string>): Promise<void> {\n for (const file of await jsonFiles(path.join(root, 'channels'), 'channel.json')) {\n const json = await readJson<Obj>(file);\n if (ids.has(String(json['id'])) && copyVersionFields(json, findChannel(server, String(json['id'])))) {\n await writeFile(file, JSON.stringify(json, null, 2));\n }\n }\n const serverLibs = new Map(librariesOf(server).map((l) => [String(l['id']), l]));\n for (const file of await jsonFiles(path.join(root, 'codeTemplates'), 'library.json')) {\n const json = await readJson<Obj>(file);\n let changed = ids.has(String(json['id'])) && copyVersionFields(json, serverLibs.get(String(json['id'])));\n const container = json['codeTemplates'] as Obj | undefined;\n for (const t of list(container?.['codeTemplate'])) {\n if (ids.has(String(t['id'])) && copyVersionFields(t, findTemplate(server, String(t['id'])))) changed = true;\n }\n if (changed) await writeFile(file, JSON.stringify(json, null, 2));\n }\n}\n\n","/**\n * `.env` file read/update. Updates rewrite only the lines they touch, so\n * comments and hand-added variables survive a pull.\n */\nimport { randomBytes } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { appendFile, chmod, copyFile, mkdir, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises';\nimport * as path from 'node:path';\n\nimport { parse } from 'dotenv';\n\n/**\n * Marks a value stored base64-encoded because no dotenv quoting can carry it\n * exactly (dotenv turns CRLF into LF, and each quote style excludes some\n * characters), e.g. a configuration-map JSON with Windows line endings.\n */\nconst BASE64_PREFIX = 'cv-base64:';\n\n/** Parse env-file text, decoding values channelvault had to store base64-encoded. */\nexport function parseEnv(text: string): Record<string, string> {\n const out = parse(text);\n for (const [k, v] of Object.entries(out)) {\n if (v.startsWith(BASE64_PREFIX)) out[k] = Buffer.from(v.slice(BASE64_PREFIX.length), 'base64').toString('utf8');\n }\n return out;\n}\n\nexport async function readEnvFile(file: string): Promise<Record<string, string>> {\n if (!existsSync(file)) return {};\n return parseEnv(await readFile(file, 'utf8'));\n}\n\n/**\n * Serialize a value so it reads back unchanged. Tries bare, single, backtick\n * and double quotes in turn and proves the choice by parsing it; falls back to\n * base64 for values none of them can carry.\n */\nexport function formatValue(value: string): string {\n const candidates = [\n /^[\\w@%+=:,./-]*$/.test(value) && !value.startsWith(BASE64_PREFIX) ? value : null,\n value.includes(\"'\") ? null : `'${value}'`,\n value.includes('`') ? null : `\\`${value}\\``,\n value.includes('\"') ? null : `\"${value.replace(/\\n/g, '\\\\n').replace(/\\r/g, '\\\\r')}\"`,\n ];\n for (const c of candidates) {\n if (c !== null && parseEnv(`K=${c}`)['K'] === value) return c;\n }\n return `${BASE64_PREFIX}${Buffer.from(value, 'utf8').toString('base64')}`;\n}\n\n/** Set `updates` in `file`, replacing existing assignments in place and appending new ones. */\nexport async function updateEnvFile(file: string, updates: Record<string, string>): Promise<void> {\n const names = Object.keys(updates);\n if (names.length === 0) return;\n const existing = existsSync(file) ? await readFile(file, 'utf8') : '';\n const lines = existing === '' ? [] : existing.replace(/\\r\\n/g, '\\n').replace(/\\n$/, '').split('\\n');\n const written = new Set<string>();\n const out: string[] = [];\n // Inside a multi-line quoted value (of any variable), lines are value text,\n // never assignments. `dropping` marks the continuation lines of a value\n // being replaced.\n let inQuote: string | null = null;\n let dropping = false;\n for (const line of lines) {\n if (inQuote !== null) {\n if (!dropping) out.push(line);\n if (line.includes(inQuote)) [inQuote, dropping] = [null, false];\n continue;\n }\n const m = /^\\s*(?:export\\s+)?([\\w.-]+)\\s*=\\s*(.*)$/.exec(line);\n const q = m?.[2]![0];\n const opens = (q === '\"' || q === \"'\" || q === '`') && m![2]!.lastIndexOf(q) === 0 ? q : null;\n if (m && Object.prototype.hasOwnProperty.call(updates, m[1]!)) {\n // Replace the first assignment and drop later duplicates: dotenv uses the\n // last one, so a stale duplicate would stay in effect.\n if (!written.has(m[1]!)) {\n out.push(`${m[1]}=${formatValue(updates[m[1]!]!)}`);\n written.add(m[1]!);\n }\n if (opens) [inQuote, dropping] = [opens, true];\n continue;\n }\n out.push(line);\n if (opens) inQuote = opens;\n }\n for (const name of names) {\n if (!written.has(name)) out.push(`${name}=${formatValue(updates[name]!)}`);\n }\n const text = `${out.join('\\n')}\\n`;\n // Prove the file says what we mean before replacing it.\n const readBack = parseEnv(text);\n const wrong = names.filter((n) => readBack[n] !== updates[n]);\n if (wrong.length > 0) throw new Error(`env file update would not read back correctly for ${wrong.join(', ')}; nothing written`);\n // Write beside it and rename over it: a crash mid-write must not truncate\n // what may be the only copy of these secrets. Through a link, replace the\n // file it points to, not the link.\n const target = existsSync(file) ? await realpath(file) : file;\n const temp = `${target}.${process.pid}-${randomBytes(4).toString('hex')}.tmp`;\n try {\n await writeFile(temp, text, { encoding: 'utf8', mode: 0o600 });\n await rename(temp, target);\n } catch (err) {\n await rm(temp, { force: true });\n throw err;\n }\n}\n\n/** How many superseded env files to keep; old secrets should not pile up on disk. */\nexport const ENV_BACKUPS_KEPT = 5;\n\n/**\n * Before `updates` overwrite a value already in `file`, copy the file to\n * `<dir>/<name>-<UTC timestamp>` (the tree's git-ignored `.secrets/`), keeping the newest\n * {@link ENV_BACKUPS_KEPT}. Adding new variables loses nothing, so it makes\n * no copy. Returns the backup path, or null if none was needed.\n */\nexport async function backupEnvFile(file: string, updates: Record<string, string>, dir: string): Promise<string | null> {\n if (!existsSync(file)) return null;\n const current = parseEnv(await readFile(file, 'utf8'));\n if (!Object.entries(updates).some(([k, v]) => current[k] !== undefined && current[k] !== v)) return null;\n\n await mkdir(dir, { recursive: true });\n const prefix = `${path.basename(file)}-`;\n // 20260924T173321.123Z: sorts chronologically; a same-millisecond collision gets -02, -03…\n const stamp = new Date().toISOString().replace(/[-:]/g, '');\n let target = path.join(dir, `${prefix}${stamp}`);\n for (let n = 2; existsSync(target); n += 1) target = path.join(dir, `${prefix}${stamp}-${String(n).padStart(2, '0')}`);\n await copyFile(file, target);\n await chmod(target, 0o600);\n\n // Prune the oldest, never the copy just made.\n const others = (await readdir(dir)).filter((f) => f.startsWith(prefix) && f !== path.basename(target)).sort();\n for (const old of others.slice(0, Math.max(0, others.length - (ENV_BACKUPS_KEPT - 1)))) {\n await rm(path.join(dir, old));\n }\n return target;\n}\n\nconst IGNORE_LINES = ['.env', '.env.*', '!.env.example', '.secrets/'];\n\n/** Make sure `dir/.gitignore` keeps env files out of git. Returns true if it changed. */\nexport async function ensureEnvIgnored(dir: string, envFile?: string): Promise<boolean> {\n const file = path.join(dir, '.gitignore');\n const text = existsSync(file) ? await readFile(file, 'utf8') : '';\n const present = new Set(text.split(/\\r?\\n/).map((l) => l.trim()));\n const wanted = [...IGNORE_LINES];\n // The chosen env file itself, when the standard patterns miss its name\n // (e.g. `--dotenv secrets.prod`).\n if (envFile) {\n const rel = path.relative(dir, envFile).split(path.sep).join('/');\n const base = path.basename(envFile);\n const covered = !rel.includes('/') && (base === '.env' || (base.startsWith('.env.') && base !== '.env.example'));\n if (!covered && !rel.startsWith('..') && !path.isAbsolute(rel)) wanted.push(`/${rel}`);\n }\n const missing = wanted.filter((l) => !present.has(l));\n if (missing.length === 0) return false;\n const prefix = text === '' || text.endsWith('\\n') ? '' : '\\n';\n await appendFile(file, `${prefix}# channelvault: secrets and per-environment values\\n${missing.join('\\n')}\\n`);\n return true;\n}\n","/**\n * Server backups: the XML document Mirth's `GET /server/configuration`\n * returns, the same one the Administrator's Backup Config saves, stored as\n * `<server>-<UTC stamp>.xml`. A backup holds every credential in plain text,\n * so files are owner-only (on POSIX; on Windows they inherit the directory's\n * permissions) and a backup directory channelvault creates ignores itself in\n * git.\n *\n * The name in the file name comes from the configuration, which moves between\n * servers (a restore or a whole-server push carries it along). So which server\n * a backup came from is recorded separately, by Mirth's per-installation\n * server ID, in the directory's manifest; choosing and rotating backups go by\n * that.\n */\nimport { randomBytes } from 'node:crypto';\nimport { existsSync, realpathSync } from 'node:fs';\nimport { mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport * as path from 'node:path';\n\nimport type { CanonicalConfig, Json } from '../types.js';\n\n/** Default backup directory, relative to the current directory. */\nexport const DEFAULT_BACKUP_DIR = '.backup';\n/** Backups kept per server unless `--keep` says otherwise. */\nexport const DEFAULT_KEEP = 10;\n\n/** `<server>-20260925T143012Z.xml`, or `-2`, `-3`… after the stamp for a second backup in one second. */\nconst FILE_NAME = /^(.+)-(\\d{8}T\\d{6}Z)(?:-(\\d+))?\\.xml$/;\n\n/** Lower-case letters, digits and single dashes: \"VNS Gov\" -> \"vns-gov\". */\nexport function serverSlug(name: string): string {\n return name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');\n}\n\n/**\n * The name a backup is filed under: the server name, else the environment\n * name (both in Server Settings), else `fallback` (host and port).\n */\nexport function backupName(config: CanonicalConfig, fallback: string): string {\n return configuredName(config) || serverSlug(fallback) || 'mirth';\n}\n\n/** The server or environment name set in Server Settings, as a slug; '' when neither is. */\nexport function configuredName(config: CanonicalConfig): string {\n const settings = config['serverSettings'];\n const field = (key: string): string => {\n const v = settings !== null && typeof settings === 'object' && !Array.isArray(settings) ? (settings as Record<string, Json>)[key] : undefined;\n return typeof v === 'string' ? serverSlug(v) : '';\n };\n return field('serverName') || field('environmentName');\n}\n\n/** `20260925T143012Z` for `date`, in UTC so it sorts and never repeats at a DST change. */\nexport function stamp(date: Date): string {\n return date.toISOString().replace(/[-:]/g, '').replace(/\\.\\d{3}Z$/, 'Z');\n}\n\nexport interface BackupFile {\n file: string;\n server: string;\n stamp: string;\n /** Same-second sequence: 1 for the first. */\n seq: number;\n}\n\n/** Backups in `dir` by file name, oldest first. Other files are ignored. */\nexport async function listBackups(dir: string): Promise<BackupFile[]> {\n if (!existsSync(dir)) return [];\n const out: BackupFile[] = [];\n for (const name of await readdir(dir)) {\n const m = FILE_NAME.exec(name);\n if (m) out.push({ file: path.join(dir, name), server: m[1]!, stamp: m[2]!, seq: m[3] ? Number(m[3]) : 1 });\n }\n return out.sort((a, b) => a.stamp.localeCompare(b.stamp) || a.seq - b.seq);\n}\n\n/** The server a backup file name says it came from, or null for a name channelvault didn't make. */\nexport function serverOfFile(file: string): string | null {\n return FILE_NAME.exec(path.basename(file))?.[1] ?? null;\n}\n\n/** Which server each backup in a directory came from. */\nexport const MANIFEST = 'channelvault-backups.json';\n\n/** Where a backup came from: Mirth's server ID (stable per installation) and, for people, its host. */\nexport interface Origin {\n serverId: string;\n host: string;\n}\n\ntype Manifest = Record<string, Origin>;\n\nasync function readManifest(dir: string): Promise<Manifest> {\n const file = path.join(dir, MANIFEST);\n if (!existsSync(file)) return {};\n try {\n const parsed = JSON.parse(await readFile(file, 'utf8')) as { files?: Manifest };\n return parsed.files ?? {};\n } catch (err) {\n // Without it no backup can be matched to a server, so none is chosen or rotated.\n throw new Error(`${file}: ${err instanceof Error ? err.message : String(err)}; restore it from a copy or delete it`);\n }\n}\n\nasync function writeManifest(dir: string, files: Manifest): Promise<void> {\n const present = Object.fromEntries(Object.entries(files).filter(([name]) => existsSync(path.join(dir, name))));\n await writePrivate(path.join(dir, MANIFEST), `${JSON.stringify({ version: 1, files: present }, null, 2)}\\n`);\n}\n\n/** The backups in `dir` taken from the server with this ID, oldest first. */\nexport async function backupsOf(dir: string, serverId: string): Promise<BackupFile[]> {\n const manifest = await readManifest(dir);\n return (await listBackups(dir)).filter((b) => manifest[path.basename(b.file)]?.serverId === serverId);\n}\n\n/** The recorded origin of `file`, when it is a backup in `dir`'s manifest; else null. */\nexport async function originOf(dir: string, file: string): Promise<Origin | null> {\n if (!existsSync(dir) || !sameFile(path.dirname(file), dir)) return null;\n return (await readManifest(dir))[path.basename(file)] ?? null;\n}\n\n/** The origins recorded in `dir`, for telling someone which servers it has backups of. */\nexport async function originsIn(dir: string): Promise<Origin[]> {\n if (!existsSync(dir)) return [];\n const seen = new Map<string, Origin>();\n for (const o of Object.values(await readManifest(dir))) seen.set(o.serverId, o);\n return [...seen.values()];\n}\n\n/**\n * Save `xml` as the newest backup of the server at `origin`, filed as\n * `<name>-<stamp>.xml` in `dir`, then keep only the newest `keep` backups of\n * that server (never removing `protect`, or any file the manifest doesn't\n * attribute to it). Returns the new file's path.\n */\nexport async function saveBackup(\n dir: string,\n name: string,\n xml: string,\n opts: { keep: number; origin: Origin; now?: Date; protect?: string },\n): Promise<string> {\n await ensureBackupDir(dir);\n const manifest = await readManifest(dir);\n const base = `${name}-${stamp(opts.now ?? new Date())}`;\n let file = path.join(dir, `${base}.xml`);\n for (let n = 2; existsSync(file); n += 1) file = path.join(dir, `${base}-${n}.xml`);\n await writePrivate(file, xml);\n manifest[path.basename(file)] = opts.origin;\n await writeManifest(dir, manifest);\n\n const mine = (await listBackups(dir)).filter((b) => manifest[path.basename(b.file)]?.serverId === opts.origin.serverId);\n for (const old of mine.slice(0, Math.max(0, mine.length - opts.keep))) {\n if (sameFile(old.file, file) || (opts.protect !== undefined && sameFile(old.file, opts.protect))) continue;\n await rm(old.file);\n }\n await writeManifest(dir, manifest);\n return file;\n}\n\n/** Two paths name the same file: links resolved, and case folded where the file system ignores it. */\nfunction sameFile(a: string, b: string): boolean {\n const real = (p: string): string => {\n const resolved = existsSync(p) ? realpathSync.native(p) : path.resolve(p);\n return process.platform === 'win32' || process.platform === 'darwin' ? resolved.toLowerCase() : resolved;\n };\n return real(a) === real(b);\n}\n\n/**\n * Create `dir` if needed. A directory channelvault creates gets a\n * `.gitignore` of `*`, so no repository it sits in can commit its backups;\n * an existing directory is left alone (it may be the user's own folder).\n */\nexport async function ensureBackupDir(dir: string): Promise<void> {\n if (existsSync(dir)) return;\n await mkdir(dir, { recursive: true });\n await writeFile(path.join(dir, '.gitignore'), '# channelvault backups hold credentials in plain text\\n*\\n');\n}\n\n/** Owner-only, written beside the target and renamed into place. */\nexport async function writePrivate(file: string, text: string): Promise<void> {\n const temp = `${file}.${process.pid}-${randomBytes(4).toString('hex')}.tmp`;\n try {\n await writeFile(temp, text, { encoding: 'utf8', mode: 0o600 });\n await rename(temp, file);\n } catch (err) {\n await rm(temp, { force: true });\n throw err;\n }\n}\n\n/** `4.5.2` (or `4.5.2-SNAPSHOT`) as [4, 5, 2]; null when it does not start with a number. */\nexport function numericVersion(v: string): number[] | null {\n const m = /^\\d+(?:\\.\\d+)*/.exec(v.trim());\n return m ? m[0].split('.').map(Number) : null;\n}\n\n/** Compare dotted versions numerically: negative when `a` is older. Both must pass {@link numericVersion}. */\nexport function compareVersions(a: string, b: string): number {\n const pa = numericVersion(a)!;\n const pb = numericVersion(b)!;\n for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {\n const d = (pa[i] ?? 0) - (pb[i] ?? 0);\n if (d !== 0) return d;\n }\n return 0;\n}\n"],"mappings":";;;AAYA,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KAAK,MAAM;AAAA,CAAI;AAChD,YAAQ,OAAO,MAAM,YAAY,KAAK,QAAQ;AAAA,CAAI;AAClD,YAAQ,OAAO,MAAM,YAAY,KAAK,iBAAiB,SAAS;AAAA,CAAI;AAAA,EACtE;AACA,UAAQ,OAAO;AAAA,IACb,2BAA2B,EAAE,QAAQ;AAAA,0BACR,EAAE,aAAa;AAAA,0BACf,EAAE,qBAAqB;AAAA,0BACvB,EAAE,aAAa;AAAA;AAAA,EAC9C;AACF,CAAC;AAED,QAAQ,WAAW,EAAE,MAAM,CAAC,QAAiB;AAE3C,MAAI,eAAe,eAAgB;AACnC,UAAQ,OAAO,MAAM,UAAU,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,CAAC;AAAA,CAAI;AAC1F,QAAM,OAAQ,KAAmC;AACjD,MAAI,OAAO,SAAS,YAAY,qBAAqB,IAAI,IAAI,GAAG;AAC9D,YAAQ,OAAO;AAAA,MACb;AAAA,IAEF;AAAA,EACF;AACA,MAAI,EAAE,eAAe,aAAa,eAAe,SAAS,QAAQ,IAAI,oBAAoB;AACxF,YAAQ,OAAO,MAAM,GAAG,MAAM,IAAI,SAAS,EAAE,CAAC;AAAA,CAAI;AAAA,EACpD;AACA,UAAQ,WAAW;AACrB,CAAC;","names":["mkdir","readdir","readFile","realpath","rename","rm","writeFile","existsSync","path","readFile","readFile","xml","out","path","xml","path","createHash","templatesOf","writeFile","existsSync","path","nameOf","existsSync","writeFile","existsSync","mkdir","readFile","readdir","realpath","writeFile","path","stamp","randomBytes","existsSync","mkdir","readdir","readFile","rename","rm","writeFile","path","existsSync","readFile","xml","rm","mkdir","writeFile","randomBytes","rename","writeJson","asArray","writeFile","existsSync","mkdir","realpath","rm","rename","nameOf","readFile","list","readdir"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/explode/index.ts","../src/types.ts","../src/json.ts","../src/xml/index.ts","../src/client/index.ts","../src/secrets/detect.ts","../src/secrets/index.ts","../src/client/validate.ts","../src/push/index.ts","../src/push/apply.ts","../src/secrets/envfile.ts","../src/backup/index.ts","../src/tree/transaction.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * channelvault CLI — git-style pull/push/diff for Mirth Connect.\n *\n * channelvault explode <backup.xml> <dir> XML -> tree\n * channelvault implode <dir> <backup.xml> tree -> XML\n * channelvault pull <dir> live server -> tree\n * channelvault push <dir> tree -> live server\n * channelvault diff <dir> tree vs live server\n * channelvault status <dir> summary of the working tree\n */\n\nimport { spawnSync } from 'node:child_process';\nimport { cp, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rm, writeFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { createRequire } from 'node:module';\nimport * as path from 'node:path';\nimport { createInterface } from 'node:readline/promises';\n\nimport { Command, CommanderError } from 'commander';\n\nimport { createExplodeEngine } from './explode/index.js';\nimport { XmlConfigAdapter } from './xml/index.js';\nimport { createMirthClient, UNTRUSTED_CERT_CODES, type MirthClientExt } from './client/index.js';\nimport {\n adoptTarget,\n changedSince,\n channelsOf,\n knownAfterPush,\n librariesOf,\n savedChangeMatches,\n knownFrom,\n newerOnServer,\n normalizeEolDeep,\n withoutVolatile,\n planPush,\n resourceIds,\n sameServerConfig,\n type Change,\n type Known,\n type Plan,\n type Scope,\n} from './push/index.js';\nimport { applyPlan, deployChannels, refreshRevisions } from './push/apply.js';\nimport { mapLeaves, redactKnownSecrets, render, templatize } from './secrets/index.js';\nimport { backupEnvFile, ensureEnvIgnored, readEnvFile, updateEnvFile } from './secrets/envfile.js';\nimport { findEchoes, formatFindings, scanSecrets, type AllowEntry } from './secrets/detect.js';\nimport { backupName, backupsOf, compareVersions, configuredName, DEFAULT_BACKUP_DIR, DEFAULT_KEEP, MANIFEST, numericVersion, originOf, originsIn, saveBackup, writePrivate } from './backup/index.js';\nimport { readJson } from './json.js';\nimport type { CanonicalConfig, ClientConfig, Json } from './types.js';\nimport { JOURNAL, lockTree, MANAGED_DIRS, recoverTree, replaceTree, STAGING_DIR } from './tree/transaction.js';\n\nconst engine = createExplodeEngine();\nconst xml = new XmlConfigAdapter();\n\n/** From package.json, one level up from both src/cli.ts and dist/cli.js. */\nconst VERSION = (createRequire(import.meta.url)('../package.json') as { version: string }).version;\n\n// --- helpers --------------------------------------------------------------\n\n/** A user-facing error: printed without a stack trace. */\nclass CliError extends Error {}\n\n/**\n * Abort the command. Throws rather than calling process.exit so open\n * connections close first; exiting while undici sockets are closing crashes\n * Node on Windows with a libuv assertion.\n */\nfunction fail(message: string): never {\n throw new CliError(message);\n}\n\n/** Exit status for an error. `diff` uses 2, because its 1 means \"differences found\". */\nlet errorExitCode = 1;\n\n/**\n * Recursive-remove options. `maxRetries` is essential on Windows, where a\n * recursive delete can transiently fail with EBUSY/ENOTEMPTY/EPERM while the OS\n * releases just-closed handles; `fs.rm` retries those specific errors.\n */\nconst RM_OPTS = { recursive: true, force: true, maxRetries: 5, retryDelay: 50 } as const;\n\ninterface ConnectionFlags {\n host?: string;\n port?: string;\n user?: string;\n pass?: string;\n insecure?: boolean;\n https?: boolean;\n}\n\n/** Resolve server connection from flags, falling back to MIRTH_* env vars. */\nfunction resolveClientConfig(flags: ConnectionFlags): ClientConfig {\n const host = flags.host ?? process.env.MIRTH_HOST;\n const portStr = flags.port ?? process.env.MIRTH_PORT;\n const username = flags.user ?? process.env.MIRTH_USER;\n const password = flags.pass ?? process.env.MIRTH_PASS;\n\n if (!host) fail('no server host (pass --host or set MIRTH_HOST)');\n if (!portStr) fail('no server port (pass --port or set MIRTH_PORT)');\n if (!username) fail('no username (pass --user or set MIRTH_USER)');\n if (password == null) fail('no password (pass --pass or set MIRTH_PASS)');\n\n const port = Number(portStr);\n if (!Number.isInteger(port)) fail(`invalid port: ${portStr}`);\n\n return {\n host,\n port,\n username,\n password,\n https: flags.https !== false,\n disableTlsCheck: flags.insecure === true,\n // Opt-in: error bodies can echo credentials (see `scrub`, applied to all output).\n includeResponseBodies: Boolean(process.env.CHANNELVAULT_DEBUG),\n };\n}\n\nfunction addConnectionFlags(cmd: Command): Command {\n return cmd\n .option('--host <host>', 'Mirth server host (env MIRTH_HOST)')\n .option('--port <port>', 'Mirth server port (env MIRTH_PORT)')\n .option('--user <user>', 'username (env MIRTH_USER)')\n .option('--pass <pass>', 'password (env MIRTH_PASS)')\n .option('--insecure', 'allow self-signed TLS certificates', false)\n .option('--no-https', 'use http instead of https');\n}\n\nasync function withClient<T>(flags: ConnectionFlags, fn: (client: MirthClientExt) => Promise<T>): Promise<T> {\n const client = createMirthClient(resolveClientConfig(flags));\n try {\n await client.login();\n return await fn(client);\n } finally {\n await client.logout().catch(() => undefined);\n await client.close().catch(() => undefined);\n }\n}\n\n// --- JSON output --------------------------------------------------------------\n\ninterface JsonFlags {\n json?: boolean;\n}\n\n/**\n * `--json`: one JSON document on stdout, for scripts and agents. Errors still\n * go to stderr with the command's exit code; notes move into the document.\n */\nfunction addJsonFlag(cmd: Command): Command {\n return cmd.option('--json', 'print the result as one JSON document on stdout', false);\n}\n\nfunction writeJson(value: unknown): void {\n process.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\n// --- backups ------------------------------------------------------------------\n\ninterface BackupFlags {\n backupDir?: string;\n keep?: string;\n /** false with --no-backup (push). */\n backup?: boolean;\n}\n\nfunction addBackupDirFlags(cmd: Command): Command {\n return cmd\n .option('--backup-dir <dir>', `where backups are kept (default ./${DEFAULT_BACKUP_DIR})`)\n .option('--keep <n>', `backups kept per server (default ${DEFAULT_KEEP})`);\n}\n\nfunction backupDirOf(flags: BackupFlags): string {\n return path.resolve(flags.backupDir ?? DEFAULT_BACKUP_DIR);\n}\n\nfunction keepOf(flags: BackupFlags): number {\n if (flags.keep === undefined) return DEFAULT_KEEP;\n const n = Number(flags.keep);\n if (!Number.isInteger(n) || n < 1) fail(`--keep must be a whole number of at least 1, not ${flags.keep}`);\n return n;\n}\n\n/** The name a server's backups are filed under; the host and port when it has no configured name. */\nfunction serverNameOf(config: CanonicalConfig, flags: ConnectionFlags): string {\n const cfg = resolveClientConfig(flags);\n return backupName(config, `${cfg.host}-${cfg.port}`);\n}\n\n/** Parse backup XML, naming the file in the error. */\nfunction parseBackup(text: string, where: string): CanonicalConfig {\n try {\n return xml.parse(text);\n } catch (err) {\n fail(`${where}: ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\n/** Save the server's configuration `text` as its newest backup and say where. */\nasync function saveServerBackup(\n client: MirthClientExt,\n text: string,\n flags: ConnectionFlags & BackupFlags,\n protect?: string,\n): Promise<string> {\n const config = parseBackup(text, 'the server configuration');\n const origin = { serverId: await client.getServerId(), host: hostOf(flags) };\n const file = await saveBackup(backupDirOf(flags), serverNameOf(config, flags), text, { keep: keepOf(flags), origin, protect });\n if (gitWouldCommit(file)) {\n process.stderr.write(`warning: git does not ignore ${file}, which holds credentials in plain text; add it to .gitignore\\n`);\n }\n return file;\n}\n\n/** Before a push changes anything: a backup to undo it with, unless --no-backup. */\nasync function backupBeforePush(client: MirthClientExt, flags: ConnectionFlags & BackupFlags & { overwriteConfigMap?: boolean; deploy?: boolean }): Promise<void> {\n if (flags.backup === false) return;\n const file = await saveServerBackup(client, await client.getServerConfigurationXml(), flags);\n process.stdout.write(`backed up the server to ${file} (undo with: ${undoCommand(file, flags)})\\n`);\n printUndoLimits(flags);\n}\n\n/** Literal arguments for the user's shell; never include a connection password. */\nfunction shellArgument(value: string): string {\n return process.platform === 'win32' ? `'${value.replace(/'/g, \"''\")}'` : `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\nfunction undoCommand(file: string, flags: ConnectionFlags & BackupFlags & { overwriteConfigMap?: boolean }): string {\n const cfg = resolveClientConfig(flags);\n const args = ['channelvault', 'restore', shellArgument(file),\n '--host', shellArgument(cfg.host), '--port', String(cfg.port), '--user', shellArgument(cfg.username),\n '--backup-dir', shellArgument(backupDirOf(flags))];\n if (cfg.https === false) args.push('--no-https');\n if (cfg.disableTlsCheck) args.push('--insecure');\n if (flags.overwriteConfigMap) args.push('--overwrite-config-map');\n return args.join(' ');\n}\n\nfunction printUndoLimits(flags: ConnectionFlags & { deploy?: boolean }): void {\n if (flags.pass !== undefined) process.stdout.write('undo authentication: supply this server\\'s password through MIRTH_PASS; it is omitted from the command\\n');\n if (flags.deploy) process.stdout.write('the undo restores saved configuration; runtime deployment state is not in the backup. Review targeted redeployment separately\\n');\n}\n\n/** `host:port`, for telling people which server a backup came from. */\nfunction hostOf(flags: ConnectionFlags): string {\n const cfg = resolveClientConfig(flags);\n return `${cfg.host}:${cfg.port}`;\n}\n\nasync function confirm(question: string): Promise<boolean> {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n const controller = new AbortController();\n rl.once('close', () => controller.abort());\n rl.once('SIGINT', () => controller.abort());\n try {\n const answer = (await rl.question(`${question} [y/N] `, { signal: controller.signal })).trim().toLowerCase();\n return answer === 'y' || answer === 'yes';\n } catch (err) {\n if (controller.signal.aborted) fail('confirmation interrupted; nothing was pushed');\n throw err;\n } finally {\n rl.close();\n }\n}\n\n/** Walk a canonical config and tally headline resource counts for `status`. */\nfunction summarize(config: CanonicalConfig): Record<string, number> {\n const asArray = (v: Json | undefined): Json[] => (Array.isArray(v) ? v : v == null ? [] : [v]);\n const channels = asArray((config.channels as Record<string, Json> | undefined)?.channel);\n const libraries = asArray(\n (config.codeTemplateLibraries as Record<string, Json> | undefined)?.codeTemplateLibrary,\n );\n const groups = asArray((config.channelGroups as Record<string, Json> | undefined)?.channelGroup);\n\n let codeTemplates = 0;\n for (const lib of libraries) {\n if (lib && typeof lib === 'object' && !Array.isArray(lib)) {\n const cts = (lib.codeTemplates as Record<string, Json> | undefined)?.codeTemplate;\n codeTemplates += asArray(cts).length;\n }\n }\n\n return {\n channels: channels.length,\n channelGroups: groups.length,\n codeTemplateLibraries: libraries.length,\n codeTemplates,\n };\n}\n\ninterface SyncMeta {\n tool: string;\n version: string;\n source: string;\n pulledAt: string;\n engineVersion: string | null;\n /** Resource ids the tree held at pull time (see Known in src/push). Absent in older trees. */\n resources?: Known;\n /** Revision histories belong to this installation, independently of its URL or name. */\n serverId?: string;\n}\n\nasync function writeMeta(root: string, source: string, config: CanonicalConfig, previous: SyncMeta | null, serverId?: string, resources = resourceIds(config)): Promise<void> {\n const meta: SyncMeta = {\n tool: 'channelvault',\n version: VERSION,\n source,\n pulledAt: new Date().toISOString(),\n // XML adapter yields `@_version`; the live JSON API yields `@version` (Jackson).\n engineVersion:\n typeof config['@_version'] === 'string'\n ? (config['@_version'] as string)\n : typeof config['@version'] === 'string'\n ? (config['@version'] as string)\n : null,\n resources,\n serverId,\n };\n // A pull that changed nothing else must not leave a timestamp-only change\n // for git to show.\n const file = path.join(root, 'channelvault.json');\n if (previous && JSON.stringify({ ...previous, pulledAt: '' }) === JSON.stringify({ ...meta, pulledAt: '' })) meta.pulledAt = previous.pulledAt;\n await writeFile(file, JSON.stringify(meta, null, 2) + '\\n', 'utf8');\n}\n\n// --- secrets / env ----------------------------------------------------------\n\ninterface EnvFlags {\n dotenv?: string;\n extractSecrets?: boolean;\n}\n\nfunction envFilePath(root: string, flags: EnvFlags): string {\n return flags.dotenv ? path.resolve(flags.dotenv) : path.join(root, '.env');\n}\n\n/** The env file overlaid with the process environment (which wins, as in CI). */\nasync function loadEnv(file: string): Promise<Record<string, string | undefined>> {\n return { ...(await readEnvFile(file)), ...process.env };\n}\n\nfunction addEnvFlag(cmd: Command): Command {\n // Not --env-file: Node scans the whole command line for that name and parses\n // the file itself (it fails on a directory and honours NODE_OPTIONS in it).\n return cmd.option('--dotenv <path>', 'env file holding secrets and per-environment values (default <dir>/.env)');\n}\n\nfunction addExtractFlag(cmd: Command): Command {\n return cmd.option('--extract-secrets', 'move secrets found inside values (URLs, scripts, headers) to the env file', false);\n}\n\n/** The tree as stored, placeholders unresolved; null if there is no tree yet. */\nasync function existingTree(root: string): Promise<CanonicalConfig | null> {\n return existsSync(path.join(root, 'server', 'configuration.json')) ? engine.implode({ root }) : null;\n}\n\n/** The tree with placeholders filled from the env file; fails listing any missing names. */\nasync function renderedTree(root: string, flags: EnvFlags): Promise<CanonicalConfig> {\n const tree = await engine.implode({ root });\n const env = await loadEnv(envFilePath(root, flags));\n rememberSecrets(tree, env);\n return render(tree, env);\n}\n\n/**\n * The values behind the tree's placeholders. A server's error can echo what\n * was sent, so everything printed about a failure goes through `scrub`.\n */\nconst knownSecrets = new Set<string>();\n\nfunction rememberSecrets(tree: CanonicalConfig, env: Record<string, string | undefined>): void {\n mapLeaves(tree, (value) => {\n for (const m of value.matchAll(/\\{\\{env:([A-Za-z_][A-Za-z0-9_]*)\\}\\}/g)) {\n const secret = env[m[1]!];\n // Shorter values (a port, \"true\") would redact ordinary words.\n if (secret !== undefined && secret.length >= 4) knownSecrets.add(secret);\n }\n return value;\n });\n}\n\n/**\n * `text` with every known secret value replaced, longest first. Error bodies\n * reach here decoded (see `readableBody`); the encoded forms cover text that\n * quotes a secret some other way.\n */\nfunction scrub(text: string): string {\n const forms = [...knownSecrets].flatMap((s) => [\n s,\n JSON.stringify(s).slice(1, -1),\n s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/'/g, '&apos;'),\n encodeURIComponent(s),\n ]);\n return [...new Set(forms)].sort((a, b) => b.length - a.length).reduce((t, s) => t.split(s).join('<redacted>'), text);\n}\n\n/**\n * Write a fetched config into the tree with credentials swapped for\n * placeholders; their values go to the env file, never to the tree.\n */\nconst ALLOW_FILE = 'channelvault.allow.json';\n\n/** Known false positives, committed with the tree: `{ \"ignore\": [{ \"location\", \"kind\", \"note\"? }] }`. */\nasync function readAllow(root: string): Promise<AllowEntry[]> {\n const file = path.join(root, ALLOW_FILE);\n if (!existsSync(file)) return [];\n const parsed = await readJson<{ ignore?: AllowEntry[] }>(file);\n return parsed.ignore ?? [];\n}\n\n/**\n * Write a fetched config into the tree with credentials swapped for\n * placeholders; their values go to the env file, never to the tree. Anything\n * that still looks like a secret stops the write unless --extract-secrets.\n */\nasync function writeTree(root: string, fetched: CanonicalConfig, source: string, flags: EnvFlags, serverId?: string): Promise<void> {\n const envFile = envFilePath(root, flags);\n const previousMeta = await preflightTree(root, envFile);\n const env = await loadEnv(envFile);\n const templated = templatize(fetched, await existingTree(root), env);\n const scan = scanSecrets(templated.config, {\n mode: flags.extractSecrets ? 'extract' : 'find',\n allow: await readAllow(root),\n env: { ...env, ...templated.envUpdates },\n });\n if (scan.findings.length > 0 && !flags.extractSecrets) {\n fail(\n `found ${scan.findings.length} possible secret(s) that would be stored in plain text; nothing was written:\\n` +\n `${formatFindings(scan.findings)}\\n` +\n `Rerun with --extract-secrets to move them to ${envFile}, or list false positives in ${ALLOW_FILE}.`,\n );\n }\n const config = scan.config;\n const envUpdates = { ...templated.envUpdates, ...scan.envUpdates };\n rememberSecrets(config, { ...env, ...envUpdates });\n // A known secret repeated somewhere no rule recognised is still in plain\n // text; say where (the env file's own values only, not all of process.env).\n const echoes = findEchoes(config, { ...(await readEnvFile(envFile)), ...envUpdates });\n\n const rel = path.relative(root, envFile);\n const envInTree = !rel.startsWith('..') && !path.isAbsolute(rel);\n let backup: string | null = null;\n await replaceTree(root, envFile, async next => {\n await engine.explode(config, { root: next });\n await writeMeta(next, source, fetched, previousMeta, serverId);\n if (Object.keys(envUpdates).length > 0) {\n const history = path.join(root, '.secrets');\n if (existsSync(history)) {\n if ((await lstat(history)).isSymbolicLink()) fail(`refusing a linked secret history directory: ${history}`);\n await cp(history, path.join(next, '.secrets'), { recursive: true });\n }\n const stagedBackup = await backupEnvFile(envFile, envUpdates, path.join(next, '.secrets'));\n if (stagedBackup) backup = path.join(root, '.secrets', path.basename(stagedBackup));\n if (backup || envInTree) {\n const ignore = path.join(root, '.gitignore');\n if (existsSync(ignore)) await writeFile(path.join(next, '.gitignore'), await readFile(ignore));\n await ensureEnvIgnored(next, envInTree ? envFile : undefined, root);\n }\n const stagedEnv = path.join(next, '.env');\n if (existsSync(envFile)) await writeFile(stagedEnv, await readFile(envFile), { mode: 0o600 });\n await updateEnvFile(stagedEnv, envUpdates);\n }\n });\n if (scan.findings.length > 0) process.stdout.write(`extracted ${scan.findings.length} secret(s) found in values\\n`);\n const updated = Object.keys(envUpdates).length;\n if (updated > 0) process.stdout.write(`stored ${updated} secret value(s) in ${envFile}\\n`);\n if (backup) process.stdout.write(`previous env file kept as ${backup}\\n`);\n for (const note of templated.notes) process.stderr.write(`note: ${note}\\n`);\n for (const e of echoes) {\n process.stderr.write(`warning: the value of ${e.name} also appears in plain text at ${e.where}\\n`);\n }\n if (existsSync(envFile) && gitWouldCommit(envFile)) {\n process.stderr.write(`warning: git does not ignore ${envFile}, so its secret values could be committed; add it to .gitignore\\n`);\n }\n}\n\n/**\n * True when `file` is inside a git work tree and not ignored there (or is\n * already tracked). Outside a repository, or without git, there is nothing to\n * commit it to.\n */\nfunction gitWouldCommit(file: string): boolean {\n const r = spawnSync('git', ['check-ignore', '-q', path.basename(file)], { cwd: path.dirname(file) });\n return r.status === 1;\n}\n\n/** `p` with links resolved as far as it exists (the rest may not be created yet). */\nasync function resolvedPath(p: string): Promise<string> {\n const abs = path.resolve(p);\n let existing = abs;\n while (!existsSync(existing) && path.dirname(existing) !== existing) existing = path.dirname(existing);\n return path.join(await realpath(existing), path.relative(existing, abs));\n}\n\n/** `child` is `parent` or inside it (case-insensitively on Windows). */\nfunction isWithin(child: string, parent: string): boolean {\n const norm = (p: string) => (process.platform === 'win32' ? p.toLowerCase() : p);\n const rel = path.relative(norm(parent), norm(child));\n // `..runtime.env` is a file name, not a step up.\n return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));\n}\n\n/**\n * Everything that can stop `pull`/`explode` must be checked before either\n * writes: they update the env file, then replace the managed directories,\n * then rewrite `channelvault.json`. Returns the existing metadata, if any.\n */\nasync function preflightTree(root: string, envFile: string): Promise<SyncMeta | null> {\n // The swap deletes these, so the env file must not live in one: neither by\n // the path given (a link inside one is removed with it) nor by where links\n // lead.\n const [realRoot, realEnv] = await Promise.all([resolvedPath(root), resolvedPath(envFile)]);\n const doomed = [...MANAGED_DIRS, STAGING_DIR, JOURNAL, 'channelvault.json', '.gitignore', '.secrets'].find(\n (d) => isWithin(path.resolve(envFile), path.resolve(root, d)) || isWithin(realEnv, path.join(realRoot, d)),\n );\n if (doomed) fail(`the env file ${envFile} is inside ${doomed}/, which this command replaces; keep it elsewhere`);\n\n const metaPath = path.join(root, 'channelvault.json');\n if (existsSync(metaPath)) {\n let meta: unknown;\n try {\n meta = await readJson(metaPath);\n } catch (err) {\n meta = err;\n }\n if (meta === null || typeof meta !== 'object' || Array.isArray(meta) || meta instanceof Error || typeof (meta as SyncMeta).source !== 'string') {\n fail(\n `${metaPath} is unreadable or not channelvault metadata${meta instanceof Error ? ` (${meta.message})` : ''}; nothing was written. ` +\n 'Restore it (for example `git checkout -- channelvault.json`) and retry.',\n );\n }\n return meta as SyncMeta;\n }\n // The managed directories must be ones channelvault wrote.\n const foreign = MANAGED_DIRS.filter((d) => existsSync(path.join(root, d)));\n if (foreign.length > 0) {\n fail(\n `${root} is not a channelvault tree (no channelvault.json) but has ${foreign.map((d) => `${d}/`).join(', ')}, ` +\n 'which this command would replace; nothing was written. Use a new or empty directory ' +\n '(or, if an earlier pull or explode into it was interrupted, delete those directories).',\n );\n }\n return null;\n}\n\nfunction assertTree(root: string): void {\n if (!existsSync(path.join(root, 'server', 'configuration.json'))) {\n fail(`${root} is not a channelvault tree (missing server/configuration.json). Run 'pull' or 'explode' first.`);\n }\n}\n\n/**\n * Which transport a working tree came from. The XML adapter and the live REST\n * API produce structurally DIFFERENT canonical configs (fast-xml-parser\n * `@_version`/`#text`/all-strings vs Jackson `@version`/native types), and the\n * normalization bridge between them is not implemented yet. So an XML-exploded\n * tree cannot be `push`ed to a live server, and a live-pulled tree cannot be\n * `implode`d to XML, without silent corruption. These helpers detect the origin\n * so those cross-path operations can be refused.\n */\ntype TreeOrigin = 'xml' | 'live' | 'unknown';\n\n/** Read the recorded origin from `channelvault.json` (`source` field). */\nasync function readTreeOrigin(root: string): Promise<TreeOrigin> {\n const metaPath = path.join(root, 'channelvault.json');\n if (!existsSync(metaPath)) return 'unknown';\n try {\n const meta = await readJson<SyncMeta>(metaPath);\n if (typeof meta.source === 'string') {\n if (meta.source.startsWith('file:')) return 'xml';\n if (/^https?:\\/\\//i.test(meta.source)) return 'live';\n }\n } catch {\n /* unreadable meta -> fall back to shape detection */\n }\n return 'unknown';\n}\n\n/** Infer origin from the config's attribute-key convention when meta is absent. */\nfunction detectConfigShape(config: CanonicalConfig): TreeOrigin {\n if ('@_version' in config) return 'xml';\n if ('@version' in config) return 'live';\n return 'unknown';\n}\n\n/**\n * Resolve a tree's transport, preferring recorded provenance and falling back\n * to the imploded config's shape. Refuses the operation when the tree's origin\n * is incompatible with `wants` (unless `force`).\n */\nasync function assertCompatibleOrigin(\n root: string,\n config: CanonicalConfig,\n wants: 'xml' | 'live',\n force: boolean,\n): Promise<void> {\n if (force) return;\n const origin = await readTreeOrigin(root);\n const effective = origin !== 'unknown' ? origin : detectConfigShape(config);\n if (effective === 'unknown' || effective === wants) return;\n\n const msg =\n wants === 'live'\n ? `this working tree was exploded from an XML backup, but 'push' sends to a live server. ` +\n `The two transports use different config shapes and the normalization bridge is not implemented yet, ` +\n `so pushing would upload a config the Mirth API cannot parse. Seed the tree with 'pull' instead, or pass --ignore-origin to override.`\n : `this working tree was pulled from a live server, but 'implode' writes a backup XML. ` +\n `The two transports use different config shapes and the normalization bridge is not implemented yet, ` +\n `so imploding would produce malformed XML. Re-create the tree with 'explode' from a backup, or pass --force to override.`;\n fail(msg);\n}\n\n/** Commander collector for a repeatable option; undefined until first used. */\nfunction collect(value: string, previous: string[] | undefined): string[] {\n return [...(previous ?? []), value];\n}\n\n// --- push ---------------------------------------------------------------------\n\nasync function bindingProblems(root: string, serverId: string): Promise<string[]> {\n const file = path.join(root, 'channelvault.json');\n const meta = existsSync(file) ? await readJson<SyncMeta>(file) : null;\n if (meta?.serverId === serverId) return [];\n return [`this tree's baseline belongs to ${meta?.serverId ? `installation ${meta.serverId}` : 'an unknown installation'}, not the target (${serverId}); pull the target and merge your edits, or review with 'adopt <dir> --plan-only' and run 'adopt <dir>' to establish its baseline; --force does not bypass installation binding`];\n}\n\nasync function assertBinding(client: MirthClientExt, root: string): Promise<void> {\n const problems = await bindingProblems(root, await client.getServerId());\n if (problems.length) fail(problems.join('\\n'));\n}\n\n/** Resource ids recorded at the last pull, if this tree has them. */\nasync function readKnown(root: string): Promise<Known | undefined> {\n const metaPath = path.join(root, 'channelvault.json');\n if (!existsSync(metaPath)) return undefined;\n return knownFrom((await readJson<SyncMeta>(metaPath)).resources);\n}\n\nasync function writeKnown(root: string, known: Known): Promise<void> {\n const metaPath = path.join(root, 'channelvault.json');\n if (!existsSync(metaPath)) return;\n const meta = await readJson<SyncMeta>(metaPath);\n if (!meta.resources) return; // an older tree: leave it to the next pull\n meta.resources = known;\n await writeFile(metaPath, JSON.stringify(meta, null, 2) + '\\n', 'utf8');\n}\n\n/**\n * A whole replace carries the server and environment name along; say so, or\n * the server silently starts calling itself by another's name.\n */\nfunction printNameChange(incoming: CanonicalConfig, current: CanonicalConfig): void {\n const [to, from] = [configuredName(incoming), configuredName(current)];\n if (to !== from) process.stdout.write(`server name changes: ${from || '(none)'} -> ${to || '(none)'}\\n`);\n}\n\nfunction printChanges(plan: Plan): void {\n const kindLabel: Record<Change['kind'], string> = { channel: 'channel', library: 'library', codeTemplate: 'code template', globalScripts: '' };\n for (const c of plan.changes) process.stdout.write(` ${c.op.padEnd(6)} ${`${kindLabel[c.kind]} ${c.label}`.trim()}\\n`);\n}\n\n/** Refuse conflicts and deletions unless the user opted in. */\nfunction planProblems(plan: Plan, flags: { allowDeletes?: boolean; force?: boolean }): string[] {\n const problems: string[] = [];\n if (plan.conflicts.length > 0 && !flags.force) {\n problems.push(\n `changed on the server since the last pull:\\n ${plan.conflicts.join('\\n ')}\\n` +\n `pull (and merge) first, or pass --force to overwrite the server's version`,\n );\n }\n const deletes = plan.changes.filter((c) => c.op === 'delete').length;\n if (deletes > 0 && !flags.allowDeletes) {\n problems.push(`the plan deletes ${deletes} resource(s) from the server; pass --allow-deletes, or narrow with --channel/--library`);\n }\n return problems;\n}\n\n/** What stops a whole-server replace: the scoped checks, plus resources the tree never had (deleted by a replace). */\nfunction wholeServerProblems(plan: Plan, flags: { allowDeletes?: boolean; force?: boolean }): string[] {\n const problems: string[] = [];\n if (plan.serverOnly.length > 0 && !flags.force) {\n problems.push('the replace would delete resources created on the server since the last pull; pull first, or pass --force (and --allow-deletes)');\n }\n const deletions = plan.changes.filter((c) => c.op === 'delete').length + plan.serverOnly.length;\n if (deletions > 0 && !flags.allowDeletes) problems.push(`the replace deletes ${deletions} resource(s) from the server; pass --allow-deletes`);\n if (plan.conflicts.length > 0 && !flags.force) problems.push(...planProblems({ ...plan, changes: [] }, flags));\n return problems;\n}\n\n/** `push --plan-only`: report the plan and what would stop it, change nothing. */\nfunction reportPlanOnly(\n flags: PushFlags,\n plan: Plan,\n problems: string[],\n extra: { target: string; mode: 'scoped' | 'whole-server' | 'adopt'; serverId?: string; redeploy?: string[]; notRedeployed?: string[] },\n): void {\n if (flags.json) {\n writeJson({\n target: extra.target,\n mode: extra.mode,\n ...(extra.serverId ? { serverId: extra.serverId } : {}),\n changes: plan.changes,\n conflicts: plan.conflicts,\n serverOnly: plan.serverOnly,\n notPushed: plan.notPushed,\n ...(extra.redeploy ? { redeploy: extra.redeploy, notRedeployed: extra.notRedeployed ?? [] } : {}),\n wouldStop: problems,\n });\n return;\n }\n for (const p of problems) process.stdout.write(`a push would stop: ${p}\\n`);\n process.stdout.write('plan only: nothing was changed\\n');\n}\n\ninterface PushFlags extends ConnectionFlags, BackupFlags, JsonFlags {\n /** --plan-only: report the plan and what would stop it; change nothing. */\n planOnly?: boolean;\n allowDeletes?: boolean;\n deploy?: boolean;\n force?: boolean;\n yes?: boolean;\n overwriteConfigMap?: boolean;\n}\n\nasync function scopedPush(\n client: MirthClientExt,\n root: string,\n local: CanonicalConfig,\n scope: Scope,\n target: string,\n flags: PushFlags,\n): Promise<void> {\n const remote = await client.getServerConfiguration();\n const known = await readKnown(root);\n const plan = planPush(local, remote, scope, known);\n const problems = [...await bindingProblems(root, await client.getServerId()), ...planProblems(plan, flags)];\n const names = new Map(\n [...channelsOf(remote), ...channelsOf(local)].map((c) => [String(c['id']), String(c['name'])] as const),\n );\n const nameOf = (id: string): string => names.get(id) ?? id;\n\n // --deploy refreshes what is running; it never starts a channel that is not\n // deployed now (an operator may have taken it down on purpose).\n const deployed = flags.deploy && plan.deployIds.length > 0 ? await client.getDeployedChannelIds() : new Set<string>();\n const toDeploy = plan.deployIds.filter((id) => deployed.has(id));\n const notDeployed = flags.deploy ? plan.deployIds.filter((id) => !deployed.has(id)) : [];\n\n if (flags.planOnly && flags.json) {\n const redeploy = flags.deploy ? { redeploy: toDeploy.map(nameOf), notRedeployed: notDeployed.map(nameOf) } : {};\n reportPlanOnly(flags, plan, problems, { target, mode: 'scoped', ...redeploy });\n return;\n }\n if (plan.changes.length === 0) {\n process.stdout.write(`nothing to push: ${target} already matches the tree\\n`);\n } else {\n process.stdout.write(`Push to ${target}:\\n`);\n printChanges(plan);\n if (toDeploy.length > 0) process.stdout.write(`then redeploy: ${toDeploy.map(nameOf).join(', ')}\\n`);\n if (notDeployed.length > 0) {\n process.stdout.write(`not redeployed (not deployed on the server now): ${notDeployed.map(nameOf).join(', ')}\\n`);\n }\n }\n if (plan.notPushed.length > 0) {\n process.stdout.write(`not pushed (differs; use --whole-server): ${plan.notPushed.join(', ')}\\n`);\n }\n if (plan.serverOnly.length > 0) {\n process.stdout.write(`left alone (created on the server since the last pull; pull to get them): ${plan.serverOnly.join(', ')}\\n`);\n }\n if (flags.planOnly) {\n reportPlanOnly(flags, plan, problems, { target, mode: 'scoped' });\n return;\n }\n if (problems.length > 0) fail(problems.join('\\n'));\n if (plan.changes.length === 0) return;\n if (!flags.yes && !(await confirm('Continue?'))) {\n process.stdout.write('aborted.\\n');\n return;\n }\n\n // The prompt may have been open for a while: re-check that nothing in the\n // plan changed on the server meanwhile. Each channel save re-checks its own\n // revision once more; the gap after that last check can't be closed from\n // here, because Mirth accepts a stale revision.\n const fresh = await client.getServerConfiguration();\n const moved = changedSince(plan, remote, fresh);\n if (moved.length > 0 && !flags.force) {\n fail(`changed on the server while this push was being confirmed:\\n ${moved.join('\\n ')}\\npull and try again, or pass --force`);\n }\n // Apply against the fresh snapshot, so whatever is sent for resources\n // outside the plan (the rest of the library list) is the server's latest.\n await backupBeforePush(client, flags);\n const afterBackup = await client.getServerConfiguration();\n const changedDuringBackup = changedSince(plan, fresh, afterBackup);\n if (!flags.force && changedDuringBackup.length) {\n fail(`changed on the server during backup: ${changedDuringBackup.join(', ')}; pull and try again`);\n }\n await assertBinding(client, root);\n const result = await applyPlan(client, plan, local, afterBackup, scope, { force: flags.force === true });\n // Record the server's new revisions even after a partial failure, so the\n // resources that did go through don't read as conflicts next time.\n try {\n const after = await client.getServerConfiguration();\n const refreshedLibraries: Change[] = librariesOf(local)\n .filter(l => result.touchedIds.has(String(l['id'])))\n .map(l => ({ kind: 'library', op: 'update', id: String(l['id']), label: String(l['name']) }));\n const membershipSent = result.sentLibraries\n ? { ...local, codeTemplateLibraries: { codeTemplateLibrary: result.sentLibraries } }\n : local;\n const changedAgain = [...result.applied, ...refreshedLibraries].filter(c => !savedChangeMatches(c, c.kind === 'library' ? membershipSent : local, after));\n if (changedAgain.length > 0) fail(`changed again after saving: ${[...new Set(changedAgain.map(c => c.label))].join(', ')}; pull and review before retrying`);\n if (result.touchedIds.size > 0) await refreshRevisions(root, after, result.touchedIds);\n if (known) await writeKnown(root, knownAfterPush(known, result.applied, result.touchedIds, after));\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (!result.failed) fail(`applied ${result.applied.length} change(s), but could not refresh the local sync baseline: ${message}; inspect the server before retrying`);\n process.stderr.write(`warning: could not refresh the local sync baseline: ${scrub(message)}\\n`);\n }\n if (result.failed) {\n const { change, error } = result.failed;\n fail(`applied ${result.applied.length} of ${plan.changes.length}; ${change.op} ${change.label} failed: ${error}`);\n }\n process.stdout.write(`pushed ${result.applied.length} change(s)\\n`);\n\n if (toDeploy.length > 0) {\n const { deployed, skipped, failures } = await deployChannels(client, toDeploy, nameOf);\n process.stdout.write(`deployed ${deployed.length} of ${toDeploy.length} channel(s)\\n`);\n if (skipped.length) process.stdout.write(`redeploy skipped (no longer deployed): ${skipped.join(', ')}\\n`);\n for (const f of failures) process.stderr.write(`deploy failed: ${f.name}: ${scrub(f.error)}\\n`);\n if (failures.length > 0) process.exitCode = 1;\n }\n}\n\n/** The full replace, gated like a scoped push: it lists and guards deletions and conflicts too. */\nasync function wholeServerPush(\n client: MirthClientExt,\n root: string,\n local: CanonicalConfig,\n target: string,\n flags: PushFlags,\n): Promise<void> {\n const remote = await client.getServerConfiguration();\n const known = await readKnown(root);\n const plan = planPush(local, remote, {}, known, { wholeReplace: true });\n const problems = [...await bindingProblems(root, await client.getServerId()), ...wholeServerProblems(plan, flags)];\n if (flags.planOnly && flags.json) {\n reportPlanOnly(flags, plan, problems, { target, mode: 'whole-server' });\n return;\n }\n const s = summarize(local);\n process.stdout.write(\n `Replace the ENTIRE server configuration at ${target} (${s.channels} channels, ${s.codeTemplates} code templates` +\n `${flags.deploy ? ', then redeploy all channels' : ''}).\\n`,\n );\n printNameChange(local, remote);\n if (plan.changes.length > 0) {\n process.stdout.write('Channel, library and template changes:\\n');\n printChanges(plan);\n }\n // A full replace also deletes what the server has and the tree never had\n // (created since the pull). That is both a deletion and someone else's\n // work: it needs --allow-deletes and --force, and the preview names it.\n for (const r of plan.serverOnly) process.stdout.write(` delete ${r} (created on the server since the last pull)\\n`);\n // Mirth keeps its own configuration map unless told to overwrite it.\n const keptMap = plan.notPushed.includes('configurationMap') && !flags.overwriteConfigMap;\n const replaced = plan.notPushed.filter((k) => !(keptMap && k === 'configurationMap'));\n if (replaced.length > 0) process.stdout.write(`also replaced: ${replaced.join(', ')}\\n`);\n if (keptMap) process.stdout.write('configuration map differs but is kept (--overwrite-config-map replaces it)\\n');\n if (flags.planOnly) {\n reportPlanOnly(flags, plan, problems, { target, mode: 'whole-server' });\n return;\n }\n if (problems.length > 0) fail(problems.join('\\n'));\n if (!flags.yes && !(await confirm('Continue?'))) {\n process.stdout.write('aborted.\\n');\n return;\n }\n // The preview was made from `remote`; anything changed since would be\n // overwritten without having been shown.\n const fresh = await client.getServerConfiguration();\n if (!sameServerConfig(remote, fresh) && !flags.force) {\n fail('the server changed while this push was being confirmed; pull and try again, or pass --force');\n }\n // Force permits concurrent edits, but never grants deletion consent.\n const freshPlan = planPush(local, fresh, {}, known, { wholeReplace: true });\n if (!flags.allowDeletes && (freshPlan.serverOnly.length > 0 || freshPlan.changes.some(c => c.op === 'delete'))) {\n fail('the replace now deletes resources from the server; review the new plan and pass --allow-deletes');\n }\n await backupBeforePush(client, flags);\n const afterBackup = await client.getServerConfiguration();\n if (!sameServerConfig(fresh, afterBackup) && !flags.force) fail('the server changed during backup; pull and try again');\n const finalPlan = planPush(local, afterBackup, {}, known, { wholeReplace: true });\n if (!flags.allowDeletes && (finalPlan.serverOnly.length || finalPlan.changes.some(c => c.op === 'delete'))) {\n fail('the replace now deletes resources from the server; review the new plan and pass --allow-deletes');\n }\n await assertBinding(client, root);\n await client.putServerConfiguration(local, {\n deploy: flags.deploy === true,\n overwriteConfigMap: flags.overwriteConfigMap === true,\n });\n const after = await client.getServerConfiguration();\n if (planPush(local, after, {}, undefined, { wholeReplace: true }).changes.length > 0) {\n fail('applied the whole-server replacement, but resources changed again after saving; pull and review before retrying');\n }\n const ids = resourceIds(local);\n await refreshRevisions(root, after, new Set([...Object.keys(ids.channels), ...Object.keys(ids.libraries), ...Object.keys(ids.codeTemplates)]));\n if (known) await writeKnown(root, resourceIds(after));\n process.stdout.write(`pushed ${root} -> ${target}\\n`);\n}\n\n// --- commands -------------------------------------------------------------\n\nconst program = new Command();\nprogram\n .name('channelvault')\n .description('Git-style pull/push/diff for Mirth Connect')\n .version(VERSION)\n // An unused argument is almost always a flag lost in transit (e.g. a script\n // runner passing a literal `--`); fail rather than silently drop it.\n // Subcommands defined below inherit this.\n .allowExcessArguments(false);\n\naddExtractFlag(addEnvFlag(\n program\n .command('explode')\n .description('Explode a Mirth backup XML into a working tree')\n .argument('<backup.xml>', 'path to a Mirth backup config XML file')\n .argument('<dir>', 'output working-tree directory'),\n)).action(async (backupPath: string, dir: string, flags: EnvFlags) => {\n const config = xml.parse(await readFile(backupPath, 'utf8'));\n const root = path.resolve(dir);\n await writeTree(root, config, `file:${path.resolve(backupPath)}`, flags);\n const s = summarize(config);\n process.stdout.write(`exploded ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}\\n`);\n});\n\naddEnvFlag(\n program\n .command('implode')\n .description('Reassemble a working tree into a Mirth backup XML')\n .argument('<dir>', 'working-tree directory')\n .argument('<backup.xml>', 'output XML path')\n .option('--force', 'implode even if the tree was pulled from a live server', false),\n).action(async (dir: string, outPath: string, flags: EnvFlags & { force?: boolean }) => {\n const root = path.resolve(dir);\n assertTree(root);\n const config = await renderedTree(root, flags);\n await assertCompatibleOrigin(root, config, 'xml', flags.force === true);\n const xmlStr = xml.build(config);\n await writeFile(outPath, xmlStr, 'utf8');\n process.stdout.write(`imploded ${root} -> ${path.resolve(outPath)}\\n`);\n });\n\naddExtractFlag(addEnvFlag(addConnectionFlags(\n program\n .command('pull')\n .description('Pull the live server configuration into a working tree')\n .argument('<dir>', 'working-tree directory'),\n))).action(async (dir: string, flags: ConnectionFlags & EnvFlags) => {\n const root = path.resolve(dir);\n await preflightTree(root, envFilePath(root, flags)); // before fetching a whole server for nothing\n const { config, serverId } = await withClient(flags, async client => {\n const serverId = await client.getServerId();\n const config = await client.getServerConfiguration();\n if (await client.getServerId() !== serverId) fail('the installation changed while pulling; nothing was written');\n return { config, serverId };\n });\n const cfg = resolveClientConfig(flags);\n await writeTree(root, config, `${cfg.https === false ? 'http' : 'https'}://${cfg.host}:${cfg.port}`, flags, serverId);\n const s = summarize(config);\n process.stdout.write(`pulled ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}\\n`);\n});\n\naddJsonFlag(addEnvFlag(addConnectionFlags(\n program.command('adopt')\n .description('Review and capture this installation as the tree baseline, preserving local content; writes no server resources')\n .argument('<dir>', 'working-tree directory')\n .option('--plan-only', 'preview the resulting push plan without changing the tree', false)\n .option('-y, --yes', 'accept the reviewed destination baseline without a prompt', false),\n))).action(async (dir: string, flags: ConnectionFlags & EnvFlags & JsonFlags & { planOnly?: boolean; yes?: boolean }) => {\n const root = path.resolve(dir);\n assertTree(root);\n const previous = await preflightTree(root, envFilePath(root, flags));\n const stored = await engine.implode({ root });\n const local = await renderedTree(root, flags);\n await assertCompatibleOrigin(root, local, 'live', false);\n if (flags.json && !flags.planOnly) fail('--json needs --plan-only');\n if (!flags.yes && !flags.planOnly && !process.stdin.isTTY) fail('no terminal to confirm on; review with `adopt --plan-only` and pass --yes');\n const cfg = resolveClientConfig(flags);\n const target = `${cfg.https === false ? 'http' : 'https'}://${cfg.host}:${cfg.port}`;\n await withClient(flags, async client => {\n const serverId = await client.getServerId();\n const remote = await client.getServerConfiguration();\n const adopted = adoptTarget(local, remote);\n const plan = planPush(adopted.config, remote, {}, adopted.known);\n if (!flags.json) {\n process.stdout.write(`Adopt ${target} (installation ${serverId}) as this tree's baseline.\\nLocal content is preserved; the following differences become reviewed edits for a subsequent push:\\n`);\n printChanges(plan);\n if (plan.serverOnly.length) process.stdout.write(`left alone: ${plan.serverOnly.join(', ')}\\n`);\n if (plan.notPushed.length) process.stdout.write(`not pushed by scoped push: ${plan.notPushed.join(', ')}\\n`);\n }\n if (flags.planOnly) {\n reportPlanOnly(flags, plan, planProblems(plan, {}), { target, mode: 'adopt', serverId });\n return;\n }\n if (!flags.yes && !(await confirm('Accept this baseline?'))) {\n process.stdout.write('aborted.\\n');\n return;\n }\n if (await client.getServerId() !== serverId || !sameServerConfig(remote, await client.getServerConfiguration())) {\n fail('the target changed while adopting; nothing was written. Review the new baseline and try again');\n }\n if (!sameServerConfig(stored, await engine.implode({ root }))) fail('the local tree changed while adopting; nothing was written');\n await replaceTree(root, envFilePath(root, flags), async next => {\n const rebased = adoptTarget(stored, remote);\n await engine.explode(rebased.config, { root: next });\n await writeMeta(next, target, rebased.config, previous, serverId, adopted.known);\n });\n process.stdout.write(`adopted installation ${serverId}; review with push --plan-only before writing the server\\n`);\n });\n});\n\naddBackupDirFlags(addEnvFlag(addConnectionFlags(\n program\n .command('push')\n .description('Push changed channels, code templates and global scripts to the live server')\n .argument('<dir>', 'working-tree directory')\n .option('--channel <name>', 'only this channel (name or id); repeatable', collect)\n .option('--library <name>', 'only this code template library (name or id); repeatable', collect)\n .option('--global-scripts', 'with --channel/--library: also push global scripts')\n .option('--allow-deletes', 'delete server resources that are missing from the tree', false)\n .option('--deploy', 'redeploy the changed channels and the channels using changed code templates', false)\n .option('--force', \"push even if the server changed since the last pull (overwrites the server's version)\", false)\n .option('--ignore-origin', 'push a tree that was exploded from an XML backup (normally refused)', false)\n .option('--whole-server', 'replace the entire server configuration instead (settings, config map, groups too)', false)\n .option('--overwrite-config-map', 'with --whole-server: also overwrite the configuration map', false)\n .option('--no-backup', 'skip the backup of the server taken before anything changes')\n .option('--plan-only', 'show what would be pushed and what would stop it; change nothing (no prompt)', false)\n .option('--json', 'with --plan-only: print the plan as one JSON document', false)\n .option('-y, --yes', 'skip the confirmation prompt', false),\n))).action(\n async (\n dir: string,\n flags: PushFlags & EnvFlags & {\n channel?: string[];\n library?: string[];\n globalScripts?: boolean;\n allowDeletes?: boolean;\n deploy?: boolean;\n wholeServer?: boolean;\n overwriteConfigMap?: boolean;\n yes?: boolean;\n force?: boolean;\n ignoreOrigin?: boolean;\n },\n ) => {\n if (flags.wholeServer && (flags.channel || flags.library || flags.globalScripts)) {\n fail('--whole-server replaces everything; it cannot be combined with --channel, --library or --global-scripts');\n }\n if (flags.overwriteConfigMap && !flags.wholeServer) fail('--overwrite-config-map needs --whole-server');\n const root = path.resolve(dir);\n assertTree(root);\n const config = await renderedTree(root, flags);\n await assertCompatibleOrigin(root, config, 'live', flags.ignoreOrigin === true);\n const cfg = resolveClientConfig(flags);\n const target = `${cfg.https === false ? 'http' : 'https'}://${cfg.host}:${cfg.port}`;\n if (flags.json && !flags.planOnly) fail('--json needs --plan-only');\n if (!flags.yes && !flags.planOnly && !process.stdin.isTTY) {\n fail('no terminal to confirm on; review with `push --plan-only` or `diff`, and pass --yes');\n }\n if (flags.wholeServer) {\n await withClient(flags, (client) => wholeServerPush(client, root, config, target, flags));\n return;\n }\n const scope: Scope = { channels: flags.channel, libraries: flags.library, globalScripts: flags.globalScripts };\n await withClient(flags, (client) => scopedPush(client, root, config, scope, target, flags));\n },\n);\n\naddBackupDirFlags(addConnectionFlags(\n program\n .command('backup')\n .description(`Save the server configuration as <server>-<UTC time>.xml in ./${DEFAULT_BACKUP_DIR} (holds credentials in plain text)`)\n .option('--out <file>', 'write to this file instead (no rotation)'),\n)).action(async (flags: ConnectionFlags & BackupFlags & { out?: string }) => {\n const cfg = resolveClientConfig(flags);\n const target = `${cfg.https === false ? 'http' : 'https'}://${cfg.host}:${cfg.port}`;\n const file = await withClient(flags, async (client) => {\n const text = await client.getServerConfigurationXml();\n if (!flags.out) return saveServerBackup(client, text, flags);\n const out = path.resolve(flags.out);\n parseBackup(text, 'the server configuration');\n if (existsSync(out)) fail(`${out} already exists; choose another name`);\n await mkdir(path.dirname(out), { recursive: true });\n await writePrivate(out, text);\n if (gitWouldCommit(out)) {\n process.stderr.write(`warning: git does not ignore ${out}, which holds credentials in plain text; add it to .gitignore\\n`);\n }\n return out;\n });\n process.stdout.write(`backed up ${target} to ${file}\\n`);\n});\n\ninterface RestoreFlags extends ConnectionFlags, BackupFlags {\n deploy?: boolean;\n overwriteConfigMap?: boolean;\n yes?: boolean;\n force?: boolean;\n}\n\naddBackupDirFlags(addConnectionFlags(\n program\n .command('restore')\n .description('Replace the entire server configuration with a backup (default: the newest backup of this server)')\n .argument('[file]', 'backup XML to restore')\n .option('--deploy', 'redeploy all channels afterwards', false)\n .option('--overwrite-config-map', 'also replace the configuration map', false)\n .option('--force', 'restore a backup taken from another server', false)\n .option('-y, --yes', 'skip the confirmation prompt', false),\n)).action(async (file: string | undefined, flags: RestoreFlags) => {\n const cfg = resolveClientConfig(flags);\n const target = `${cfg.https === false ? 'http' : 'https'}://${cfg.host}:${cfg.port}`;\n if (!flags.yes && !process.stdin.isTTY) fail('no terminal to confirm on; pass --yes');\n const dir = backupDirOf(flags);\n await withClient(flags, async (client) => {\n const currentText = await client.getServerConfigurationXml();\n const current = parseBackup(currentText, 'the server configuration');\n const serverId = await client.getServerId();\n\n // Which backup: the one named, else the newest taken from this server\n // (by server ID: the name in the file name travels with the configuration).\n let chosen: string;\n if (file) {\n chosen = path.resolve(file);\n if (!existsSync(chosen)) fail(`${chosen} does not exist`);\n } else {\n const mine = await backupsOf(dir, serverId);\n if (mine.length === 0) {\n const others = (await originsIn(dir)).map((o) => o.host);\n fail(`no backups of ${target} in ${dir}${others.length ? ` (it has backups of: ${others.join(', ')})` : ''}`);\n }\n chosen = mine[mine.length - 1]!.file;\n }\n const text = await readFile(chosen, 'utf8');\n const backup = parseBackup(text, chosen);\n\n // A backup of another server would replace this one's configuration with it.\n const origin = await originOf(dir, chosen);\n if (origin) {\n if (origin.serverId !== serverId && !flags.force) {\n fail(`${chosen} was taken from ${origin.host} (server ID ${origin.serverId}), not this server (${serverId}); pass --force to restore it here anyway`);\n }\n } else {\n // Not one of this directory's backups: only the names can be compared.\n const [fromContent, fromServer] = [configuredName(backup), configuredName(current)];\n if (fromContent !== '' && fromServer !== '' && fromContent !== fromServer && !flags.force) {\n fail(`${chosen} is a backup of ${fromContent}, not ${fromServer}; pass --force to restore it here anyway`);\n }\n process.stderr.write(`warning: ${chosen} is not in ${path.join(dir, MANIFEST)}, so which server it came from cannot be checked\\n`);\n }\n\n // Older servers cannot read a newer configuration; Mirth converts older ones.\n const [bv, sv] = [backup['@_version'], current['@_version']];\n if (typeof bv === 'string' && typeof sv === 'string' && numericVersion(bv) && numericVersion(sv)) {\n if (compareVersions(bv, sv) > 0) fail(`${chosen} is from Mirth ${bv}, newer than this server (${sv}); it cannot be restored here`);\n if (compareVersions(bv, sv) < 0) process.stderr.write(`note: ${chosen} is from Mirth ${bv}; the server (${sv}) will convert it\\n`);\n } else {\n process.stderr.write(`warning: cannot compare the backup's Mirth version (${String(bv ?? 'none')}) with the server's (${String(sv ?? 'none')})\\n`);\n }\n\n const plan = planPush(backup, current, {}, undefined, { wholeReplace: true });\n process.stdout.write(`Restore ${chosen}\\nto ${target}, replacing its ENTIRE configuration${flags.deploy ? ', then redeploy all channels' : ''}.\\n`);\n printNameChange(backup, current);\n if (plan.changes.length > 0) {\n process.stdout.write('Channel, library and template changes:\\n');\n printChanges(plan);\n }\n const keptMap = plan.notPushed.includes('configurationMap') && !flags.overwriteConfigMap;\n const replaced = plan.notPushed.filter((k) => !(keptMap && k === 'configurationMap'));\n if (replaced.length > 0) process.stdout.write(`also replaced: ${replaced.join(', ')}\\n`);\n if (keptMap) process.stdout.write('configuration map differs but is kept (--overwrite-config-map replaces it)\\n');\n if (!flags.yes && !(await confirm('Continue?'))) {\n process.stdout.write('aborted.\\n');\n return;\n }\n\n // What the preview showed must still be what gets replaced; --force does\n // not cover this (it is about which server the backup is from).\n const freshText = await client.getServerConfigurationXml();\n if (!sameServerConfig(parseBackup(freshText, 'the server configuration'), current)) {\n fail('the server changed while this restore was being confirmed; nothing was restored. Run it again to review the new state');\n }\n // The undo: the configuration about to be replaced. The backup being\n // restored is protected from rotation.\n const undo = await saveServerBackup(client, freshText, flags, chosen);\n process.stdout.write(`saved the current configuration to ${undo} (undo with: ${undoCommand(undo, flags)})\\n`);\n printUndoLimits(flags);\n\n const afterBackup = parseBackup(await client.getServerConfigurationXml(), 'the server configuration');\n if (!sameServerConfig(parseBackup(freshText, 'the server configuration'), afterBackup)) {\n fail('the server changed during the undo backup; nothing was restored. Run it again to review the new state');\n }\n\n await client.putServerConfigurationXml(text, { deploy: flags.deploy === true, overwriteConfigMap: flags.overwriteConfigMap === true });\n const after = parseBackup(await client.getServerConfigurationXml(), 'the server configuration');\n const differ = planPush(backup, after, {}, undefined, { wholeReplace: true }).changes;\n if (differ.length > 0) {\n fail(`restored, but these differ from the backup afterwards: ${differ.map((c) => c.label).join(', ')}; inspect the server`);\n }\n process.stdout.write(`restored ${chosen} to ${target}\\n`);\n });\n});\n\naddJsonFlag(addEnvFlag(addConnectionFlags(\n program\n .command('diff')\n .description('Diff a working tree against the live server configuration (exit 0 = same, 1 = differences, 2 = error)')\n .argument('<dir>', 'working-tree directory')\n // Usage errors must not read as \"differences found\" either.\n .exitOverride((err) => {\n process.exitCode = err.exitCode === 0 ? 0 : 2;\n throw err;\n }),\n))).action(async (dir: string, flags: ConnectionFlags & EnvFlags & JsonFlags) => {\n errorExitCode = 2;\n const root = path.resolve(dir);\n assertTree(root);\n\n const fetched = await withClient(flags, (client) => client.getServerConfiguration());\n const tree = await engine.implode({ root });\n // Compare like with like: the server's credentials become the placeholders\n // the tree holds. Values that differ from the env file are named, never shown.\n const { config: templatedRemote, envUpdates, notes } = templatize(fetched, tree, await loadEnv(envFilePath(root, flags)));\n const messages: string[] = [\n ...Object.keys(envUpdates).map((name) => `${name} differs between the server and the env file`),\n ...notes,\n ];\n // Redact both sides the same way, so neither can print a secret and a raw\n // secret held on both sides doesn't read as a difference.\n const allow = await readAllow(root);\n // Line endings are normalised too: push ignores them because Mirth rewrites them on save.\n // So are revisions and timestamps, which Mirth bumps on any save or restore:\n // compare content, and report newer revisions separately.\n const staleRevisions = newerOnServer(tree, templatedRemote);\n if (staleRevisions.length > 0) {\n messages.push(`${staleRevisions.length} resource(s) have a newer revision on the server; pull to update the tree's baseline`);\n }\n const treeView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withoutVolatile(tree))), { mode: 'redact', allow });\n const serverView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withoutVolatile(templatedRemote))), { mode: 'redact', allow });\n if (treeView.findings.length > 0) {\n messages.push(`the tree holds ${treeView.findings.length} unextracted secret(s), redacted below; pull --extract-secrets`);\n }\n if (serverView.findings.length > 0) messages.push(`${serverView.findings.length} possible secret(s) on the server are redacted below`);\n if (!flags.json) for (const m of messages) process.stderr.write(`note: ${m}\\n`);\n\n const tmp = await mkdtemp(path.join(tmpdir(), 'channelvault-diff-'));\n try {\n // Both sides are exploded fresh from their configs, into tmp/tree and\n // tmp/server, and compared from tmp so paths print as tree/… and server/….\n await engine.explode(treeView.config, { root: path.join(tmp, 'tree') });\n await engine.explode(serverView.config, { root: path.join(tmp, 'server') });\n await mkdir(path.join(tmp, '.empty'));\n const chunks: string[] = [];\n // Only what explode owns; per directory, because git diff --no-index takes two paths.\n for (const d of MANAGED_DIRS) {\n const local = existsSync(path.join(tmp, 'tree', d)) ? `tree/${d}` : '.empty';\n const server = existsSync(path.join(tmp, 'server', d)) ? `server/${d}` : '.empty';\n if (local === '.empty' && server === '.empty') continue;\n // Pin line-ending handling so the answer doesn't depend on the user's git\n // config, and match push, which ignores CR-only differences.\n const result = spawnSync(\n 'git',\n ['-c', 'core.autocrlf=false', 'diff', '--no-index', '--no-color', '--ignore-cr-at-eol', local, server],\n { encoding: 'utf8', cwd: tmp },\n );\n // spawnSync does NOT throw when the binary is missing or the spawn fails --\n // it returns { error, status: null }. Treating an empty stdout as \"no diff\"\n // would print a confident false-clean on the exact gate users run before a\n // destructive push, so inspect the outcome explicitly.\n // git diff --no-index exits 0 when identical, 1 when differences exist;\n // any other code (or a spawn error) is a real failure.\n if (result.error) {\n fail(`failed to run git (is it installed and on PATH?): ${result.error.message}`);\n }\n if (result.status !== 0 && result.status !== 1) {\n const stderr = (result.stderr ?? '').trim();\n fail(`git diff failed (exit ${result.status ?? 'null'})${stderr ? `: ${stderr}` : ''}`);\n }\n const chunk = (result.stdout ?? '').trim();\n if (chunk !== '') chunks.push(chunk);\n }\n const out = chunks.join('\\n');\n // A secret changed on the server is drift too, even though both sides show\n // the same placeholder; name it, never its value.\n const secretDrift = Object.keys(envUpdates);\n const clean = out === '' && secretDrift.length === 0;\n if (!clean) process.exitCode = 1;\n if (flags.json) {\n const files = await changedFiles(path.join(tmp, 'tree'), path.join(tmp, 'server'));\n writeJson({ clean, files, secretDrift, staleRevisions, notes: messages, patch: out });\n } else if (clean) {\n process.stdout.write('no differences — working tree matches the server.\\n');\n } else {\n if (out !== '') process.stdout.write(out + '\\n');\n if (secretDrift.length > 0) {\n process.stdout.write(`secret values differ between the server and the env file: ${secretDrift.join(', ')}\\n`);\n }\n }\n } finally {\n await rm(tmp, RM_OPTS);\n }\n});\n\n/**\n * Files that differ between two exploded trees, by path relative to the\n * working tree. Both sides were normalised to LF before exploding, so a byte\n * comparison agrees with the patch.\n */\nasync function changedFiles(treeDir: string, serverDir: string): Promise<Array<{ path: string; change: 'modified' | 'only-in-tree' | 'only-on-server' }>> {\n const list = async (base: string): Promise<string[]> => {\n const out: string[] = [];\n for (const d of MANAGED_DIRS) {\n if (!existsSync(path.join(base, d))) continue;\n for (const entry of await readdir(path.join(base, d), { recursive: true, withFileTypes: true })) {\n if (entry.isFile()) out.push(path.relative(base, path.join(entry.parentPath, entry.name)).split(path.sep).join('/'));\n }\n }\n return out;\n };\n const [local, remote] = await Promise.all([list(treeDir), list(serverDir)]);\n const remoteSet = new Set(remote);\n const files: Array<{ path: string; change: 'modified' | 'only-in-tree' | 'only-on-server' }> = [];\n for (const p of local) {\n if (!remoteSet.has(p)) files.push({ path: p, change: 'only-in-tree' });\n else if ((await readFile(path.join(treeDir, p), 'utf8')) !== (await readFile(path.join(serverDir, p), 'utf8'))) files.push({ path: p, change: 'modified' });\n }\n const localSet = new Set(local);\n for (const p of remote) if (!localSet.has(p)) files.push({ path: p, change: 'only-on-server' });\n return files.sort((a, b) => a.path.localeCompare(b.path));\n}\n\naddJsonFlag(addEnvFlag(\n program\n .command('status')\n .description('Summarize a working tree')\n .argument('<dir>', 'working-tree directory'),\n)).action(async (dir: string, flags: JsonFlags & EnvFlags) => {\n const root = path.resolve(dir);\n assertTree(root);\n const config = await engine.implode({ root });\n const s = summarize(config);\n const metaPath = path.join(root, 'channelvault.json');\n const meta = existsSync(metaPath) ? await readJson<SyncMeta>(metaPath) : null;\n if (flags.json) {\n writeJson({ root, source: meta?.source ?? null, pulledAt: meta?.pulledAt ?? null, engineVersion: meta?.engineVersion ?? null, counts: s });\n return;\n }\n if (meta) {\n process.stdout.write(`source: ${meta.source}\\n`);\n process.stdout.write(`pulled: ${meta.pulledAt}\\n`);\n process.stdout.write(`engine: ${meta.engineVersion ?? 'unknown'}\\n`);\n }\n process.stdout.write(\n `channels: ${s.channels}\\n` +\n `channel groups: ${s.channelGroups}\\n` +\n `code template libs: ${s.codeTemplateLibraries}\\n` +\n `code templates: ${s.codeTemplates}\\n`,\n );\n});\n\nlet unlock: (() => Promise<void>) | undefined;\nprogram.hook('preAction', async (_program, command) => {\n const name = command.name();\n if (!['explode', 'pull', 'adopt', 'push', 'implode', 'diff', 'status'].includes(name)) return;\n if (name === 'diff') errorExitCode = 2;\n const root = path.resolve(String(command.processedArgs[name === 'explode' ? 1 : 0]));\n unlock = await lockTree(root);\n await recoverTree(root, envFilePath(root, command.opts<EnvFlags>()));\n});\n\nprogram.parseAsync().catch((err: unknown) => {\n // Commander has already printed it and set the exit code.\n if (err instanceof CommanderError) return;\n process.stderr.write(`error: ${scrub(err instanceof Error ? err.message : String(err))}\\n`);\n const code = (err as { code?: unknown } | null)?.code;\n if (typeof code === 'string' && UNTRUSTED_CERT_CODES.has(code)) {\n process.stderr.write(\n \"hint: the server's TLS certificate is not trusted. For a self-signed certificate (Mirth's default), \" +\n 'pass --insecure, which turns certificate verification off.\\n',\n );\n }\n if (!(err instanceof CliError) && err instanceof Error && process.env.CHANNELVAULT_DEBUG) {\n process.stderr.write(`${scrub(err.stack ?? '')}\\n`);\n }\n process.exitCode = errorExitCode;\n}).finally(async () => {\n if (unlock) {\n try { await unlock(); }\n catch (err) {\n process.stderr.write(`error: could not release working-tree lock: ${scrub(err instanceof Error ? err.message : String(err))}\\n`);\n process.exitCode = errorExitCode;\n }\n }\n});\n","/**\n * Explode / implode engine.\n *\n * Projects a canonical config (the unwrapped Mirth `serverConfiguration`) onto a\n * git-friendly directory tree and reverses it losslessly. The exploded tree is a\n * verbatim *projection* of the config split across files using two marker types:\n *\n * - `{ \"@file\": \"<relpath>\" }` replaces an extracted code/script STRING leaf;\n * the string is written to a sidecar `.js` file (path relative to the JSON\n * file holding the marker).\n * - `{ \"@ref\": \"<relpath>\" }` replaces a whole sub-object split into its own\n * `.json` file (path relative to the JSON file holding the marker).\n *\n * Invariant: `implode(explode(config))` deep-equals `config`.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { existsSync } from 'node:fs';\nimport { lstat, mkdir, readFile, readdir, realpath, writeFile } from 'node:fs/promises';\nimport * as path from 'node:path';\n\nimport {\n CHANNEL_SCRIPT_KEYS,\n CODE_KEYS,\n isFileRef,\n type CanonicalConfig,\n type ExplodeEngine,\n type ExplodeOptions,\n type Json,\n} from '../types.js';\nimport { parseJson } from '../json.js';\n\n// --- shared helpers --------------------------------------------------------\n\n/** Coerce a \"container may be object or array depending on count\" value. */\nexport function asArray<T = Json>(x: unknown): T[] {\n return Array.isArray(x) ? (x as T[]) : x == null ? [] : [x as T];\n}\n\n/** Marker left in a `*.json` file in place of an extracted sub-object. */\ninterface RefMarker {\n '@ref': string;\n}\n\nexport function isRefMarker(v: unknown): v is RefMarker {\n return (\n typeof v === 'object' &&\n v !== null &&\n !Array.isArray(v) &&\n Object.keys(v).length === 1 &&\n typeof (v as Record<string, unknown>)['@ref'] === 'string'\n );\n}\n\nconst CODE_KEY_SET: ReadonlySet<string> = new Set([...CODE_KEYS, ...CHANNEL_SCRIPT_KEYS]);\n\n/** Map of channel-level script key -> friendly file base name. */\nconst CHANNEL_SCRIPT_FRIENDLY: Record<string, string> = {\n preprocessingScript: 'preprocessor',\n postprocessingScript: 'postprocessor',\n deployScript: 'deploy',\n undeployScript: 'undeploy',\n};\n\nfunction isPlainObject(v: unknown): v is Record<string, Json> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction deepClone<T>(v: T): T {\n return structuredClone(v);\n}\n\n/**\n * Slugify a name into a filesystem-safe segment.\n * Replaces `/ \\ : * ? \" < > |` and control chars, collapses whitespace to `-`,\n * trims leading/trailing separators. Never returns an empty string.\n */\nfunction slug(name: unknown): string {\n let s = typeof name === 'string' ? name : name == null ? '' : String(name);\n // Replace reserved / control characters with a space (later collapsed).\n s = s.replace(/[/\\\\:*?\"<>|]/g, ' ');\n // eslint-disable-next-line no-control-regex\n s = s.replace(/[\\x00-\\x1f\\x7f]/g, ' ');\n // Collapse any run of whitespace to a single dash.\n s = s.replace(/\\s+/g, '-');\n // Trim leading/trailing dashes/dots.\n s = s.replace(/^[-.]+|[-.]+$/g, '');\n if (s.length === 0) return 'unnamed';\n // Windows reserves these device names in every directory.\n return /^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i.test(s) ? `${s}-` : s;\n}\n\n/**\n * Deterministically resolve slug collisions within a namespace. Compared\n * case-insensitively: on Windows and macOS `Alpha` and `alpha` are the same\n * directory, and one would silently overwrite the other.\n */\nfunction uniqueSlug(base: string, used: Set<string>): string {\n let candidate = base;\n for (let n = 2; used.has(candidate.toLowerCase()); n += 1) candidate = `${base}-${n}`;\n used.add(candidate.toLowerCase());\n return candidate;\n}\n\n/** POSIX-style relative path for storage inside markers (stable across OS). */\nfunction relPosix(fromDir: string, toFile: string): string {\n return path.relative(fromDir, toFile).split(path.sep).join('/');\n}\n\n/** The real path of the tree being exploded, for the write check below. */\nconst explodeRoot = new AsyncLocalStorage<string>();\n\n/**\n * Refuse a write whose real directory is outside the tree: the names are\n * sanitised, but a symlink or junction already inside the tree could still\n * redirect it.\n */\nasync function assertInsideTree(filePath: string): Promise<void> {\n const root = explodeRoot.getStore();\n if (root === undefined) return;\n // Check the nearest directory that already exists, before creating any:\n // mkdir through a link would already have created directories outside.\n let dir = path.dirname(filePath);\n while (!existsSync(dir) && path.dirname(dir) !== dir) dir = path.dirname(dir);\n const real = await realpath(dir);\n if (real !== root && !real.startsWith(root + path.sep)) {\n throw new Error(`refusing to write outside the working tree: ${filePath}`);\n }\n // A safe parent does not make an existing file link safe to overwrite.\n const existing = await lstat(filePath).catch((err: NodeJS.ErrnoException) => {\n if (err.code !== 'ENOENT') throw err;\n return undefined;\n });\n if (existing?.isSymbolicLink()) throw new Error(`refusing to write through a file link: ${filePath}`);\n}\n\nasync function writeFileMkdir(filePath: string, data: string): Promise<void> {\n await assertInsideTree(filePath);\n await mkdir(path.dirname(filePath), { recursive: true });\n // NO added trailing newline — code strings must round-trip byte-identical.\n await writeFile(filePath, data);\n}\n\nasync function writeJson(filePath: string, value: Json): Promise<void> {\n await assertInsideTree(filePath);\n await mkdir(path.dirname(filePath), { recursive: true });\n await writeFile(filePath, JSON.stringify(value, null, 2));\n}\n\n// --- explode ---------------------------------------------------------------\n\n/**\n * Recursively extract code leaves from a value tree, IN PLACE (caller passes a\n * clone). `jsonDir` is the directory of the JSON file that will hold this tree;\n * `codeDir` is the directory under which sidecar `.js` files for this tree are\n * written; `prefixParts` accumulates the ancestor key/index chain for fallback\n * naming. `usedPaths` dedupes generated file paths within this resource.\n */\nasync function extractCode(\n value: Json,\n ctx: {\n jsonDir: string;\n codeDir: string;\n friendly: string | null; // friendly relative path (no extension) if known\n prefixParts: string[]; // ancestor key chain for fallback naming\n usedPaths: Set<string>;\n },\n): Promise<Json> {\n if (Array.isArray(value)) {\n const out: Json[] = [];\n for (let i = 0; i < value.length; i += 1) {\n out.push(\n await extractCode(value[i] as Json, {\n ...ctx,\n friendly: null,\n prefixParts: [...ctx.prefixParts, String(i)],\n }),\n );\n }\n return out;\n }\n\n if (!isPlainObject(value)) {\n return value;\n }\n\n // Recurse, applying friendly-path recognition for known Mirth structures.\n return extractFromObject(value, ctx);\n}\n\nasync function extractFromObject(\n obj: Record<string, Json>,\n ctx: {\n jsonDir: string;\n codeDir: string;\n friendly: string | null;\n prefixParts: string[];\n usedPaths: Set<string>;\n },\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n\n for (const [key, raw] of Object.entries(obj)) {\n // Code leaf? Only extract plain non-empty string leaves.\n if (CODE_KEY_SET.has(key) && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw; // keep empty/whitespace-only inline (no file)\n continue;\n }\n const friendlyBase =\n key in CHANNEL_SCRIPT_FRIENDLY\n ? `scripts/${CHANNEL_SCRIPT_FRIENDLY[key]}`\n : // One filename segment: config keys are untrusted and may hold '/' or '..'.\n ctx.friendly ?? `_code/${slug([...ctx.prefixParts, key].join('.'))}`;\n const filePath = resolveUnique(ctx.codeDir, `${friendlyBase}.js`, ctx.usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(ctx.jsonDir, filePath) };\n continue;\n }\n\n // Recurse into children.\n out[key] = await extractCode(raw as Json, {\n ...ctx,\n friendly: null,\n prefixParts: [...ctx.prefixParts, key],\n });\n }\n\n return out;\n}\n\n/** Resolve a unique absolute file path for a friendly-or-fallback rel path. */\nfunction resolveUnique(baseDir: string, relName: string, used: Set<string>): string {\n const ext = path.extname(relName);\n const dir = path.dirname(relName);\n const stem = path.basename(relName, ext);\n const dirSlug = dir === '.' ? '' : dir;\n // Build slugged segments for the directory portion (preserve structure).\n const segs = dirSlug.split('/').filter(Boolean);\n // Case-insensitive, like uniqueSlug.\n let rel = [...segs, `${stem}${ext}`].join('/');\n for (let n = 2; used.has(rel.toLowerCase()); n += 1) rel = [...segs, `${stem}-${n}${ext}`].join('/');\n used.add(rel.toLowerCase());\n const full = path.resolve(baseDir, ...rel.split('/'));\n if (!full.startsWith(path.resolve(baseDir) + path.sep)) throw new Error(`script path escapes its directory: ${relName}`);\n return full;\n}\n\n/**\n * Walk a channel object giving friendly paths to its scripts and connector\n * transformer/filter steps, extracting code leaves in place. Returns the\n * transformed channel object. `dir` is the channel's directory (also the dir of\n * its `channel.json`). `usedPaths` dedupes within the channel.\n */\nasync function explodeChannelTree(\n channel: Record<string, Json>,\n dir: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n\n for (const [key, raw] of Object.entries(channel)) {\n // Channel-level scripts -> scripts/<friendly>.js\n if (key in CHANNEL_SCRIPT_FRIENDLY && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw;\n continue;\n }\n const filePath = resolveUnique(dir, `scripts/${CHANNEL_SCRIPT_FRIENDLY[key]}.js`, usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(dir, filePath) };\n continue;\n }\n\n if (key === 'sourceConnector' && isPlainObject(raw)) {\n out[key] = await explodeConnector(raw, dir, 'source', 'source/receiver', usedPaths);\n continue;\n }\n\n if (key === 'destinationConnectors' && isPlainObject(raw)) {\n out[key] = await explodeDestinationConnectors(raw, dir, usedPaths);\n continue;\n }\n\n // Everything else: generic extraction (covers unknown structures / code).\n out[key] = await extractCode(raw as Json, {\n jsonDir: dir,\n codeDir: dir,\n friendly: null,\n prefixParts: [key],\n usedPaths,\n });\n }\n\n return out;\n}\n\n/**\n * Explode a connector (source or a single destination). `baseRel` is the\n * relative directory prefix within the channel dir for this connector's\n * transformer/filter steps (e.g. `source` or `destinations/<slug>`).\n * `scriptFileBase` is the friendly path (no extension) for the connector's own\n * reader/writer code at `properties.script` (e.g. `source/receiver` or\n * `destinations/<slug>/writer`).\n */\nasync function explodeConnector(\n connector: Record<string, Json>,\n channelDir: string,\n baseRel: string,\n scriptFileBase: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n\n for (const [key, raw] of Object.entries(connector)) {\n if (key === 'transformer' && isPlainObject(raw)) {\n out[key] = await explodeStepContainer(raw, channelDir, `${baseRel}/transformer`, usedPaths);\n continue;\n }\n if (key === 'responseTransformer' && isPlainObject(raw)) {\n out[key] = await explodeStepContainer(\n raw,\n channelDir,\n `${baseRel}/responseTransformer`,\n usedPaths,\n );\n continue;\n }\n if (key === 'filter' && isPlainObject(raw)) {\n out[key] = await explodeStepContainer(raw, channelDir, `${baseRel}/filter`, usedPaths);\n continue;\n }\n if (key === 'properties' && isPlainObject(raw)) {\n out[key] = await explodeConnectorProperties(raw, channelDir, scriptFileBase, usedPaths);\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: [baseRel, key],\n usedPaths,\n });\n }\n\n return out;\n}\n\n/**\n * Explode a connector's `properties` object. The JavaScript Reader/Writer\n * connectors carry their body directly at `properties.script`; extract it to a\n * friendly `<scriptFileBase>.js`. Anything else recurses generically.\n */\nasync function explodeConnectorProperties(\n properties: Record<string, Json>,\n channelDir: string,\n scriptFileBase: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n for (const [key, raw] of Object.entries(properties)) {\n if (key === 'script' && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw;\n continue;\n }\n const filePath = resolveUnique(channelDir, `${scriptFileBase}.js`, usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(channelDir, filePath) };\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: ['properties', key],\n usedPaths,\n });\n }\n return out;\n}\n\nasync function explodeDestinationConnectors(\n container: Record<string, Json>,\n channelDir: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n const usedDestSlugs = new Set<string>();\n\n for (const [key, raw] of Object.entries(container)) {\n if (key === 'connector') {\n const connectors = asArray<Record<string, Json>>(raw);\n const wasArray = Array.isArray(raw);\n const transformed: Record<string, Json>[] = [];\n for (const conn of connectors) {\n const name = isPlainObject(conn) ? conn['name'] : undefined;\n const destSlug = uniqueSlug(slug(name), usedDestSlugs);\n transformed.push(\n isPlainObject(conn)\n ? await explodeConnector(\n conn,\n channelDir,\n `destinations/${destSlug}`,\n `destinations/${destSlug}/writer`,\n usedPaths,\n )\n : conn,\n );\n }\n out[key] = wasArray ? transformed : (transformed[0] as Json);\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: ['destinationConnectors', key],\n usedPaths,\n });\n }\n\n return out;\n}\n\n/**\n * Explode a transformer/filter/responseTransformer container. Mirth nests the\n * actual steps under an `elements` key. In REAL data `elements` is an OBJECT\n * keyed by the step's fully-qualified Java class name (e.g.\n * `com.mirth.connect.plugins.javascriptstep.JavaScriptStep`), whose value is an\n * array of step objects:\n *\n * elements: { \"com.mirth...JavaScriptStep\": [ { name, sequenceNumber, script } ] }\n *\n * An empty transformer/filter serializes `elements` as the empty string `\"\"`.\n * We give each step a friendly `<baseRel>/<n>.<slug(step name)>.js` path, where\n * `n` is `sequenceNumber + 1` (string-parsed) falling back to a running index.\n * Unknown shapes fall back to generic extraction so we never crash.\n */\nasync function explodeStepContainer(\n container: Record<string, Json>,\n channelDir: string,\n baseRel: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n\n for (const [key, raw] of Object.entries(container)) {\n if (key === 'elements' && (Array.isArray(raw) || isPlainObject(raw))) {\n out[key] = await explodeElementsContainer(\n raw as Json[] | Record<string, Json>,\n channelDir,\n baseRel,\n usedPaths,\n );\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: [baseRel, key],\n usedPaths,\n });\n }\n\n return out;\n}\n\n/** Does an object look like a single step (carries a code leaf or step metadata)? */\nfunction isStepLike(obj: Record<string, Json>): boolean {\n return (\n typeof obj['script'] === 'string' ||\n typeof obj['code'] === 'string' ||\n 'sequenceNumber' in obj ||\n 'name' in obj\n );\n}\n\n/**\n * Dispatch the `elements` value of a step container, numbering steps globally\n * in encounter order. Handles three shapes:\n * - ARRAY of step objects (a legacy / hand-written form).\n * - a single step OBJECT (`elements` collapsed to one step).\n * - the REAL Mirth form: an OBJECT keyed by fully-qualified class name whose\n * values are arrays (or single objects) of step objects.\n */\nasync function explodeElementsContainer(\n elements: Json[] | Record<string, Json>,\n channelDir: string,\n baseRel: string,\n usedPaths: Set<string>,\n): Promise<Json> {\n const counter = { i: 0 };\n\n if (Array.isArray(elements)) {\n return explodeStepArray(elements, channelDir, baseRel, usedPaths, counter);\n }\n\n // A single step object directly under `elements`.\n if (isStepLike(elements)) {\n return explodeStep(elements, channelDir, baseRel, counter.i++, usedPaths);\n }\n\n // Class-keyed map of step buckets (the real shape).\n const out: Record<string, Json> = {};\n for (const [className, raw] of Object.entries(elements)) {\n // Attributes (`@_...`), adapter metadata (`#order`, `#comment`) and nulls\n // are passed through generically, not numbered as steps.\n if (className.startsWith('@_') || className.startsWith('#') || raw == null) {\n out[className] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: [baseRel, 'elements', className],\n usedPaths,\n });\n continue;\n }\n if (Array.isArray(raw)) {\n out[className] = await explodeStepArray(raw, channelDir, baseRel, usedPaths, counter);\n continue;\n }\n if (isPlainObject(raw) && isStepLike(raw)) {\n out[className] = await explodeStep(raw, channelDir, baseRel, counter.i++, usedPaths);\n continue;\n }\n out[className] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: [baseRel, 'elements', className],\n usedPaths,\n });\n }\n return out;\n}\n\nasync function explodeStepArray(\n steps: Json[],\n channelDir: string,\n baseRel: string,\n usedPaths: Set<string>,\n counter: { i: number },\n): Promise<Json[]> {\n const transformed: Json[] = [];\n for (const step of steps) {\n transformed.push(await explodeStep(step, channelDir, baseRel, counter.i++, usedPaths));\n }\n return transformed;\n}\n\nasync function explodeStep(\n step: Json,\n channelDir: string,\n baseRel: string,\n index: number,\n usedPaths: Set<string>,\n): Promise<Json> {\n if (!isPlainObject(step)) {\n return step;\n }\n\n // Sequence number (Mirth) is 0-based; prefer it, else fall back to index.\n const seqRaw = step['sequenceNumber'];\n let seq = index;\n if (typeof seqRaw === 'number') seq = seqRaw;\n else if (typeof seqRaw === 'string' && seqRaw.trim() !== '' && !Number.isNaN(Number(seqRaw))) {\n seq = Number(seqRaw);\n }\n const n = seq + 1;\n const stepName = step['name'];\n // Many real steps have no `name`; fall back to a bare `<n>` segment so the\n // file reads as e.g. `1.js` rather than `1.unnamed.js`.\n const hasName = typeof stepName === 'string' && stepName.trim().length > 0;\n const friendlyBase = hasName ? `${baseRel}/${n}.${slug(stepName)}` : `${baseRel}/${n}`;\n\n const out: Record<string, Json> = {};\n for (const [key, raw] of Object.entries(step)) {\n if (CODE_KEY_SET.has(key) && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw;\n continue;\n }\n const filePath = resolveUnique(channelDir, `${friendlyBase}.js`, usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(channelDir, filePath) };\n continue;\n }\n // Recurse generically into anything else (handles nested unknowns).\n out[key] = await extractCode(raw as Json, {\n jsonDir: channelDir,\n codeDir: channelDir,\n friendly: null,\n prefixParts: [baseRel, String(index), key],\n usedPaths,\n });\n }\n return out;\n}\n\n/**\n * Split the three known top-level collections into per-resource JSON files,\n * replacing each element with an `@ref` marker (order preserved). Each split-out\n * resource is itself code-extracted under its own directory.\n *\n * Returns the rewritten container value (object or array preserved as-is) with\n * `@ref` markers, or null if the collection was absent.\n */\nasync function splitCollection(\n parent: Record<string, Json>,\n containerKey: string, // e.g. 'channels'\n elementKey: string, // e.g. 'channel'\n root: string,\n serverDir: string, // dir holding configuration.json (markers are relative to it)\n targetFor: (name: unknown, slugName: string) => { jsonFile: string; resourceDir: string },\n usedSlugs: Set<string>,\n explodeResource: (\n el: Record<string, Json>,\n resourceDir: string,\n ) => Promise<Record<string, Json>>,\n): Promise<void> {\n const container = parent[containerKey];\n if (!isPlainObject(container)) return;\n const raw = container[elementKey];\n if (raw == null) return;\n\n const wasArray = Array.isArray(raw);\n const elements = asArray<Json>(raw);\n const refs: Json[] = [];\n\n // Suffixes for colliding names (\"Lab Feed\", \"LAB FEED\") are handed out by\n // name then id, not list order: the server's order can change (a restore\n // reorders it), which would move a resource to another directory.\n const byName = (el: Record<string, Json>) => `${slug(el['name']).toLowerCase()}\\u0000${String(el['id'] ?? '')}`;\n const slugs = new Map<Json, string>();\n for (const el of elements.filter(isPlainObject).sort((a, b) => (byName(a) < byName(b) ? -1 : byName(a) > byName(b) ? 1 : 0))) {\n slugs.set(el, uniqueSlug(slug(el['name']), usedSlugs));\n }\n\n for (const el of elements) {\n if (!isPlainObject(el)) {\n // Non-object element: keep inline (cannot meaningfully split).\n refs.push(el);\n continue;\n }\n const slugName = slugs.get(el)!;\n const { jsonFile, resourceDir } = targetFor(el['name'], slugName);\n const transformed = await explodeResource(el, resourceDir);\n await writeJson(jsonFile, transformed);\n refs.push({ '@ref': relPosix(serverDir, jsonFile) });\n }\n\n // Preserve object-vs-array shape of the element container.\n container[elementKey] = wasArray ? refs : (refs[0] as Json);\n}\n\nasync function explode(config: CanonicalConfig, opts: ExplodeOptions): Promise<void> {\n await mkdir(opts.root, { recursive: true });\n await explodeRoot.run(await realpath(opts.root), () => explodeInto(config, opts));\n}\n\nasync function explodeInto(config: CanonicalConfig, opts: ExplodeOptions): Promise<void> {\n const root = opts.root;\n const serverDir = path.join(root, 'server');\n const skeleton = deepClone(config) as Record<string, Json>;\n\n // 1. channels.channel[] -> channels/<slug>/channel.json\n if (isPlainObject(skeleton['channels'])) {\n const channelSlugs = new Set<string>();\n await splitCollection(\n skeleton,\n 'channels',\n 'channel',\n root,\n serverDir,\n (_name, slugName) => {\n const resourceDir = path.join(root, 'channels', slugName);\n return { jsonFile: path.join(resourceDir, 'channel.json'), resourceDir };\n },\n channelSlugs,\n async (el, resourceDir) => explodeChannelTree(el, resourceDir, new Set<string>()),\n );\n }\n\n // 2. codeTemplateLibraries.codeTemplateLibrary[] -> codeTemplates/<slug>/library.json\n if (isPlainObject(skeleton['codeTemplateLibraries'])) {\n const libSlugs = new Set<string>();\n await splitCollection(\n skeleton,\n 'codeTemplateLibraries',\n 'codeTemplateLibrary',\n root,\n serverDir,\n (_name, slugName) => {\n const resourceDir = path.join(root, 'codeTemplates', slugName);\n return { jsonFile: path.join(resourceDir, 'library.json'), resourceDir };\n },\n libSlugs,\n async (el, resourceDir) => explodeLibrary(el, resourceDir),\n );\n }\n\n // 3. channelGroups.channelGroup[] -> channelGroups/<slug>.json\n if (isPlainObject(skeleton['channelGroups'])) {\n const groupSlugs = new Set<string>();\n await splitCollection(\n skeleton,\n 'channelGroups',\n 'channelGroup',\n root,\n serverDir,\n (_name, slugName) => {\n const resourceDir = path.join(root, 'channelGroups');\n return { jsonFile: path.join(resourceDir, `${slugName}.json`), resourceDir };\n },\n groupSlugs,\n async (el, resourceDir) =>\n // group json lives in channelGroups/; sidecar code (rare) under same dir\n extractCode(el, {\n jsonDir: resourceDir,\n codeDir: resourceDir,\n friendly: null,\n prefixParts: ['channelGroup'],\n usedPaths: new Set<string>(),\n }) as Promise<Record<string, Json>>,\n );\n }\n\n // 4. Extract code in the remaining skeleton (e.g. globalScripts) and write it.\n const finalSkeleton = await extractCode(skeleton, {\n jsonDir: serverDir,\n codeDir: serverDir,\n friendly: null,\n prefixParts: [],\n usedPaths: new Set<string>(),\n });\n\n await writeJson(path.join(serverDir, 'configuration.json'), finalSkeleton);\n}\n\n/**\n * Explode a code template library: split-out resource. Each template's `code`\n * leaf -> `<slug(template name)>.js` next to library.json (resourceDir).\n */\nasync function explodeLibrary(\n library: Record<string, Json>,\n resourceDir: string,\n): Promise<Record<string, Json>> {\n const used = new Set<string>();\n const usedTemplateSlugs = new Set<string>();\n const out: Record<string, Json> = {};\n\n for (const [key, raw] of Object.entries(library)) {\n if (key === 'codeTemplates' && isPlainObject(raw)) {\n out[key] = await explodeLibraryTemplates(raw, resourceDir, usedTemplateSlugs, used);\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: resourceDir,\n codeDir: resourceDir,\n friendly: null,\n prefixParts: [key],\n usedPaths: used,\n });\n }\n return out;\n}\n\nasync function explodeLibraryTemplates(\n container: Record<string, Json>,\n resourceDir: string,\n usedTemplateSlugs: Set<string>,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n for (const [key, raw] of Object.entries(container)) {\n if (key === 'codeTemplate' && raw != null) {\n const wasArray = Array.isArray(raw);\n const templates = asArray<Json>(raw);\n const transformed: Json[] = [];\n for (const t of templates) {\n transformed.push(\n await explodeCodeTemplate(t, resourceDir, usedTemplateSlugs, usedPaths),\n );\n }\n out[key] = wasArray ? transformed : (transformed[0] as Json);\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: resourceDir,\n codeDir: resourceDir,\n friendly: null,\n prefixParts: ['codeTemplates', key],\n usedPaths,\n });\n }\n return out;\n}\n\nasync function explodeCodeTemplate(\n template: Json,\n resourceDir: string,\n usedTemplateSlugs: Set<string>,\n usedPaths: Set<string>,\n): Promise<Json> {\n if (!isPlainObject(template)) return template;\n const friendlyBase = uniqueSlug(slug(template['name']), usedTemplateSlugs);\n const out: Record<string, Json> = {};\n for (const [key, raw] of Object.entries(template)) {\n // In real Mirth data the body lives at `properties.code`; handle that and\n // (defensively) a `code`/`script` leaf directly on the template object.\n if (key === 'properties' && isPlainObject(raw)) {\n out[key] = await explodeTemplateProperties(raw, resourceDir, friendlyBase, usedPaths);\n continue;\n }\n if (CODE_KEY_SET.has(key) && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw;\n continue;\n }\n const filePath = resolveUnique(resourceDir, `${friendlyBase}.js`, usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(resourceDir, filePath) };\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: resourceDir,\n codeDir: resourceDir,\n friendly: null,\n prefixParts: ['codeTemplate', key],\n usedPaths,\n });\n }\n return out;\n}\n\n/**\n * Explode a code template's `properties` object, whose `code` leaf is the\n * template body -> friendly `<friendlyBase>.js` next to library.json.\n */\nasync function explodeTemplateProperties(\n properties: Record<string, Json>,\n resourceDir: string,\n friendlyBase: string,\n usedPaths: Set<string>,\n): Promise<Record<string, Json>> {\n const out: Record<string, Json> = {};\n for (const [key, raw] of Object.entries(properties)) {\n if (CODE_KEY_SET.has(key) && typeof raw === 'string') {\n if (raw.trim().length === 0) {\n out[key] = raw;\n continue;\n }\n const filePath = resolveUnique(resourceDir, `${friendlyBase}.js`, usedPaths);\n await writeFileMkdir(filePath, raw);\n out[key] = { '@file': relPosix(resourceDir, filePath) };\n continue;\n }\n out[key] = await extractCode(raw as Json, {\n jsonDir: resourceDir,\n codeDir: resourceDir,\n friendly: null,\n prefixParts: ['codeTemplate', 'properties', key],\n usedPaths,\n });\n }\n return out;\n}\n\n// --- implode ---------------------------------------------------------------\n\n/**\n * Resolve a marker path relative to `jsonDir` and assert it stays inside the\n * working-tree `root`. Legitimate markers DO use `..` (e.g. `server/`'s config\n * references `../channelGroups/*.json`), so `..` is allowed — only escaping the\n * tree root is rejected. Working trees are shared/cloned git repos, so marker\n * values are attacker-influenceable input; without this check a crafted\n * `{\"@file\": \"../../../../etc/passwd\"}` would be read into the imploded config\n * (and, via `push`, uploaded to a live server).\n */\nfunction resolveWithinRoot(root: string, jsonDir: string, rel: string): string {\n const target = path.resolve(jsonDir, rel);\n if (target !== root && !target.startsWith(root + path.sep)) {\n throw new Error(`marker path escapes the working tree: ${rel}`);\n }\n return target;\n}\n\n/**\n * Read a marker target, re-checking containment on the real path: the text\n * check above can't see a symlink or junction inside the tree that points\n * outside it.\n */\nasync function readWithinRoot(root: string, target: string, rel: string): Promise<string> {\n const [realRoot, realTarget] = await Promise.all([realpath(root), realpath(target)]);\n if (realTarget !== realRoot && !realTarget.startsWith(realRoot + path.sep)) {\n throw new Error(`marker path escapes the working tree through a link: ${rel}`);\n }\n return readFile(realTarget, 'utf8');\n}\n\n/**\n * Recursively resolve markers in a parsed JSON value. `jsonDir` is the directory\n * of the JSON file this value came from (markers are relative to it); `root` is\n * the working-tree root that every marker target must stay within.\n */\nconst pathKey = (file: string): string => process.platform === 'win32' ? file.toLowerCase() : file;\n\nasync function resolveMarkers(value: Json, jsonDir: string, root: string, referenced: Set<string>): Promise<Json> {\n if (Array.isArray(value)) {\n const out: Json[] = [];\n for (const item of value) {\n // A collection member whose file is gone was deleted from the tree\n // (e.g. `rm -r channels/<name>`), so it is dropped, not an error.\n if (isRefMarker(item) && !existsSync(resolveWithinRoot(root, jsonDir, item['@ref']))) continue;\n out.push(await resolveMarkers(item, jsonDir, root, referenced));\n }\n return out;\n }\n\n if (isFileRef(value)) {\n const target = resolveWithinRoot(root, jsonDir, value['@file']);\n // Raw read, NO trimming — byte-identical round-trip.\n return readWithinRoot(root, target, value['@file']);\n }\n\n if (isRefMarker(value)) {\n const target = resolveWithinRoot(root, jsonDir, value['@ref']);\n const text = await readWithinRoot(root, target, value['@ref']);\n referenced.add(pathKey(await realpath(target)));\n const parsed = parseJson<Json>(text, target);\n return resolveMarkers(parsed, path.dirname(target), root, referenced);\n }\n\n if (isPlainObject(value)) {\n const out: Record<string, Json> = {};\n for (const [k, v] of Object.entries(value)) {\n // Same for a one-member collection, which explode stores as a bare marker.\n if (isRefMarker(v) && !existsSync(resolveWithinRoot(root, jsonDir, v['@ref']))) continue;\n out[k] = await resolveMarkers(v, jsonDir, root, referenced);\n }\n return out;\n }\n\n return value;\n}\n\n/** Canonical resource files are discoverable, so additions and directory renames cannot disappear. */\nasync function discoverResources(config: CanonicalConfig, root: string, referenced: Set<string>): Promise<void> {\n const realRoot = await realpath(root);\n const contained = async (file: string): Promise<string> => {\n const real = await realpath(file);\n if (real !== realRoot && !real.startsWith(realRoot + path.sep)) throw new Error(`resource path escapes the working tree through a link: ${file}`);\n return real;\n };\n const layouts = [\n { folder: 'channels', filename: 'channel.json', container: 'channels', member: 'channel' },\n { folder: 'codeTemplates', filename: 'library.json', container: 'codeTemplateLibraries', member: 'codeTemplateLibrary' },\n { folder: 'channelGroups', filename: null, container: 'channelGroups', member: 'channelGroup' },\n ];\n for (const layout of layouts) {\n const dir = path.join(root, layout.folder);\n if (!existsSync(dir)) continue;\n await contained(dir);\n const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);\n const additions: Json[] = [];\n for (const entry of entries) {\n let file = path.join(dir, entry.name);\n if (layout.filename) {\n if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;\n await contained(file);\n file = path.join(file, layout.filename);\n if (!existsSync(file)) continue;\n } else if (!entry.name.endsWith('.json')) continue;\n const real = await contained(file);\n if (referenced.has(pathKey(real))) continue;\n const parsed = parseJson<Json>(await readWithinRoot(root, file, file), file);\n const resource = await resolveMarkers(parsed, path.dirname(file), root, referenced);\n if (!isPlainObject(resource) || typeof resource['id'] !== 'string' || !resource['id'].trim() || typeof resource['name'] !== 'string' || !resource['name'].trim()) {\n throw new Error(`new resource ${file} needs a nonempty id and name`);\n }\n additions.push(resource);\n referenced.add(pathKey(real));\n }\n if (!additions.length) continue;\n const container = isPlainObject(config[layout.container]) ? config[layout.container] as Record<string, Json> : {};\n const old = container[layout.member];\n const members = [...(old == null || old === '' ? [] : asArray<Json>(old)), ...additions];\n const ids = new Set<string>();\n for (const member of members.filter(isPlainObject)) {\n const id = String(member['id']);\n if (ids.has(id)) throw new Error(`duplicate ${layout.member} id ${id}: a copied resource keeps its source's id; give each copy a new UUID`);\n ids.add(id);\n }\n config[layout.container] = { ...container, [layout.member]: members.length === 1 ? members[0]! : members };\n }\n}\n\nasync function implode(opts: ExplodeOptions): Promise<CanonicalConfig> {\n const root = path.resolve(opts.root);\n if (existsSync(path.join(root, '.channelvault-transaction.json'))) {\n throw new Error('working tree has a pending replacement; run a channelvault CLI command with the original --dotenv selection to recover it before reading');\n }\n const serverDir = path.join(root, 'server');\n const configPath = path.join(serverDir, 'configuration.json');\n const parsed = parseJson<Json>(await readWithinRoot(root, configPath, configPath), configPath);\n const referenced = new Set<string>();\n const resolved = await resolveMarkers(parsed, serverDir, root, referenced);\n if (!isPlainObject(resolved)) throw new Error('server/configuration.json must hold a configuration object');\n await discoverResources(resolved, root, referenced);\n return resolved as CanonicalConfig;\n}\n\n// --- factory ---------------------------------------------------------------\n\nexport function createExplodeEngine(): ExplodeEngine {\n return { explode, implode };\n}\n","/**\n * Shared contracts for channelvault.\n *\n * The whole tool is organized around a single in-memory representation called\n * the **canonical config**: a plain JSON object tree that mirrors Mirth's\n * `serverConfiguration` document. Two adapters produce/consume it:\n *\n * - XML adapter (src/xml): backup .xml <-> canonical (dev / offline path)\n * - Mirth client (src/client): live server <-> canonical (GET/PUT /server/configuration)\n *\n * The explode engine (src/explode) projects a canonical config onto a\n * git-friendly directory tree and reverses it, with embedded JavaScript pulled\n * out into sidecar `.js` files.\n */\n\n/** A JSON value as produced by the XML adapter or the live API. */\nexport type Json = string | number | boolean | null | Json[] | { [k: string]: Json };\n\n/** A canonical config object (the `serverConfiguration` payload, unwrapped). */\nexport type CanonicalConfig = { [k: string]: Json };\n\n/**\n * Marker left in a `*.json` file in place of an extracted script/code leaf.\n *\n * During explode, a code-bearing string leaf (e.g. a transformer step's\n * `script`, or a code template's `code`) is written to a sidecar `.js` file and\n * the original string is replaced, in place, with `{ \"@file\": \"<relpath>\" }`.\n * During implode, any object whose only key is `@file` is replaced by the text\n * content of that file. The path is relative to the JSON file holding the marker.\n */\nexport interface FileRef {\n '@file': string;\n}\n\nexport function isFileRef(v: unknown): v is FileRef {\n return (\n typeof v === 'object' &&\n v !== null &&\n !Array.isArray(v) &&\n Object.keys(v).length === 1 &&\n typeof (v as Record<string, unknown>)['@file'] === 'string'\n );\n}\n\n/**\n * The set of leaf element keys whose string values are treated as JavaScript\n * and extracted to sidecar `.js` files. Detection is by key name plus a\n * non-trivial-content check (see explode engine).\n */\nexport const CODE_KEYS = ['script', 'code'] as const;\n\n/**\n * Channel-level script keys that live directly on a channel object (no nesting).\n * Extracted into `<channel>/scripts/<name>.js`.\n */\nexport const CHANNEL_SCRIPT_KEYS = [\n 'preprocessingScript',\n 'postprocessingScript',\n 'deployScript',\n 'undeployScript',\n] as const;\n\n// --- XML adapter contract -------------------------------------------------\n\nexport interface XmlAdapter {\n /** Parse a Mirth backup XML string into a canonical config. */\n parse(xml: string): CanonicalConfig;\n /** Serialize a canonical config back to Mirth backup XML. */\n build(config: CanonicalConfig): string;\n}\n\n// --- Explode engine contract ----------------------------------------------\n\nexport interface ExplodeOptions {\n /** Absolute path to the working tree root. */\n root: string;\n}\n\nexport interface ExplodeEngine {\n /** Write a canonical config out as a directory tree under `root`. */\n explode(config: CanonicalConfig, opts: ExplodeOptions): Promise<void>;\n /** Read a directory tree under `root` back into a canonical config. */\n implode(opts: ExplodeOptions): Promise<CanonicalConfig>;\n}\n\n// --- Mirth client contract ------------------------------------------------\n\nexport interface ClientConfig {\n host: string;\n port: number;\n username: string;\n password: string;\n /** default true */\n https?: boolean;\n /** default false; set true for self-signed certs */\n disableTlsCheck?: boolean;\n /**\n * default false. Put the server's response body in error messages. A body\n * can echo the credentials that were sent; it is decoded and has credential\n * fields redacted, but the caller must still scrub known secret values.\n */\n includeResponseBodies?: boolean;\n}\n\nexport interface ApiError {\n status: number;\n statusText: string;\n message: string;\n body?: unknown;\n}\n\nexport interface ApiResponse<T> {\n data: T | null;\n error: ApiError | null;\n}\n\nexport interface MirthClient {\n login(): Promise<void>;\n logout(): Promise<void>;\n isAuthenticated(): boolean;\n /** GET /server/configuration -> canonical config (whole-server snapshot). */\n getServerConfiguration(): Promise<CanonicalConfig>;\n /** PUT /server/configuration <- canonical config. */\n putServerConfiguration(config: CanonicalConfig): Promise<void>;\n}\n","import { readFile } from 'node:fs/promises';\n\n/** JSON.parse, naming the file in the error: a tree has hundreds of JSON files. */\nexport function parseJson<T = unknown>(text: string, file: string): T {\n try {\n return JSON.parse(text) as T;\n } catch (err) {\n throw new Error(`${file}: ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nexport async function readJson<T = unknown>(file: string): Promise<T> {\n return parseJson<T>(await readFile(file, 'utf8'), file);\n}\n","/**\n * XML canonical adapter for Mirth Connect \"Backup Config\" documents.\n *\n * Converts a Mirth `serverConfiguration` XML document to/from the canonical\n * config (a plain JSON object tree). `fast-xml-parser` v5 does the tokenizing in\n * its order-preserving mode; the conversion to the canonical object shape and\n * the serializer are ours, because fxp's object mode is lossy in ways a\n * round-trip test built on the same parser cannot see (it regroups interleaved\n * siblings, concatenates mixed-content text, and renames `__proto__`).\n *\n * Canonical shape (unchanged from the original fxp object-mode shape, so\n * existing exploded trees stay valid):\n *\n * - An element with no attributes and no child elements is its text, as a\n * STRING (`\"\"` when empty). Values are never coerced or trimmed: Mirth ids,\n * ports, `\"0B\"`, leading zeros and script-body whitespace all survive.\n * - Otherwise it is an object: child elements (and `#comment`) keyed by name in\n * first-appearance order, then `#text`, then attributes as `@_<name>`.\n * - Repeated names become arrays; `ALWAYS_ARRAY_TAGS` are arrays even when\n * single, so downstream code never special-cases \"one vs many\".\n * - Whitespace-only text beside child elements is indentation and is dropped.\n * - `#order` records the document order of an element's children ONLY when\n * the default order (keys in order, each array contiguous, `#text` last)\n * would differ from it — e.g. a transformer whose steps interleave\n * `JavaScriptStep` and `MapperStep`. It never appears for ordinary Mirth\n * output, and a stale hint (after hand-editing) degrades gracefully.\n *\n * Text fidelity: we own entity decode/encode. XML end-of-line handling (a\n * literal CRLF or CR in the document is a LF) and attribute-value\n * normalization (a literal tab/newline in an attribute is a space) are applied\n * as a conforming parser — Mirth's — would apply them, so the canonical value is\n * what Mirth actually reads. Characters those rules would destroy (CR, and tab\n * or newline inside attributes) are written back as character references.\n *\n * The acceptance criterion is a semantic, order-preserving round-trip:\n *\n * parse(build(parse(xml))) deep-equals parse(xml)\n *\n * plus document order of the rebuilt XML equal to the source's (see tests).\n */\nimport { XMLParser, XMLValidator } from 'fast-xml-parser';\nimport type { CanonicalConfig, Json, XmlAdapter } from '../types.js';\n\n/**\n * Well-known Mirth collection element tags that must ALWAYS be arrays, even\n * when a document contains only a single instance.\n */\nconst ALWAYS_ARRAY_TAGS: ReadonlySet<string> = new Set<string>([\n 'channel',\n 'connector',\n 'codeTemplate',\n 'codeTemplateLibrary',\n 'channelGroup',\n 'alert',\n 'rule',\n 'entry',\n 'string',\n // Fully-qualified JavaScript step / rule element names (live under <elements>).\n 'com.mirth.connect.plugins.javascriptstep.JavaScriptStep',\n 'com.mirth.connect.plugins.javascriptrule.JavaScriptRule',\n 'com.mirth.connect.plugins.mapper.MapperStep',\n 'com.mirth.connect.plugins.messagebuilder.MessageBuilderStep',\n]);\n\n/** The single top-level wrapper key of a Mirth backup document. */\nconst ROOT_KEY = 'serverConfiguration';\n\nconst TEXT_KEY = '#text';\nconst COMMENT_KEY = '#comment';\nconst CDATA_KEY = '#cdata';\n/** Document-order hint; `#` cannot start an XML name, so it cannot collide. */\nexport const ORDER_KEY = '#order';\nconst ATTR_PREFIX = '@_';\nconst ORDERED_ATTRS = ':@';\nconst INDENT = ' ';\n\n/** An fxp `preserveOrder` node: `{ <name>: children, ':@'?: attrs }`. */\ntype OrderedNode = Record<string, unknown>;\n\nfunction isWhitespaceOnly(s: string): boolean {\n return /^\\s*$/.test(s);\n}\n\n/** Named XML entities (the five predefined) -> their character. */\nconst NAMED_DECODE: Readonly<Record<string, string>> = {\n amp: '&',\n lt: '<',\n gt: '>',\n quot: '\"',\n apos: \"'\",\n};\n\n/**\n * Decode XML entities in a single left-to-right pass: the five predefined named\n * entities plus decimal (`&#10;`) and hex (`&#xd;`) numeric character\n * references.\n *\n * A single non-overlapping scan is what makes `&#xd;` and `&amp;#xd;`\n * distinguishable: `&amp;` is consumed as one token (-> `&`) and its output is\n * not re-scanned, so the trailing `#xd;` stays literal.\n */\nfunction decodeEntities(value: string): string {\n if (!value.includes('&')) return value;\n return value.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g, (whole, body: string) => {\n if (body[0] !== '#') return NAMED_DECODE[body] ?? whole;\n const code =\n body[1] === 'x' || body[1] === 'X' ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);\n if (!(code <= 0x10ffff)) {\n throw new Error(`XmlConfigAdapter.parse: invalid character reference ${whole}`);\n }\n return String.fromCodePoint(code);\n });\n}\n\nfunction charRef(ch: string): string {\n return `&#x${ch.charCodeAt(0).toString(16)};`;\n}\n\nconst ESCAPE: Readonly<Record<string, string>> = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&apos;',\n};\n\n/**\n * Encode text content. Escapes the same set fxp's builder did (so unchanged\n * values serialize byte-identically) and writes CR and the other C0 controls\n * except tab/LF as character references: a literal CR would be read back as LF.\n */\nfunction encodeText(value: string): string {\n // eslint-disable-next-line no-control-regex\n return value.replace(/[&<>\"'\\x00-\\x08\\x0b-\\x1f]/g, (ch) => ESCAPE[ch] ?? charRef(ch));\n}\n\n/** Encode an attribute value; tab and LF must be references there too. */\nfunction encodeAttr(value: string): string {\n // eslint-disable-next-line no-control-regex\n return value.replace(/[&<>\"'\\x00-\\x1f]/g, (ch) => ESCAPE[ch] ?? charRef(ch));\n}\n\n// --- parse -----------------------------------------------------------------\n\nfunction nodeName(node: OrderedNode): string {\n const name = Object.keys(node).find((k) => k !== ORDERED_ATTRS);\n if (name === undefined) throw new Error('XmlConfigAdapter.parse: empty node');\n return name;\n}\n\n/** Concatenated text of a `#comment` / `#cdata` node's children, undecoded. */\nfunction rawInnerText(children: unknown): string {\n return (children as OrderedNode[]).map((c) => String(c[TEXT_KEY] ?? '')).join('');\n}\n\n/** The child sequence the serializer emits for `obj` absent an `#order` hint. */\nfunction defaultOrder(obj: Record<string, Json>): string[] {\n const seq: string[] = [];\n for (const [key, value] of Object.entries(obj)) {\n if (key.startsWith(ATTR_PREFIX) || key === ORDER_KEY) continue;\n const count = Array.isArray(value) ? value.length : 1;\n for (let i = 0; i < count; i += 1) seq.push(key);\n }\n return seq;\n}\n\n/** Convert one element's ordered children + attributes to its canonical value. */\nfunction convertElement(children: OrderedNode[], attrs: Record<string, string> | undefined): Json {\n const hasElementChild = children.some((c) => {\n const n = nodeName(c);\n return n !== TEXT_KEY && n !== CDATA_KEY;\n });\n\n // Merge adjacent text/CDATA runs into text segments (CDATA is literal: no\n // entity decoding), and record the document order of what we keep.\n const groups = new Map<string, Json[]>();\n const order: string[] = [];\n const segments: string[] = [];\n let pending: string | null = null;\n const flushText = (): void => {\n if (pending === null) return;\n if (!hasElementChild || !isWhitespaceOnly(pending)) {\n segments.push(pending);\n order.push(TEXT_KEY);\n }\n pending = null;\n };\n\n for (const child of children) {\n const name = nodeName(child);\n if (name === TEXT_KEY) {\n pending = (pending ?? '') + decodeEntities(String(child[TEXT_KEY]));\n continue;\n }\n if (name === CDATA_KEY) {\n pending = (pending ?? '') + rawInnerText(child[CDATA_KEY]);\n continue;\n }\n flushText();\n // fxp renames this element to `#__proto__`; it cannot be an object key.\n if (name === '#__proto__') {\n throw new Error('XmlConfigAdapter.parse: unsupported element name <__proto__>');\n }\n const value =\n name === COMMENT_KEY\n ? rawInnerText(child[COMMENT_KEY])\n : convertElement(child[name] as OrderedNode[], child[ORDERED_ATTRS] as Record<string, string>);\n const group = groups.get(name);\n if (group) group.push(value);\n else groups.set(name, [value]);\n order.push(name);\n }\n flushText();\n\n const attrEntries = Object.entries(attrs ?? {});\n if (!hasElementChild && attrEntries.length === 0) {\n return segments.join('');\n }\n\n const obj: Record<string, Json> = {};\n for (const [name, values] of groups) {\n obj[name] = values.length > 1 || ALWAYS_ARRAY_TAGS.has(name) ? values : values[0]!;\n }\n if (segments.length === 1) obj[TEXT_KEY] = segments[0]!;\n else if (segments.length > 1) obj[TEXT_KEY] = segments;\n\n for (const [key, raw] of attrEntries) {\n if (key === `${ATTR_PREFIX}__proto__`) {\n throw new Error('XmlConfigAdapter.parse: unsupported attribute name __proto__');\n }\n // Attribute-value normalization: literal tab/LF (CRs are already LFs) read\n // as a space; character references were the way to keep them.\n obj[key] = decodeEntities(String(raw).replace(/[\\t\\n]/g, ' '));\n }\n\n const def = defaultOrder(obj);\n if (def.length !== order.length || def.some((k, i) => k !== order[i])) {\n obj[ORDER_KEY] = order;\n }\n return obj;\n}\n\nconst parser = new XMLParser({\n preserveOrder: true,\n ignoreAttributes: false,\n attributeNamePrefix: ATTR_PREFIX,\n parseTagValue: false,\n parseAttributeValue: false,\n trimValues: false,\n processEntities: false,\n commentPropName: COMMENT_KEY,\n cdataPropName: CDATA_KEY,\n});\n\n// --- build -----------------------------------------------------------------\n\n/**\n * The children of `obj` in emit order: honours an `#order` hint as far as it\n * matches the actual children, then appends anything it didn't mention in\n * default order. So adding, removing or renaming a child by hand never loses it.\n */\nfunction orderedChildren(obj: Record<string, Json>, where: string): Array<[string, Json]> {\n const queues = new Map<string, Json[]>();\n for (const [key, value] of Object.entries(obj)) {\n if (key.startsWith(ATTR_PREFIX) || key === ORDER_KEY) continue;\n queues.set(key, Array.isArray(value) ? [...value] : [value]);\n }\n const out: Array<[string, Json]> = [];\n const hint = obj[ORDER_KEY];\n if (hint !== undefined) {\n if (!Array.isArray(hint) || !hint.every((h) => typeof h === 'string')) {\n throw new Error(`XmlConfigAdapter.build: ${ORDER_KEY} under <${where}> must be an array of names`);\n }\n for (const name of hint as string[]) {\n const next = queues.get(name)?.shift();\n if (next !== undefined) out.push([name, next]);\n }\n }\n for (const [key, rest] of queues) {\n for (const value of rest) out.push([key, value]);\n }\n return out;\n}\n\nfunction scalar(value: Json): string {\n return value === null ? '' : String(value);\n}\n\nfunction serialize(name: string, value: Json, depth: number, pretty: boolean, out: string[]): void {\n const pad = pretty ? INDENT.repeat(depth) : '';\n const nl = pretty ? '\\n' : '';\n\n if (name === COMMENT_KEY) {\n const text = scalar(value);\n if (text.includes('--') || text.endsWith('-')) {\n throw new Error(`XmlConfigAdapter.build: comment text cannot contain \"--\": ${text}`);\n }\n out.push(`${pad}<!--${text}-->${nl}`);\n return;\n }\n if (name === TEXT_KEY) {\n out.push(encodeText(scalar(value)));\n return;\n }\n\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n out.push(`${pad}<${name}>${encodeText(scalar(value))}</${name}>${nl}`);\n return;\n }\n\n const attrs = Object.entries(value)\n .filter(([k]) => k.startsWith(ATTR_PREFIX))\n .map(([k, v]) => ` ${k.slice(ATTR_PREFIX.length)}=\"${encodeAttr(scalar(v))}\"`)\n .join('');\n const children = orderedChildren(value, name);\n const hasElementChild = children.some(([k]) => k !== TEXT_KEY);\n\n if (!hasElementChild) {\n const text = children.map(([, v]) => encodeText(scalar(v))).join('');\n out.push(`${pad}<${name}${attrs}>${text}</${name}>${nl}`);\n return;\n }\n\n // Mixed content can't be indented: the indentation would become part of its\n // text. Emit that element compactly.\n const mixed = children.some(([k]) => k === TEXT_KEY);\n const childPretty = pretty && !mixed;\n out.push(`${pad}<${name}${attrs}>${childPretty ? '\\n' : ''}`);\n for (const [key, child] of children) {\n serialize(key, child, depth + 1, childPretty, out);\n }\n out.push(`${childPretty ? pad : ''}</${name}>${nl}`);\n}\n\n// --- adapter ---------------------------------------------------------------\n\nexport class XmlConfigAdapter implements XmlAdapter {\n /** Parse a Mirth backup XML string into a canonical config. */\n parse(xml: string): CanonicalConfig {\n // XML end-of-line handling, which fxp does not apply.\n const normalized = xml.replace(/\\r\\n?/g, '\\n');\n if (/<!DOCTYPE/i.test(normalized.slice(0, normalized.search(/<[A-Za-z_]/)))) {\n // A DTD could declare entities we would not expand; Mirth never emits one.\n throw new Error('XmlConfigAdapter.parse: DOCTYPE declarations are not supported');\n }\n // fxp's parser accepts unclosed elements, so a truncated backup would read\n // as a smaller, \"valid\" configuration; validate the whole document first.\n const valid = XMLValidator.validate(normalized);\n if (valid !== true) {\n const { line, col, msg } = valid.err;\n throw new Error(`XmlConfigAdapter.parse: not well-formed XML at line ${line}, column ${col}: ${msg}`);\n }\n const nodes = parser.parse(normalized) as OrderedNode[];\n const root = nodes.find((n) => nodeName(n) === ROOT_KEY);\n if (root === undefined) {\n throw new Error(`XmlConfigAdapter.parse: expected a top-level <${ROOT_KEY}> element`);\n }\n const value = convertElement(root[ROOT_KEY] as OrderedNode[], root[ORDERED_ATTRS] as Record<string, string>);\n return (typeof value === 'object' && value !== null && !Array.isArray(value) ? value : {}) as CanonicalConfig;\n }\n\n /** Serialize a canonical config back to Mirth backup XML. */\n build(config: CanonicalConfig): string {\n const out: string[] = [];\n serialize(ROOT_KEY, config, 0, true, out);\n return out.join('');\n }\n}\n","/**\n * Live Mirth transport client.\n *\n * Talks to a running Mirth Connect (a.k.a. NextGen Connect / OIE / BridgeLink)\n * server over its REST API and produces/consumes the canonical config (the\n * unwrapped `serverConfiguration` document) — the same logical document the XML\n * adapter parses from a backup file.\n *\n * The transport (login, cookie jar, TLS bypass, 401 re-auth, single-flight\n * login) is ported from the proven `baseClient.ts` in the sibling\n * `integration-engine-api` project. We deliberately do NOT carry over the\n * OpenAPI-generated typing layers: payloads are opaque `CanonicalConfig` JSON.\n *\n * Wrapping behavior for the two endpoints:\n *\n * - GET /server/configuration returns a Jackson-style document wrapped in a\n * single top-level key (`serverConfiguration`), with `@version` / `@class`\n * metadata sprinkled throughout. `getServerConfiguration()` unwraps the\n * single top-level key and returns its contents.\n * - PUT /server/configuration expects the same wrapper, so\n * `putServerConfiguration()` re-wraps as `{ serverConfiguration: config }`.\n */\nimport { CookieJar } from 'tough-cookie';\nimport { Agent } from 'undici';\nimport { redactSecretsInText } from '../secrets/detect.js';\nimport { isSecretKey } from '../secrets/index.js';\nimport type { ApiError, CanonicalConfig, ClientConfig, MirthClient } from '../types.js';\nimport { liveConfiguration } from './validate.js';\n\n/** TLS verification failures, typically a self-signed or privately issued server certificate. */\nexport const UNTRUSTED_CERT_CODES: ReadonlySet<string> = new Set([\n 'DEPTH_ZERO_SELF_SIGNED_CERT',\n 'SELF_SIGNED_CERT_IN_CHAIN',\n 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',\n 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',\n // Not an expired certificate or a host-name mismatch: turning verification\n // off is the wrong advice for those, and their messages already say why.\n]);\n\n/**\n * fetch reports every network failure as \"fetch failed\" and keeps the reason\n * (ECONNREFUSED, a certificate error) in `cause`; surface it, with its code.\n */\nfunction connectionError(url: string, err: unknown): Error & { code?: string } {\n let cause = err instanceof Error ? (err.cause as (Error & { code?: string; errors?: unknown[] }) | undefined) : undefined;\n // Several addresses tried (IPv4 and IPv6): report the first attempt.\n if (cause instanceof AggregateError && cause.errors[0] instanceof Error) cause = cause.errors[0] as Error & { code?: string };\n const detail = cause?.message || (err instanceof Error ? err.message : String(err));\n const code = cause?.code;\n const error = new Error(\n `cannot reach ${new URL(url).origin}: ${detail}${code && !detail.includes(code) ? ` (${code})` : ''}`,\n { cause: err },\n ) as Error & { code?: string };\n error.code = code;\n return error;\n}\n\n/** Optional flags accepted by `putServerConfiguration` (Mirth query params). */\nexport interface PutServerConfigurationOptions {\n /** Redeploy all channels after applying the configuration. */\n deploy?: boolean;\n /** Overwrite the global configuration map. */\n overwriteConfigMap?: boolean;\n}\n\n/**\n * The public client type. It satisfies the declared {@link MirthClient}\n * contract but widens `putServerConfiguration` to accept the optional Mirth\n * query-param flags. The widened signature is structurally assignable to the\n * one-arg contract (the extra parameter is optional), so a `MirthClientExt`\n * is a valid `MirthClient` wherever the bare contract is expected.\n */\nexport interface MirthClientExt extends MirthClient {\n putServerConfiguration(config: CanonicalConfig, options?: PutServerConfigurationOptions): Promise<void>;\n /** GET /server/id: the installation's ID, which a configuration restore does not change (verified on 4.5.2). */\n getServerId(): Promise<string>;\n /** GET /server/configuration as the server's own XML (the Administrator's Backup Config document). */\n getServerConfigurationXml(): Promise<string>;\n /** PUT /server/configuration from backup XML, as the Administrator's Restore Config does. */\n putServerConfigurationXml(xml: string, options?: PutServerConfigurationOptions): Promise<void>;\n /** GET /channels/{id}, unwrapped; includes the tag and dependency data the server configuration omits. */\n getChannel(id: string): Promise<Record<string, unknown> | null>;\n /** Standalone templates remain readable after being removed from a library. */\n getCodeTemplate(id: string): Promise<Record<string, unknown> | null>;\n /** PUT /channels/{id}; creates the channel if the id is new. */\n putChannel(channel: Record<string, unknown>): Promise<void>;\n /** Release pooled connections so the process can exit promptly. */\n close(): Promise<void>;\n deleteChannel(id: string): Promise<void>;\n /** PUT /codeTemplates/{id}; creates the template if the id is new. */\n putCodeTemplate(template: Record<string, unknown>): Promise<void>;\n deleteCodeTemplate(id: string): Promise<void>;\n /** PUT /codeTemplateLibraries: replaces the whole list (membership and library settings). */\n putCodeTemplateLibraries(libraries: Record<string, unknown>[]): Promise<void>;\n /** PUT /server/globalScripts, from the `globalScripts` value of a server configuration. */\n putGlobalScripts(globalScripts: unknown): Promise<void>;\n /** POST /channels/{id}/_deploy; throws if deployment fails. */\n deployChannel(id: string): Promise<void>;\n /** Ids of the channels currently deployed (GET /channels/statuses). */\n getDeployedChannelIds(): Promise<Set<string>>;\n}\n\n/** Internal HTTP verbs we use. */\ntype HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n\n/** Options for the low-level authenticated request helper. */\ninterface RequestOptions {\n /** Already-serialized request body. */\n body?: string;\n /** Query parameters appended to the URL. */\n query?: Record<string, unknown>;\n /** Additional headers merged over the defaults. */\n headers?: Record<string, string>;\n}\n\n/** Shape of the (unwrapped) Mirth login status payload we read. */\ninterface LoginStatusPayload {\n status?: string;\n message?: string | null;\n}\n\n/** The single top-level wrapper key of a Mirth backup / server config document. */\nconst SERVER_CONFIG_KEY = 'serverConfiguration';\n\n/**\n * Unwrap a Jackson-style single-key wrapper. Mirth wraps many responses in a\n * single top-level namespace key. If the value has exactly one top-level key we\n * unwrap it; otherwise we return it unchanged (defensive against the wrapper\n * being named differently or absent).\n */\nfunction unwrapSingleKey(value: Record<string, unknown>): unknown {\n const keys = Object.keys(value);\n if (keys.length === 1) {\n return value[keys[0] as string];\n }\n return value;\n}\n\n/**\n * MirthClient implementation. Created via {@link createMirthClient}.\n */\nclass MirthClientImpl implements MirthClientExt {\n private readonly config: ClientConfig;\n private readonly baseUrl: string;\n private readonly cookieJar: CookieJar;\n /** Our own pool (not the global one) so `close()` can release it. */\n private readonly dispatcher: Agent;\n\n private authenticated = false;\n /** Single in-flight login promise (concurrency guard). */\n private loginPromise: Promise<void> | null = null;\n\n constructor(config: ClientConfig) {\n this.config = config;\n const protocol = config.https !== false ? 'https' : 'http';\n this.baseUrl = `${protocol}://${config.host}:${config.port}/api`;\n this.cookieJar = new CookieJar();\n\n this.dispatcher = new Agent(config.disableTlsCheck ? { connect: { rejectUnauthorized: false } } : {});\n }\n\n isAuthenticated(): boolean {\n return this.authenticated;\n }\n\n /**\n * Establish a session. Concurrent calls share a single in-flight login.\n */\n async login(): Promise<void> {\n if (this.loginPromise) {\n return this.loginPromise;\n }\n\n this.loginPromise = (async () => {\n try {\n const loginUrl = `${this.baseUrl}/users/_login`;\n\n const body = new URLSearchParams({\n username: this.config.username,\n password: this.config.password,\n });\n\n const response = await this.send(loginUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'X-Requested-With': 'XMLHttpRequest',\n Accept: 'application/json',\n },\n body: body.toString(),\n });\n\n await this.storeCookies(response, this.baseUrl);\n\n if (!response.ok) {\n // Not the body: a login endpoint's error page can echo the request.\n await response.body?.cancel();\n throw new Error(`Login failed: HTTP ${response.status} ${response.statusText}`.trimEnd());\n }\n\n const result = (await response.json()) as Record<string, unknown>;\n\n // Mirth wraps the result, e.g.\n // { 'com.mirth.connect.model.LoginStatus': { status: 'SUCCESS', message: null } }\n const payload = unwrapSingleKey(result) as LoginStatusPayload;\n\n if (payload.status !== 'SUCCESS') {\n throw new Error(`Login failed: ${payload.status} - ${payload.message ?? 'Unknown error'}`);\n }\n\n this.authenticated = true;\n } finally {\n this.loginPromise = null;\n }\n })();\n\n return this.loginPromise;\n }\n\n /**\n * End the session and clear local auth state + cookies.\n */\n async logout(): Promise<void> {\n if (!this.authenticated) {\n return;\n }\n\n try {\n const logoutUrl = `${this.baseUrl}/users/_logout`;\n const cookieString = await this.cookieJar.getCookieString(logoutUrl);\n await this.send(logoutUrl, {\n method: 'POST',\n headers: {\n 'X-Requested-With': 'XMLHttpRequest',\n ...(cookieString ? { Cookie: cookieString } : {}),\n },\n });\n } finally {\n this.authenticated = false;\n await this.cookieJar.removeAllCookies();\n }\n }\n\n /**\n * GET /server/configuration -> canonical config.\n *\n * Requests JSON and validates the envelope and core resource collections\n * before this snapshot can be used to replace a tree or plan server writes.\n */\n async getServerConfiguration(): Promise<CanonicalConfig> {\n const response = await this.request('GET', '/server/configuration', {\n headers: { Accept: 'application/json' },\n });\n\n let json: unknown;\n try { json = await response.json(); }\n catch { throw new Error('invalid server configuration response: expected JSON'); }\n return liveConfiguration(json);\n }\n\n /**\n * PUT /server/configuration <- canonical config.\n *\n * Re-wraps the canonical config as `{ serverConfiguration: config }` and\n * forwards the optional `deploy` / `overwriteConfigMap` flags as query params.\n */\n async putServerConfiguration(config: CanonicalConfig, options: PutServerConfigurationOptions = {}): Promise<void> {\n const query: Record<string, unknown> = {};\n if (options.deploy !== undefined) {\n query.deploy = options.deploy;\n }\n if (options.overwriteConfigMap !== undefined) {\n query.overwriteConfigMap = options.overwriteConfigMap;\n }\n\n const wrapped = { [SERVER_CONFIG_KEY]: config };\n\n await this.request('PUT', '/server/configuration', {\n query,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n },\n body: JSON.stringify(wrapped),\n });\n }\n\n async getServerId(): Promise<string> {\n // JSON is refused (406); the ID comes as plain text. Mirth generates a UUID but reads it from\n // appdata/server.id, which admins can set to any name (one 4.5.0 server answers \"mirth-gov\").\n // It is only compared and printed, so accept one printable line and refuse control and\n // format characters (terminal escapes, newlines, bidi overrides).\n const response = await this.request('GET', '/server/id', { headers: { Accept: 'text/plain' } });\n const id = (await response.text()).trim();\n if (!/^[^\\p{Cc}\\p{Cf}]{1,255}$/u.test(id)) throw new Error('the server returned an invalid installation ID');\n return id;\n }\n\n async getServerConfigurationXml(): Promise<string> {\n const response = await this.request('GET', '/server/configuration', { headers: { Accept: 'application/xml' } });\n return response.text();\n }\n\n async putServerConfigurationXml(xml: string, options: PutServerConfigurationOptions = {}): Promise<void> {\n await this.request('PUT', '/server/configuration', {\n query: { deploy: options.deploy, overwriteConfigMap: options.overwriteConfigMap },\n headers: { 'Content-Type': 'application/xml', Accept: 'application/json' },\n body: xml,\n });\n }\n\n // --- per-resource ---------------------------------------------------------\n // Override is on: Mirth does not reject a stale revision anyway (verified on\n // 4.5.2), so conflict detection happens in the push planner instead.\n\n async getChannel(id: string): Promise<Record<string, unknown> | null> {\n return this.getResource(`/channels/${encodeURIComponent(id)}`);\n }\n\n async getCodeTemplate(id: string): Promise<Record<string, unknown> | null> {\n return this.getResource(`/codeTemplates/${encodeURIComponent(id)}`);\n }\n\n private async getResource(resourcePath: string): Promise<Record<string, unknown> | null> {\n const response = await this.request('GET', resourcePath, {\n headers: { Accept: 'application/json' },\n }).catch((err: Error & ApiError) => {\n if (err.status === 404) return null;\n throw err;\n });\n if (!response) return null;\n const text = await response.text();\n if (text.trim() === '') return null;\n const parsed = JSON.parse(text) as Record<string, unknown> | null;\n return parsed === null ? null : unwrapSingleKey(parsed) as Record<string, unknown> | null;\n }\n\n async close(): Promise<void> {\n await this.dispatcher.close();\n }\n\n async putChannel(channel: Record<string, unknown>): Promise<void> {\n await this.sendJson('PUT', `/channels/${encodeURIComponent(String(channel.id))}`, { channel }, { override: true });\n }\n\n async deleteChannel(id: string): Promise<void> {\n await this.request('DELETE', `/channels/${encodeURIComponent(id)}`);\n }\n\n async putCodeTemplate(template: Record<string, unknown>): Promise<void> {\n await this.sendJson('PUT', `/codeTemplates/${encodeURIComponent(String(template.id))}`, { codeTemplate: template }, { override: true });\n }\n\n async deleteCodeTemplate(id: string): Promise<void> {\n await this.request('DELETE', `/codeTemplates/${encodeURIComponent(id)}`);\n }\n\n async putCodeTemplateLibraries(libraries: Record<string, unknown>[]): Promise<void> {\n await this.sendJson('PUT', '/codeTemplateLibraries', { list: { codeTemplateLibrary: libraries } }, { override: true });\n }\n\n async putGlobalScripts(globalScripts: unknown): Promise<void> {\n await this.sendJson('PUT', '/server/globalScripts', { map: globalScripts });\n }\n\n async getDeployedChannelIds(): Promise<Set<string>> {\n const response = await this.request('GET', '/channels/statuses', { headers: { Accept: 'application/json' } });\n const text = await response.text();\n const ids = new Set<string>();\n // Undeployed channels have no status entry; collect every channelId present.\n for (const m of text.matchAll(/\"channelId\"\\s*:\\s*\"([^\"]+)\"/g)) ids.add(m[1]!);\n return ids;\n }\n\n async deployChannel(id: string): Promise<void> {\n await this.request('POST', `/channels/${encodeURIComponent(id)}/_deploy`, { query: { returnErrors: true } });\n }\n\n /** Send a JSON body; Mirth answers some updates with `{\"boolean\": false}` instead of an error status. */\n private async sendJson(method: HttpMethod, path: string, body: unknown, query?: Record<string, unknown>): Promise<void> {\n const response = await this.request(method, path, {\n query,\n headers: { 'Content-Type': 'application/json', Accept: 'application/json' },\n body: JSON.stringify(body),\n });\n const text = await response.text();\n if (/^\\s*\\{\\s*\"boolean\"\\s*:\\s*false\\s*\\}\\s*$/.test(text)) {\n throw new Error(`${method} ${path}: the server refused the update`);\n }\n }\n\n // --- internal transport ---------------------------------------------------\n\n /**\n * Make an authenticated request. Ensures login, attaches/stores cookies, and\n * on a 401 while authenticated resets auth, re-logs in once, and retries.\n * Throws an {@link ApiError}-shaped error on a non-2xx response.\n */\n private async request(method: HttpMethod, path: string, options: RequestOptions = {}, isRetry = false): Promise<Response> {\n if (!this.authenticated) {\n await this.login();\n }\n\n const url = this.buildUrl(path, options.query);\n\n const headers: Record<string, string> = {\n 'X-Requested-With': 'XMLHttpRequest',\n ...options.headers,\n };\n\n const cookieString = await this.cookieJar.getCookieString(url);\n if (cookieString) {\n headers.Cookie = cookieString;\n }\n\n const response = await this.send(url, { method, headers, body: options.body });\n\n await this.storeCookies(response, url);\n\n // 401 while authenticated -> reset auth, re-login once, retry exactly once.\n if (response.status === 401 && this.authenticated && !isRetry) {\n this.authenticated = false;\n await this.login();\n return this.request(method, path, options, true);\n }\n\n if (!response.ok) {\n throw await this.toApiError(response);\n }\n\n return response;\n }\n\n /** fetch through this client's pool, with network failures explained. */\n private async send(url: string, init: RequestInit): Promise<Response> {\n try {\n return await fetch(url, {\n ...init,\n // @ts-expect-error - dispatcher is a Node.js/undici specific option\n dispatcher: this.dispatcher,\n });\n } catch (err) {\n throw connectionError(url, err);\n }\n }\n\n /** Build an absolute URL with an optional query string. */\n private buildUrl(path: string, query?: Record<string, unknown>): string {\n const url = `${this.baseUrl}${path}`;\n if (!query || Object.keys(query).length === 0) {\n return url;\n }\n\n const searchParams = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) {\n continue;\n }\n searchParams.append(key, String(value));\n }\n\n const qs = searchParams.toString();\n return qs ? `${url}?${qs}` : url;\n }\n\n /** Persist any `set-cookie` from a response into the jar. */\n private async storeCookies(response: Response, url: string): Promise<void> {\n // One entry per header: get('set-cookie') joins them with \", \", which also\n // appears inside a cookie's Expires date.\n for (const cookie of response.headers.getSetCookie()) {\n await this.cookieJar.setCookie(cookie, url);\n }\n }\n\n /** Build an ApiError-shaped Error from a non-2xx response. */\n private async toApiError(response: Response): Promise<Error & ApiError> {\n let body: unknown;\n try {\n body = await response.text();\n } catch {\n // ignore body read errors\n }\n\n // An error body can echo the payload sent, credentials included, in any\n // form (escaped, truncated, reformatted), so no redaction of it is\n // complete: it is left out unless asked for. When included it is whole and\n // unnormalized, so the caller's scrub of known values can still match.\n const text = typeof body === 'string' ? redactSecretsInText(readableBody(body)).trim() : '';\n const reason =\n text === '' ? '' : this.config.includeResponseBodies ? `: ${text}` : ' (server response withheld; it may echo credentials)';\n const message = `HTTP ${response.status}: ${response.statusText}${reason}`;\n const error = new Error(message) as Error & ApiError;\n error.status = response.status;\n error.statusText = response.statusText;\n error.message = message;\n error.body = text;\n return error;\n }\n}\n\nconst XML_ENTITIES: Readonly<Record<string, string>> = { amp: '&', lt: '<', gt: '>', quot: '\"', apos: \"'\" };\n\n/**\n * An error body as the text a person reads: JSON as its decoded values, XML as\n * its decoded text. Anything that redacts by value (the CLI knows the secrets\n * sent) then sees a secret as it was sent, not escaped as `\\\"` or `&amp;`.\n * Credential fields are replaced while their names are still known.\n */\nexport function readableBody(body: string): string {\n const trimmed = body.trim();\n // Any JSON value: a bare string can carry \\u escapes too.\n if (/^[[{\"]/.test(trimmed)) {\n try {\n return flattenJson(JSON.parse(trimmed) as unknown);\n } catch {\n // not JSON after all\n }\n }\n if (!trimmed.startsWith('<')) return trimmed;\n // Mirth's HTML error pages say only \"Request failed.\", so they add nothing.\n if (/^<(!doctype|html)/i.test(trimmed)) return '';\n // A marker that survives removing the tags.\n const REDACTED = '\\u0000redacted\\u0000';\n return trimmed\n .replace(/<([\\w.:-]+)>[^<]*<\\/\\1>/g, (whole, key: string) => (isSecretKey(key) ? ` ${key}: ${REDACTED} ` : whole))\n .replace(/<[^>]*>/g, ' ')\n .split(REDACTED)\n .join('<redacted>')\n .replace(/&(#x[0-9a-f]+|#[0-9]+|amp|lt|gt|quot|apos);/gi, (whole, e: string) =>\n e[0] === '#'\n ? String.fromCodePoint(e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10))\n : (XML_ENTITIES[e.toLowerCase()] ?? whole),\n );\n}\n\nfunction flattenJson(value: unknown, key = ''): string {\n if (typeof value === 'string') return key !== '' && isSecretKey(key) && value !== '' ? '<redacted>' : value;\n if (Array.isArray(value)) return value.map((v) => flattenJson(v, key)).join('; ');\n if (value !== null && typeof value === 'object') {\n return Object.entries(value).map(([k, v]) => `${k}: ${flattenJson(v, k)}`).join(', ');\n }\n return String(value);\n}\n\n/**\n * Factory for the live Mirth transport client.\n */\nexport function createMirthClient(config: ClientConfig): MirthClientExt {\n return new MirthClientImpl(config);\n}\n","/**\n * Find secrets that the key-name rules in `templatize` miss: credentials\n * embedded in URLs and connection strings, authorization headers, password\n * assignments in scripts, private keys and well-known token formats.\n *\n * Findings are reported by location and kind only; a secret value is never\n * printed. `extract` replaces just the secret part of each string with an\n * `{{env:NAME}}` placeholder, so the surrounding script or URL stays readable.\n */\nimport { createHash } from 'node:crypto';\n\nimport { CHANNEL_SCRIPT_KEYS, CODE_KEYS, type CanonicalConfig } from '../types.js';\nimport { derivedName, hasPlaceholder, isSecretKey, mapLeaves, placeholder, type Env, type Leaf } from './index.js';\n\nexport type SecretKind =\n | 'private-key'\n | 'url-credentials'\n | 'connection-string'\n | 'authorization-header'\n | 'db-connection-call'\n | 'assignment'\n | 'setter-call'\n | 'aws-access-key'\n | 'jwt'\n | 'github-token'\n | 'slack-token';\n\n/** A secret's position in a string. */\ninterface Span {\n start: number;\n end: number;\n}\n\ninterface Rule {\n kind: SecretKind;\n /** Suffix for the env variable name. */\n suffix: string;\n /** `script`: the value is JavaScript (a step, template or channel script). */\n spans(value: string, script: boolean): Span[];\n}\n\n/** Spans of capture group `group` (0 = whole match) of every match of `re`. */\nfunction regexSpans(re: RegExp, group: number): (value: string) => Span[] {\n return (value) => {\n const out: Span[] = [];\n for (const m of value.matchAll(re)) {\n const secret = m[group];\n if (secret === undefined) continue;\n // The secret is the last occurrence of its text within the match.\n const start = m.index + m[0].lastIndexOf(secret);\n out.push({ start, end: start + secret.length });\n }\n return out;\n };\n}\n\n/**\n * The fourth argument of `createDatabaseConnection(driver, url, user, password)`\n * when it is a string literal. Arguments are split at top-level commas, so\n * calls like `$('driver')` in earlier arguments don't throw it off.\n */\nfunction dbConnectionSpans(value: string): Span[] {\n const out: Span[] = [];\n for (const m of value.matchAll(/createDatabaseConnection\\s*\\(/g)) {\n let depth = 0;\n let quote: string | null = null;\n let argStart = m.index + m[0].length;\n const args: Span[] = [];\n for (let i = argStart; i < value.length; i += 1) {\n const c = value[i]!;\n if (quote) {\n if (c === '\\\\') i += 1;\n else if (c === quote) quote = null;\n continue;\n }\n if (c === '\"' || c === \"'\") quote = c;\n else if (c === '(' || c === '[' || c === '{') depth += 1;\n else if ((c === ')' || c === ']' || c === '}') && depth > 0) depth -= 1;\n else if ((c === ',' && depth === 0) || c === ')') {\n args.push({ start: argStart, end: i });\n argStart = i + 1;\n if (c === ')') break;\n }\n }\n const pw = args[3];\n if (!pw) continue;\n const literal = /^\\s*([\"'])(.+)\\1\\s*$/s.exec(value.slice(pw.start, pw.end));\n if (literal) {\n const start = value.indexOf(literal[2]!, pw.start);\n out.push({ start, end: start + literal[2]!.length });\n }\n }\n return out;\n}\n\n/**\n * The tail of `name = 'literal'` / `name: \"literal\"`: an optional default-value\n * prefix (`name || `, `name ?? `), then a quoted literal of 4+ characters on one\n * line. Braces are excluded so `${var}` templates and placeholders don't match. A\n * literal with spaces must also hold a digit or symbol, so prose such as\n * `secret = 'Not configured yet'` is not a secret.\n */\nconst ASSIGNED = String.raw`[\"']?\\s*[:=]\\s*(?:[\\w$.[\\]'\"]+\\s*(?:\\|\\||\\?\\?)\\s*)?([\"'])((?=\\S)(?:[^\"'{}\\s]{4,}|(?=[^\"'{}\\n]*[0-9@#$%^&*+=~|\\\\/<>_])[^\"'{}\\n]{4,}))\\1`;\n\n/** A connection-string value: up to the next delimiter, without surrounding spaces. */\nconst CONN_VALUE = String.raw`([^;&'\"\\s](?:[^;&'\"\\n]*[^;&'\"\\s])?)`;\n\n/**\n * String literals and comments of a script: where a connection string can\n * appear as text. Regex literals are not recognised, so a quote inside one\n * can shift what counts as a literal.\n */\nfunction textSpans(code: string): Span[] {\n const out: Span[] = [];\n let i = 0;\n while (i < code.length) {\n const c = code[i]!;\n const next = code[i + 1];\n if (c === '/' && (next === '/' || next === '*')) {\n const close = next === '/' ? code.indexOf('\\n', i) : code.indexOf('*/', i + 2);\n const end = close < 0 ? code.length : close;\n out.push({ start: i + 2, end });\n i = end + 2;\n } else if (c === '\"' || c === \"'\" || c === '`') {\n let j = i + 1;\n while (j < code.length && code[j] !== c && (c === '`' || code[j] !== '\\n')) j += code[j] === '\\\\' ? 2 : 1;\n out.push({ start: i + 1, end: Math.min(j, code.length) });\n i = j + 1;\n } else {\n i += 1;\n }\n }\n return out;\n}\n\n/** Apply `spans` to a whole data value, but only to the text parts of a script. */\nfunction outsideCode(spans: (value: string) => Span[]): (value: string, script: boolean) => Span[] {\n return (value, script) =>\n script\n ? textSpans(value).flatMap((t) => spans(value.slice(t.start, t.end)).map((s) => ({ start: s.start + t.start, end: s.end + t.start })))\n : spans(value);\n}\n\n// Earlier rules win where spans overlap: a private key block may contain text\n// other rules match, and `token = 'ghp_…'` is one secret, not two.\nconst RULES: Rule[] = [\n {\n kind: 'private-key',\n suffix: 'PRIVATE_KEY',\n spans: regexSpans(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, 0),\n },\n { kind: 'aws-access-key', suffix: 'AWS_ACCESS_KEY', spans: regexSpans(/\\b(?:AKIA|ASIA)[0-9A-Z]{16}\\b/g, 0) },\n { 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) },\n { kind: 'github-token', suffix: 'TOKEN', spans: regexSpans(/\\b(?:ghp|gho|ghs|ghu|github_pat)_[A-Za-z0-9_]{20,}/g, 0) },\n { kind: 'slack-token', suffix: 'TOKEN', spans: regexSpans(/\\bxox[abprs]-[A-Za-z0-9-]{10,}/g, 0) },\n // user:password@host. The user part stops at ';', '?' and '&' so a JDBC\n // parameter like `user=svc@srv` is not mistaken for credentials.\n { kind: 'url-credentials', suffix: 'PASSWORD', spans: regexSpans(/\\b[a-z][a-z0-9+.-]*:\\/\\/[^\\s:/@'\";?&]+:([^\\s@'\"/;?&]+)@/gi, 1) },\n // Drivers trim around `=` and the value, so spaces are allowed there. In a\n // script only string literals and comments are searched: `pwd=$('x')` is code.\n {\n kind: 'connection-string',\n suffix: 'PASSWORD',\n spans: outsideCode(regexSpans(new RegExp(String.raw`[;?&]\\s*(?:password|pwd)\\s*=\\s*${CONN_VALUE}`, 'gi'), 1)),\n },\n // Leading the whole value (`Password=…;Server=…`), when another key=value follows.\n {\n kind: 'connection-string',\n suffix: 'PASSWORD',\n spans: outsideCode(regexSpans(new RegExp(String.raw`^\\s*(?:password|pwd)\\s*=\\s*${CONN_VALUE}(?=\\s*;\\s*[\\w ]+=)`, 'gi'), 1)),\n },\n // Case-sensitive, and the credential must contain a digit or a base64/token\n // symbol, so prose like \"Basic authentication\" does not match.\n {\n kind: 'authorization-header',\n suffix: 'TOKEN',\n spans: regexSpans(/\\b(?:Basic|Bearer)\\s+((?=[A-Za-z0-9+/=._~-]*[0-9+/=])[A-Za-z0-9+/=._~-]{12,})/g, 1),\n },\n { kind: 'db-connection-call', suffix: 'DB_PASSWORD', spans: dbConnectionSpans },\n // name = 'literal' where the name ends in a secret word: password, dbPassword,\n // db_password, DB_PASSWORD, apiKey, authToken… (not tokenizer, not ==).\n // Also the default-value idiom: apiKey = apiKey || 'literal' (or ??).\n {\n kind: 'assignment',\n suffix: 'PASSWORD',\n spans: regexSpans(new RegExp(`(?<![\\\\w$])[\\\\w$]*?(?:password|passwd|pwd|secret|api[_-]?key|access[_-]?key|token)${ASSIGNED}`, 'gi'), 2),\n },\n // `pass` as a whole name or a word boundary within one (pass, dbPass,\n // DB_PASS, sftp_pass), case-sensitive so bypass and compass don't match,\n // and not after words that make it an ordinary noun (byPass, firstPass).\n {\n kind: 'assignment',\n suffix: 'PASSWORD',\n 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),\n },\n // conn.setPassword('literal'), props.setApiKey(\"literal\")…\n {\n kind: 'setter-call',\n suffix: 'PASSWORD',\n spans: regexSpans(/\\bset[A-Za-z]*(?:Password|Passwd|Passphrase|Secret|Token|ApiKey)\\s*\\(\\s*([\"'])([^\"'\\n]{4,})\\1\\s*\\)/g, 2),\n },\n];\n\n/** A Mirth `${variable}` or one of our placeholders is a reference, not a secret. */\nfunction isReference(secret: string): boolean {\n return secret.includes('${') || hasPlaceholder(secret);\n}\n\nexport interface Finding {\n location: string;\n kind: SecretKind;\n /** Where it is, for people: enclosing channel/connector names and the field. */\n where: string;\n /** Identifies the surrounding text (secret removed), for allow entries. */\n context: string;\n}\n\n/**\n * A known false positive. `context` ties it to the surrounding text as well as\n * the location, so an entry for a transformer step at index 2 stops matching\n * if a different step moves into that index.\n */\nexport interface AllowEntry {\n location: string;\n kind: SecretKind;\n context: string;\n note?: string;\n}\n\nexport type ScanMode = 'find' | 'extract' | 'redact';\n\nexport interface ScanResult {\n config: CanonicalConfig;\n findings: Finding[];\n /** extract mode: values for the env file (only ones it doesn't already hold). Never print these. */\n envUpdates: Record<string, string>;\n}\n\ninterface Hit extends Span {\n rule: Rule;\n}\n\n/** Every secret span in `value`, earlier rules winning overlaps, in position order. */\nfunction hitsIn(value: string, script = false): Hit[] {\n const taken: Hit[] = [];\n for (const rule of RULES) {\n for (const span of rule.spans(value, script)) {\n if (span.end <= span.start || isReference(value.slice(span.start, span.end))) continue;\n if (taken.some((t) => span.start < t.end && t.start < span.end)) continue;\n taken.push({ ...span, rule });\n }\n }\n return taken.sort((a, b) => a.start - b.start);\n}\n\nconst SCRIPT_KEYS: ReadonlySet<string> = new Set<string>([...CODE_KEYS, ...CHANNEL_SCRIPT_KEYS]);\n\n/** Script leaves: step, template and channel code, and the global scripts. */\nfunction isScript(leaf: Leaf): boolean {\n return SCRIPT_KEYS.has(leaf.key) || leaf.section === 'globalScripts';\n}\n\n/** `value` with every secret a rule recognises replaced by a marker, for messages. */\nexport function redactSecretsInText(text: string): string {\n // Credential fields echoed as JSON (\"passcode\": \"…\") or XML (<keyPW>…</keyPW>),\n // by the field names `templatize` extracts, then the value rules.\n const value = text\n .replace(/(\"([\\w.-]+)\"\\s*:\\s*\")((?:[^\"\\\\]|\\\\.)+)\"/g, (whole, head: string, key: string) => (isSecretKey(key) ? `${head}<redacted>\"` : whole))\n .replace(/<([\\w.:-]+)>([^<]+)<\\/\\1>/g, (whole, key: string) => (isSecretKey(key) ? `<${key}><redacted></${key}>` : whole));\n let out = '';\n let at = 0;\n for (const h of hitsIn(value)) {\n out += `${value.slice(at, h.start)}<redacted ${h.rule.kind}>`;\n at = h.end;\n }\n return out + value.slice(at);\n}\n\n/** Hash of the string with every secret removed: stable while its text is, and holds no secret. */\nfunction contextOf(value: string, hits: Hit[]): string {\n let redacted = '';\n let at = 0;\n for (const h of hits) {\n redacted += `${value.slice(at, h.start)}\\u0000${h.rule.kind}\\u0000`;\n at = h.end;\n }\n redacted += value.slice(at);\n return createHash('sha256').update(redacted).digest('hex').slice(0, 16);\n}\n\n/**\n * Scan every string leaf. `find` reports only; `extract` swaps each secret\n * for a placeholder and returns the values; `redact` swaps it for a marker\n * (for display, e.g. in `diff`).\n */\nexport function scanSecrets(config: CanonicalConfig, opts: { mode: ScanMode; allow?: AllowEntry[]; env?: Env }): ScanResult {\n const allowed = new Set((opts.allow ?? []).map((a) => `${a.location}#${a.kind}#${a.context}`));\n const env = opts.env ?? {};\n const findings: Finding[] = [];\n const envUpdates: Record<string, string> = {};\n const assigned = new Map<string, string>(); // name -> value, this run\n\n // Names placeholders already use belong to their locations; each new\n // placeholder gets its own name, so rotating one secret never changes another.\n const inUse = new Set<string>();\n mapLeaves(config, (value) => {\n for (const m of value.matchAll(/\\{\\{env:([A-Za-z_][A-Za-z0-9_]*)\\}\\}/g)) inUse.add(m[1]!);\n return value;\n });\n const nameFor = (leaf: Leaf, rule: Rule, value: string): string => {\n const base = `${derivedName(leaf)}__${rule.suffix}`;\n for (let n = 1; ; n += 1) {\n const name = n === 1 ? base : `${base}_${n}`;\n if (assigned.has(name) || inUse.has(name)) continue;\n if (env[name] === undefined || env[name] === value) {\n assigned.set(name, value);\n // A value the environment already holds (the file, or CI's process\n // environment) is not written to the file again.\n if (env[name] !== value) envUpdates[name] = value;\n return name;\n }\n }\n };\n\n const out = mapLeaves(config, (value, leaf) => {\n const hits = hitsIn(value, isScript(leaf));\n if (hits.length === 0) return value;\n const context = contextOf(value, hits);\n let result = '';\n let at = 0;\n for (const h of hits) {\n if (allowed.has(`${leaf.location}#${h.rule.kind}#${context}`)) continue;\n findings.push({ location: leaf.location, kind: h.rule.kind, where: [...leaf.labels, leaf.key].join(' › '), context });\n if (opts.mode === 'find') continue;\n const secret = value.slice(h.start, h.end);\n const replacement = opts.mode === 'extract' ? placeholder(nameFor(leaf, h.rule, secret)) : `<redacted ${h.rule.kind}>`;\n result += value.slice(at, h.start) + replacement;\n at = h.end;\n }\n return opts.mode === 'find' ? value : result + value.slice(at);\n });\n\n return { config: out, findings, envUpdates };\n}\n\n/**\n * Known secret values that still appear verbatim somewhere in `config`: a\n * repeat no rule recognised (a default argument, a URL fragment). Values\n * shorter than 8 characters are skipped; short ones such as a database name\n * reused as a password match too much ordinary text.\n */\nexport function findEchoes(config: CanonicalConfig, secrets: Env): Array<{ name: string; where: string }> {\n const values = Object.entries(secrets).filter((e): e is [string, string] => typeof e[1] === 'string' && e[1].length >= 8);\n const out: Array<{ name: string; where: string }> = [];\n if (values.length === 0) return out;\n mapLeaves(config, (value, leaf) => {\n for (const [name, secret] of values) {\n if (value.includes(secret)) out.push({ name, where: [...leaf.labels, leaf.key].join(' › ') });\n }\n return value;\n });\n return out;\n}\n\nexport function formatFindings(findings: Finding[]): string {\n return findings\n .map((f) => ` ${f.kind.padEnd(20)} ${f.where}\\n ${''.padEnd(20)} at ${f.location} context ${f.context}`)\n .join('\\n');\n}\n","/**\n * Keep secrets and per-environment values out of the working tree.\n *\n * A string in the tree may contain `{{env:NAME}}` placeholders. `render`\n * replaces them from an environment (a `.env` file plus `process.env`) before\n * anything is sent to Mirth or written as XML. `templatize` goes the other way\n * on `pull`/`explode`: it swaps credential values for placeholders, returning\n * the values so the caller can store them in `.env`.\n *\n * The syntax is not Mirth's `${...}`, which connector fields already use for\n * Velocity variables (`${message.encodedData}`).\n */\nimport type { CanonicalConfig, Json } from '../types.js';\n\nexport type Env = Readonly<Record<string, string | undefined>>;\n\nconst PLACEHOLDER = /\\{\\{env:([A-Za-z_][A-Za-z0-9_]*)\\}\\}/g;\n\n/**\n * Credential-bearing keys: `password`, `smtpPassword`, `passPhrase`, `apiToken`,\n * and the DICOM connector's `passcode`, `keyPW`, `keyStorePW`, `trustStorePW`.\n */\nconst SECRET_KEY = /(password|passwd|passphrase|passcode|secret|token|pw|pwd|(?:api|access|secret|private)[_-]?key)$/i;\n\n/** Mirth's configuration-map entry value holder (XML and live shapes). */\nconst CONFIG_PROPERTY = 'com.mirth.connect.util.ConfigurationProperty';\n\nexport function placeholder(name: string): string {\n return `{{env:${name}}}`;\n}\n\nexport function hasPlaceholder(value: string): boolean {\n PLACEHOLDER.lastIndex = 0;\n return PLACEHOLDER.test(value);\n}\n\n/** Fill every placeholder in `value`; names with no value are collected in `missing`. */\nfunction fill(value: string, env: Env, missing: Set<string>): string {\n return value.replace(PLACEHOLDER, (whole, name: string) => {\n const v = env[name];\n if (v === undefined) {\n missing.add(name);\n return whole;\n }\n return v;\n });\n}\n\n/**\n * Replace every placeholder in the config. Throws, naming every missing\n * variable, rather than sending a literal `{{env:…}}` to a server.\n */\nexport function render(config: CanonicalConfig, env: Env): CanonicalConfig {\n const missing = new Set<string>();\n const walk = (node: Json): Json => {\n if (typeof node === 'string') return fill(node, env, missing);\n if (Array.isArray(node)) return node.map(walk);\n if (node && typeof node === 'object') {\n const out: Record<string, Json> = {};\n for (const [k, v] of Object.entries(node)) out[k] = walk(v);\n return out;\n }\n return node;\n };\n const out = walk(config) as CanonicalConfig;\n if (missing.size > 0) {\n throw new Error(\n `missing values for ${[...missing].sort().join(', ')} (set them in the env file or the environment)`,\n );\n }\n return out;\n}\n\n// --- locations -------------------------------------------------------------\n\ntype Segment = string;\n\n/**\n * A stable address for a value: array elements are identified by `id` or\n * `metaDataId` when they have one, and configuration-map entries by their key,\n * so removing, reordering or adding elements does not move an existing\n * placeholder to a different value.\n */\nfunction elementSegment(el: Json, index: number): Segment {\n if (el && typeof el === 'object' && !Array.isArray(el)) {\n const id = el['id'] ?? el['metaDataId'];\n if (typeof id === 'string' || typeof id === 'number') return `[${String(id)}]`;\n const mapKey = CONFIG_PROPERTY in el ? configMapKeyOf(el) : undefined;\n if (mapKey !== undefined) return `[${mapKey}]`;\n }\n return `[${index}]`;\n}\n\nfunction configMapKeyOf(entry: Record<string, Json>): string | undefined {\n const key = entry['string'];\n if (typeof key === 'string') return key;\n return Array.isArray(key) && typeof key[0] === 'string' ? key[0] : undefined;\n}\n\nexport interface Leaf {\n location: string;\n key: string;\n /** `name`s of enclosing objects (channel, connector), outermost first. */\n labels: string[];\n /** Top-level section the leaf lives in (`serverSettings`, `channels`, …). */\n section: string;\n /** The configuration-map key when this leaf is a map entry's value. */\n configMapKey?: string;\n}\n\n/** Visit every string leaf, allowing the visitor to replace it. */\nexport function mapLeaves(config: CanonicalConfig, visit: (value: string, leaf: Leaf) => string): CanonicalConfig {\n const walk = (node: Json, key: string, path: Segment[], labels: string[], section: string, cmKey?: string): Json => {\n if (typeof node === 'string') {\n return visit(node, { location: path.join('/'), key, labels, section, configMapKey: cmKey });\n }\n if (Array.isArray(node)) {\n return node.map((el, i) => walk(el, key, [...path.slice(0, -1), `${path[path.length - 1]}${elementSegment(el, i)}`], labels, section, cmKey));\n }\n if (node && typeof node === 'object') {\n const name = node['name'];\n const inner = typeof name === 'string' && name.trim() !== '' ? [...labels, name] : labels;\n // A configuration-map entry: { string: key | [key], ConfigurationProperty: { value, comment } }.\n const mapKey = section === 'configurationMap' && CONFIG_PROPERTY in node ? configMapKeyOf(node) : cmKey;\n const out: Record<string, Json> = {};\n for (const [k, v] of Object.entries(node)) {\n out[k] = walk(v, k, [...path, k], inner, section || k, mapKey);\n }\n return out;\n }\n return node;\n };\n return walk(config, '', [], [], '') as CanonicalConfig;\n}\n\n/** A field name that holds a credential (see {@link SECRET_KEY}). */\nexport function isSecretKey(key: string): boolean {\n return SECRET_KEY.test(key);\n}\n\nfunction isSecret(leaf: Leaf): boolean {\n if (leaf.section === 'configurationMap') return leaf.configMapKey !== undefined && leaf.key === 'value';\n return SECRET_KEY.test(leaf.key);\n}\n\nexport function envName(parts: string[]): string {\n return parts\n .map((p) => p.toUpperCase().replace(/[^A-Z0-9]+/g, '_').replace(/^_+|_+$/g, ''))\n .filter(Boolean)\n .join('__')\n .replace(/^(?=[0-9])/, '_');\n}\n\nexport function derivedName(leaf: Leaf): string {\n if (leaf.configMapKey !== undefined) return envName(['CONFIG_MAP', leaf.configMapKey]);\n const context = leaf.labels.length > 0 ? leaf.labels : [leaf.section];\n return envName([...context, leaf.key]);\n}\n\n/**\n * Replace every literal credential (by field name, as `templatize` finds them)\n * with a marker, for display. `diff` uses it so a password typed into the\n * tree by hand is never printed.\n */\nexport function redactKnownSecrets(config: CanonicalConfig): CanonicalConfig {\n return mapLeaves(config, (value, leaf) => (isSecret(leaf) && value !== '' && !hasPlaceholder(value) ? '<redacted>' : value));\n}\n\n// --- templatize ------------------------------------------------------------\n\nexport interface TemplatizeResult {\n config: CanonicalConfig;\n /** Values to write to the env file (new or changed on the server). Never print these. */\n envUpdates: Record<string, string>;\n /** Human-readable notes: placeholders dropped, secrets updated from the server. */\n notes: string[];\n}\n\n/** Placeholder-bearing strings in a previously pulled (un-rendered) tree, by location. */\nfunction templatesOf(config: CanonicalConfig | null): Map<string, string> {\n const out = new Map<string, string>();\n if (config) {\n mapLeaves(config, (value, leaf) => {\n if (hasPlaceholder(value)) out.set(leaf.location, value);\n return value;\n });\n }\n return out;\n}\n\n/**\n * Read `value` as `template` with its placeholders filled in: returns each\n * placeholder's value, or null if the text around them differs. A name used\n * twice must match the same text both times.\n */\nfunction matchTemplate(template: string, value: string): Map<string, string> | null {\n const names: string[] = [];\n let pattern = '^';\n let at = 0;\n for (const m of template.matchAll(PLACEHOLDER)) {\n pattern += template.slice(at, m.index).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const seen = names.indexOf(m[1]!);\n if (seen >= 0) {\n pattern += `\\\\${seen + 1}`;\n } else {\n names.push(m[1]!);\n pattern += '([\\\\s\\\\S]*?)';\n }\n at = m.index + m[0].length;\n }\n pattern += `${template.slice(at).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}$`;\n const match = new RegExp(pattern).exec(value);\n return match ? new Map(names.map((n, i) => [n, match[i + 1]!])) : null;\n}\n\n/**\n * Replace credentials in a freshly fetched config with placeholders.\n *\n * `previous` is the existing tree (un-rendered), so placeholders the user\n * added by hand survive a re-pull as long as they still render to what the\n * server holds. `env` is what they render with.\n */\nexport function templatize(remote: CanonicalConfig, previous: CanonicalConfig | null, env: Env): TemplatizeResult {\n const templates = templatesOf(previous);\n const envUpdates: Record<string, string> = {};\n const notes: string[] = [];\n const assigned = new Map<string, string>(); // name -> value, this run\n const reserved = new Set<string>();\n for (const t of templates.values()) {\n for (const m of t.matchAll(PLACEHOLDER)) reserved.add(m[1]!);\n }\n\n /** A name no location uses yet, bound to `value`. Placeholders are never shared between locations. */\n const fresh = (base: string, value: string): string => {\n let name = base;\n for (let n = 2; assigned.has(name) || reserved.has(name); n += 1) name = `${base}_${n}`;\n assigned.set(name, value);\n if (env[name] !== value) envUpdates[name] = value;\n return name;\n };\n\n /**\n * Bind this location's placeholder values. A name another location already\n * holds with a different value (a shared placeholder whose credentials have\n * diverged) is split off under a new name, so rotating one credential never\n * changes another.\n */\n const bind = (template: string, values: Map<string, string>, rotated: boolean): string => {\n let out = template;\n for (const [name, value] of values) {\n const bound = assigned.get(name);\n if (bound !== undefined && bound !== value) {\n reserved.delete(name);\n const renamed = fresh(name, value);\n out = out.split(placeholder(name)).join(placeholder(renamed));\n notes.push(`${renamed}: split from ${name}, which another location holds with a different value`);\n continue;\n }\n assigned.set(name, value);\n if (env[name] !== value) {\n envUpdates[name] = value;\n if (rotated) notes.push(`${name}: server value differs from the env file; env file updated`);\n }\n }\n return out;\n };\n const envValues = (template: string): Map<string, string> =>\n new Map([...template.matchAll(PLACEHOLDER)].map((m) => [m[1]!, env[m[1]!]!] as const));\n\n const config = mapLeaves(remote, (value, leaf) => {\n const template = templates.get(leaf.location);\n if (template !== undefined) {\n const missing = new Set<string>();\n if (fill(template, env, missing) === value && missing.size === 0) return bind(template, envValues(template), false);\n // Same text around the placeholders, new values (a rotated secret):\n // keep the template and take the new values.\n const captured = matchTemplate(template, value);\n if (captured) return bind(template, captured, true);\n // Text edited elsewhere, secrets unchanged: put the placeholders back\n // where their values still appear. Lossless, since rendering restores\n // exactly this text.\n let restored = value;\n for (const m of template.matchAll(PLACEHOLDER)) {\n const v = env[m[1]!];\n if (v !== undefined && v.length >= 4) restored = restored.split(v).join(placeholder(m[1]!));\n }\n if (restored !== value) return bind(restored, envValues(restored), false);\n notes.push(`${leaf.location}: placeholder no longer matches the server; replaced with the server value`);\n return value;\n }\n if (isSecret(leaf) && value !== '' && !hasPlaceholder(value)) {\n return placeholder(fresh(derivedName(leaf), value));\n }\n return value;\n });\n\n return { config, envUpdates, notes };\n}\n","import type { CanonicalConfig } from '../types.js';\n\nconst object = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);\n\n/** Validate the live API envelope and core collections without dropping plugin fields. */\nexport function liveConfiguration(payload: unknown): CanonicalConfig {\n const bad = (detail: string): never => { throw new Error(`invalid server configuration response: ${detail}; nothing should be written from this snapshot`); };\n if (!object(payload) || Object.keys(payload).length !== 1 || !('serverConfiguration' in payload)) bad('expected the serverConfiguration wrapper');\n const config = (payload as Record<string, unknown>)['serverConfiguration'];\n if (!object(config)) bad('expected a configuration object');\n const c = config as Record<string, unknown>;\n if (typeof c['@version'] !== 'string' || !/^\\d+\\.\\d+(?:\\.\\d+)*(?:[-+][A-Za-z0-9.-]+)?$/.test(c['@version'])) bad('missing or invalid engine version');\n if (!('channels' in c)) bad('missing channels collection');\n const collection = (container: unknown, key: string, where: string): Record<string, unknown>[] => {\n if (container == null || container === '') return [];\n if (!object(container)) bad(`invalid ${where} collection`);\n if (!(key in (container as Record<string, unknown>)) && Object.keys(container as object).some(k => !k.startsWith('@'))) bad(`missing resource list in ${where}`);\n const raw = (container as Record<string, unknown>)[key];\n if (raw == null || raw === '') return [];\n const items = Array.isArray(raw) ? raw : [raw];\n for (const item of items) {\n if (!object(item) || typeof item.id !== 'string' || !item.id.trim() || typeof item.name !== 'string' || !item.name.trim()) bad(`invalid resource in ${where}`);\n if ('revision' in item && (!Number.isSafeInteger(item.revision) || Number(item.revision) < 0)) bad(`invalid revision in ${where}`);\n }\n return items as Record<string, unknown>[];\n };\n collection(c.channels, 'channel', 'channels');\n if ('codeTemplateLibraries' in c) {\n for (const library of collection(c.codeTemplateLibraries, 'codeTemplateLibrary', 'code template libraries')) {\n if ('codeTemplates' in library) collection(library.codeTemplates, 'codeTemplate', 'code templates');\n }\n }\n if ('channelGroups' in c) collection(c.channelGroups, 'channelGroup', 'channel groups');\n return c as CanonicalConfig;\n}\n","/**\n * Scoped push: work out which channels, code templates, libraries and global\n * scripts differ between the working tree and the server, and send only\n * those, one resource at a time. Everything else in the server configuration\n * (settings, configuration map, groups, alerts) is left alone and reported if\n * it differs.\n *\n * Both configs are in the live (Jackson JSON) shape, and the local one has its\n * `{{env:…}}` placeholders already rendered.\n */\nimport { createHash } from 'node:crypto';\n\nimport type { CanonicalConfig, Json } from '../types.js';\n\ntype Obj = Record<string, Json>;\n\nconst isObj = (v: unknown): v is Obj => typeof v === 'object' && v !== null && !Array.isArray(v);\n\n/** Jackson writes a one-element list as a bare object; normalize to an array. */\nexport function list(v: Json | undefined): Obj[] {\n if (v == null || v === '') return [];\n return (Array.isArray(v) ? v : [v]).filter(isObj);\n}\n\nexport function channelsOf(c: CanonicalConfig): Obj[] {\n return isObj(c['channels']) ? list(c['channels']['channel']) : [];\n}\n\nexport function librariesOf(c: CanonicalConfig): Obj[] {\n return isObj(c['codeTemplateLibraries']) ? list(c['codeTemplateLibraries']['codeTemplateLibrary']) : [];\n}\n\nexport function templatesOf(library: Obj): Obj[] {\n return isObj(library['codeTemplates']) ? list(library['codeTemplates']['codeTemplate']) : [];\n}\n\nconst idOf = (o: Obj): string => String(o['id']);\nconst nameOf = (o: Obj): string => String(o['name'] ?? o['id']);\nconst revisionOf = (o: Obj): number => Number(o['revision'] ?? 0);\n\n/**\n * Mirth rewrites every line ending (CRLF, and a lone CR too) as LF when it\n * saves a channel (seen on 4.5.2), so a line-ending-only difference can never\n * be pushed and would otherwise re-appear on every run.\n */\nexport function normalizeEol(s: string): string {\n return s.replace(/\\r\\n?/g, '\\n');\n}\n\n/** `normalizeEol` applied to every string in a config (for display, e.g. `diff`). */\nexport function normalizeEolDeep<T extends Json>(value: T): T {\n if (typeof value === 'string') return normalizeEol(value) as T;\n if (Array.isArray(value)) return value.map((v) => normalizeEolDeep(v)) as T;\n if (isObj(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, normalizeEolDeep(v)])) as T;\n return value;\n}\n\n/** Key-order-insensitive structural equality, ignoring line-ending style. */\nfunction same(a: Json | undefined, b: Json | undefined): boolean {\n if (a === b) return true;\n if (typeof a === 'string' && typeof b === 'string') return normalizeEol(a) === normalizeEol(b);\n if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((x, i) => same(x, b[i]));\n if (isObj(a) && isObj(b)) {\n const ka = Object.keys(a);\n return ka.length === Object.keys(b).length && ka.every((k) => k in b && same(a[k], b[k]));\n }\n return false;\n}\n\n/**\n * A channel's tag and dependency links. Saving a channel replaces them with\n * whatever the payload carries, so push carries the server's over.\n */\nexport const ASSOCIATIONS = ['channelTags', 'dependentIds', 'dependencyIds'];\n\n/**\n * Mirth holds a code template's context types in a Java set, so two servers\n * list the same contexts in different orders (seen on 4.5.0).\n */\nfunction withSortedContexts(o: Obj): Obj {\n const set = o['contextSet'];\n const delegate = isObj(set) ? set['delegate'] : undefined;\n const types = isObj(delegate) ? delegate['contextType'] : undefined;\n if (!isObj(set) || !isObj(delegate) || !Array.isArray(types)) return o;\n const sorted = [...types].sort((a, b) => String(a).localeCompare(String(b), 'en'));\n return { ...o, contextSet: { ...set, delegate: { ...delegate, contextType: sorted } } };\n}\n\n/** Drop the fields Mirth changes on every save, so they never count as a change. */\nfunction stripVolatile(o: Obj): Obj {\n const out: Obj = withSortedContexts({ ...o });\n delete out['revision'];\n delete out['lastModified'];\n // Of exportData, compare only the channel's own metadata. Its tags and\n // dependency links are carried over from the server on push, and Mirth\n // flips them between absent and null in GET /server/configuration after\n // unrelated saves (seen on 4.5.2).\n const exportData = out['exportData'];\n if (isObj(exportData)) {\n const metadata = isObj(exportData['metadata']) ? { ...exportData['metadata'] } : undefined;\n if (metadata) {\n delete metadata['lastModified'];\n delete metadata['userId'];\n }\n out['exportData'] = metadata ? { metadata } : {};\n }\n return out;\n}\n\nconst groupsOf = (c: CanonicalConfig): Obj[] => (isObj(c['channelGroups']) ? list(c['channelGroups']['channelGroup']) : []);\n\n/**\n * `c` without the fields Mirth changes on every save (revisions, timestamps),\n * so a comparison sees content only. Mirth bumps them on a restore, and on a\n * save in the Administrator even when nothing changed.\n */\nexport function withoutVolatile(c: CanonicalConfig): CanonicalConfig {\n const out = structuredClone(c);\n const strip = (o: Obj): void => {\n delete o['revision'];\n delete o['lastModified'];\n const exportData = o['exportData'];\n const md = isObj(exportData) ? exportData['metadata'] : undefined;\n if (isObj(md)) {\n delete md['lastModified'];\n delete md['userId'];\n }\n // Null and absent are the same to Mirth (see stripVolatile).\n if (isObj(exportData)) for (const key of ASSOCIATIONS) if (exportData[key] === null) delete exportData[key];\n if (isObj(o['contextSet'])) o['contextSet'] = withSortedContexts(o)['contextSet']!;\n };\n for (const ch of channelsOf(out)) strip(ch);\n for (const lib of librariesOf(out)) {\n strip(lib);\n for (const t of templatesOf(lib)) strip(t);\n }\n for (const g of groupsOf(out)) {\n strip(g);\n // A group lists its channels with their revisions too.\n for (const member of isObj(g['channels']) ? list(g['channels']['channel']) : []) delete member['revision'];\n }\n return out;\n}\n\n/** Resources the server holds at a newer revision than `tree` (a pull would update their baseline). */\nexport function newerOnServer(tree: CanonicalConfig, server: CanonicalConfig): string[] {\n const out: string[] = [];\n const compare = (kind: string, local: Obj[], remote: Obj[]) => {\n const mine = new Map(local.map((o) => [idOf(o), revisionOf(o)]));\n for (const r of remote) {\n const rev = mine.get(idOf(r));\n if (rev !== undefined && revisionOf(r) > rev) out.push(`${kind} \"${nameOf(r)}\"`);\n }\n };\n compare('channel', channelsOf(tree), channelsOf(server));\n compare('library', librariesOf(tree), librariesOf(server));\n compare('code template', librariesOf(tree).flatMap(templatesOf), librariesOf(server).flatMap(templatesOf));\n compare('channel group', groupsOf(tree), groupsOf(server));\n return out;\n}\n\n/** A library's own settings and membership, without its templates' contents. */\nfunction libraryShape(lib: Obj): Obj {\n const out = stripVolatile(lib);\n out['codeTemplates'] = templatesOf(lib).map(idOf);\n return out;\n}\n\n/** Missing unfamiliar templates retain their server membership, including on a forced push. */\nfunction withRetainedMembers(local: Obj, remote: Obj, localIds: Set<string>, deletedIds: Set<string>): Obj {\n const retained = templatesOf(remote).filter(t => !localIds.has(idOf(t)) && !deletedIds.has(idOf(t)));\n if (!retained.length) return local;\n return { ...local, codeTemplates: {\n ...(isObj(local['codeTemplates']) ? local['codeTemplates'] : {}),\n codeTemplate: [...templatesOf(local), ...retained],\n } };\n}\n\n// --- plan -------------------------------------------------------------------\n\nexport type Op = 'create' | 'update' | 'delete';\n\nexport interface Change {\n kind: 'channel' | 'library' | 'codeTemplate' | 'globalScripts';\n op: Op;\n id: string;\n /** Display name: channel name, `library/template`, or `global scripts`. */\n label: string;\n}\n\nexport interface Plan {\n changes: Change[];\n /** Resources the server changed since the tree was pulled. */\n conflicts: string[];\n /** Server resources the tree never had (created since the last pull): left alone, not deleted. */\n serverOnly: string[];\n /** Top-level sections that differ but that scoped push does not send. */\n notPushed: string[];\n /** Channels to redeploy with --deploy: changed ones and users of changed libraries. */\n deployIds: string[];\n}\n\nexport interface Scope {\n /** Channel names or ids; undefined = all. */\n channels?: string[];\n /** Library names or ids; undefined = all. */\n libraries?: string[];\n globalScripts?: boolean;\n}\n\n/**\n * Resource ids the tree held when it was last pulled. A server resource the\n * tree lacks is a local deletion only if the tree once had it; otherwise it\n * was created on the server since the pull, and deleting it would destroy\n * someone else's work.\n */\nexport interface Known {\n /** id -> revision when last synced (null: unknown, from an older tree). */\n channels: Record<string, number | null>;\n libraries: Record<string, number | null>;\n codeTemplates: Record<string, number | null>;\n /** Hash of the global scripts when last synced; they carry no revision. */\n globalScripts?: string;\n}\n\nexport function hashGlobalScripts(c: CanonicalConfig): string {\n return createHash('sha256').update(JSON.stringify(normalizeEolDeep((c['globalScripts'] ?? null) as Json))).digest('hex');\n}\n\n/** The sync baseline for a config: every resource's revision, plus the global scripts' hash. */\nexport function resourceIds(c: CanonicalConfig): Known {\n const libs = librariesOf(c);\n const revs = (items: Obj[]) => Object.fromEntries(items.map((o) => [idOf(o), revisionOf(o)]));\n return {\n channels: revs(channelsOf(c)),\n libraries: revs(libs),\n codeTemplates: revs(libs.flatMap(templatesOf)),\n globalScripts: hashGlobalScripts(c),\n };\n}\n\n/** A reviewed destination baseline: use its revisions, without claiming unfamiliar resources. */\nexport function adoptTarget(local: CanonicalConfig, target: CanonicalConfig): { config: CanonicalConfig; known: Known } {\n const config = structuredClone(local);\n const mine = resourceIds(local);\n const theirs = resourceIds(target);\n const intersect = (key: 'channels' | 'libraries' | 'codeTemplates') =>\n Object.fromEntries(Object.entries(theirs[key]).filter(([id]) => id in mine[key]));\n const known: Known = {\n channels: intersect('channels'), libraries: intersect('libraries'), codeTemplates: intersect('codeTemplates'),\n globalScripts: theirs.globalScripts,\n };\n const rebase = (items: Obj[], revisions: Known['channels']) => {\n for (const item of items) item['revision'] = revisions[idOf(item)] ?? 0;\n };\n rebase(channelsOf(config), theirs.channels);\n rebase(librariesOf(config), theirs.libraries);\n rebase(librariesOf(config).flatMap(templatesOf), theirs.codeTemplates);\n return { config, known };\n}\n\n/** Accept the older id-list form of the baseline (no revisions). */\nexport function knownFrom(raw: unknown): Known | undefined {\n if (!isObj(raw as Json)) return undefined;\n const r = raw as Record<string, unknown>;\n const map = (v: unknown): Record<string, number | null> =>\n Array.isArray(v) ? Object.fromEntries(v.map((id) => [String(id), null])) : ((v ?? {}) as Record<string, number | null>);\n return {\n channels: map(r['channels']),\n libraries: map(r['libraries']),\n codeTemplates: map(r['codeTemplates']),\n globalScripts: typeof r['globalScripts'] === 'string' ? r['globalScripts'] : undefined,\n };\n}\n\n/**\n * The baseline after a push: resources the push wrote take the server's new\n * revision, created ones join, deleted ones leave; everything else keeps its\n * old baseline, so a colleague's unpulled change still reads as a conflict.\n */\nexport function knownAfterPush(known: Known, applied: Change[], touched: Set<string>, fresh: CanonicalConfig): Known {\n const now = resourceIds(fresh);\n const next: Known = {\n channels: { ...known.channels },\n libraries: { ...known.libraries },\n codeTemplates: { ...known.codeTemplates },\n globalScripts: known.globalScripts,\n };\n const key = { channel: 'channels', library: 'libraries', codeTemplate: 'codeTemplates' } as const;\n for (const c of applied) {\n if (c.kind === 'globalScripts') {\n next.globalScripts = now.globalScripts;\n } else if (c.op === 'delete') {\n delete next[key[c.kind]][c.id];\n }\n }\n for (const k of ['channels', 'libraries', 'codeTemplates'] as const) {\n for (const id of touched) if (id in now[k]) next[k][id] = now[k][id]!;\n }\n return next;\n}\n\n/** The server-configuration sections scoped push handles. */\nconst HANDLED = new Set(['channels', 'codeTemplateLibraries', 'globalScripts', 'date']);\n\nfunction selectedBy(names: string[] | undefined, what: string, local: Obj[], remote: Obj[]): (o: Obj) => boolean {\n if (names === undefined) return () => true;\n const known = [...local, ...remote];\n for (const n of names) {\n if (!known.some((o) => nameOf(o) === n || idOf(o) === n)) throw new Error(`no ${what} named \"${n}\" in the tree or on the server`);\n }\n return (o) => names.includes(nameOf(o)) || names.includes(idOf(o));\n}\n\n/**\n * With --library, the library list sent mixes the tree's in-scope libraries\n * with the server's others, so a template moved across that boundary would end\n * up in two libraries or in none. Refuse instead.\n */\nfunction assertNoMovesAcrossScope(ll: Obj[], rl: Obj[], inScope: (o: Obj) => boolean): void {\n const owner = (libs: Obj[]) => new Map(libs.flatMap((l) => templatesOf(l).map((t) => [idOf(t), l] as const)));\n const localOwner = owner(ll);\n for (const [id, r] of owner(rl)) {\n const l = localOwner.get(id);\n if (l && idOf(l) !== idOf(r) && inScope(l) !== inScope(r)) {\n throw new Error(\n `code template \"${nameOf(templatesOf(l).find((t) => idOf(t) === id)!)}\" moved from \"${nameOf(r)}\" to \"${nameOf(l)}\"; include both with --library`,\n );\n }\n }\n}\n\n/**\n * Libraries whose tree copy matched the server before a push. The library-list\n * PUT bumps every library's revision; copying the new revision into these is\n * safe, but copying it into a stale library would hide a real conflict.\n */\nexport function librariesInSync(local: CanonicalConfig, remote: CanonicalConfig): string[] {\n const rl = new Map(librariesOf(remote).map((l) => [idOf(l), l]));\n return librariesOf(local)\n .filter((l) => {\n const r = rl.get(idOf(l));\n return r !== undefined && revisionOf(r) === revisionOf(l) && same(libraryShape(l), libraryShape(r));\n })\n .map(idOf);\n}\n\n/** Channels a library's code is available to, per its include/enable/disable settings. */\nfunction channelsUsing(lib: Obj, allChannelIds: string[]): string[] {\n const ids = (v: Json | undefined): string[] =>\n isObj(v) ? (Array.isArray(v['string']) ? v['string'] : v['string'] != null ? [v['string']] : []).map(String) : [];\n if (lib['includeNewChannels'] === true) {\n const disabled = new Set(ids(lib['disabledChannelIds']));\n return allChannelIds.filter((id) => !disabled.has(id));\n }\n const enabled = new Set(ids(lib['enabledChannelIds']));\n return allChannelIds.filter((id) => enabled.has(id));\n}\n\n/** Groups of `items` sharing a key, for the keys held more than once. */\nfunction duplicates(items: Obj[], key: (o: Obj) => string): Array<[string, Obj[]]> {\n const groups = new Map<string, Obj[]>();\n for (const o of items) groups.set(key(o), [...(groups.get(key(o)) ?? []), o]);\n return [...groups].filter(([, group]) => group.length > 1);\n}\n\n/**\n * A copied channel or library directory keeps its source's id, and every save\n * addresses resources by id, so pushing it would overwrite the original.\n */\nfunction assertUniqueIds(local: CanonicalConfig): void {\n const libs = librariesOf(local);\n const problems = [\n ...duplicates(channelsOf(local), idOf).map(([id, g]) => `channels ${g.map((o) => `\"${nameOf(o)}\"`).join(', ')} share id ${id}`),\n ...duplicates(libs, idOf).map(([id, g]) => `libraries ${g.map((o) => `\"${nameOf(o)}\"`).join(', ')} share id ${id}`),\n ...duplicates(libs.flatMap(templatesOf), idOf).map(([id, g]) => `code templates ${g.map((o) => `\"${nameOf(o)}\"`).join(', ')} share id ${id}`),\n ];\n if (problems.length > 0) {\n throw new Error(`the tree holds duplicate ids (a copied directory keeps its source's id):\\n ${problems.join('\\n ')}\\ngive each copy a new id (a UUID) before pushing`);\n }\n}\n\n/**\n * `wholeReplace`: the plan is for one PUT of the whole configuration\n * (`--whole-server`, `restore`), not a sequence of per-resource saves.\n */\nexport function planPush(\n local: CanonicalConfig,\n remote: CanonicalConfig,\n scope: Scope = {},\n known?: Known,\n opts: { wholeReplace?: boolean } = {},\n): Plan {\n assertUniqueIds(local);\n const everything = scope.channels === undefined && scope.libraries === undefined && scope.globalScripts === undefined;\n const channelScope = everything || scope.channels !== undefined;\n const libraryScope = everything || scope.libraries !== undefined;\n const changes: Change[] = [];\n const conflicts: string[] = [];\n const deploy = new Set<string>();\n const serverOnly: string[] = [];\n /** A server resource missing from the tree: a planned delete, unless the tree never had it. */\n const missingLocally = (\n kind: 'channel' | 'library' | 'codeTemplate',\n r: Obj,\n label: string,\n baseline?: Record<string, number | null>,\n ): void => {\n const what = `${kind === 'codeTemplate' ? 'code template' : kind} \"${label}\"`;\n if (baseline && !(idOf(r) in baseline)) {\n serverOnly.push(what);\n return;\n }\n // Deleted locally, but edited on the server since the last pull: the\n // delete would discard someone else's work, so it is a conflict too.\n const pulled = baseline?.[idOf(r)];\n if (pulled != null && revisionOf(r) > pulled) {\n conflicts.push(`${what} changed on the server since the last pull (revision ${revisionOf(r)}, pulled ${pulled}); deleting it would discard that`);\n }\n changes.push({ kind, op: 'delete', id: idOf(r), label });\n };\n\n // Channels\n if (channelScope) {\n const lc = channelsOf(local);\n const rc = channelsOf(remote);\n const inScope = selectedBy(scope.channels, 'channel', lc, rc);\n const remoteById = new Map(rc.map((c) => [idOf(c), c]));\n const localIds = new Set(lc.map(idOf));\n for (const c of lc.filter(inScope)) {\n const r = remoteById.get(idOf(c));\n if (!r) {\n changes.push({ kind: 'channel', op: 'create', id: idOf(c), label: nameOf(c) });\n } else if (!same(stripVolatile(c), stripVolatile(r))) {\n changes.push({ kind: 'channel', op: 'update', id: idOf(c), label: nameOf(c) });\n if (revisionOf(r) > revisionOf(c)) conflicts.push(`channel \"${nameOf(c)}\" (server revision ${revisionOf(r)}, tree ${revisionOf(c)})`);\n } else {\n continue;\n }\n deploy.add(idOf(c));\n }\n for (const r of rc.filter(inScope)) {\n if (!localIds.has(idOf(r))) missingLocally('channel', r, nameOf(r), known?.channels);\n }\n }\n\n // The channels as they will be after this push: the server's, minus planned\n // deletes, with the tree's copy where the push writes one. Redeploys are\n // computed from these, so a channel created on the server since the pull,\n // or outside --channel, still gets a changed library's new code.\n const deletedChannels = new Set(changes.filter((c) => c.kind === 'channel' && c.op === 'delete').map((c) => c.id));\n const writtenChannels = new Set(changes.filter((c) => c.kind === 'channel' && c.op !== 'delete').map((c) => c.id));\n const effective = new Map<string, Obj>();\n for (const r of channelsOf(remote)) if (!deletedChannels.has(idOf(r))) effective.set(idOf(r), r);\n for (const l of channelsOf(local)) if (writtenChannels.has(idOf(l))) effective.set(idOf(l), l);\n // A saved channel may not take a name another channel holds, on the server\n // now or after the push (a tree channel beside a same-named server channel\n // with another id, as when servers were set up separately). Saves run before\n // deletes and one at a time, so a name freed by a delete or rename in the\n // same push is still taken when the save runs. Case-insensitive, to be safe.\n // A whole replace lands at once, so only the result must be free of clashes.\n // Only a save that introduces a name (a new channel or a rename) is checked:\n // two channels that already share a name on the server (Mirth allows\n // \"Lab Feed\" beside \"LAB FEED\") can still each be updated.\n const nameKey = (c: Obj) => nameOf(c).toLowerCase();\n const remoteNames = new Map(channelsOf(remote).map((c) => [idOf(c), nameKey(c)]));\n const introducesName = (c: Obj) => writtenChannels.has(idOf(c)) && remoteNames.get(idOf(c)) !== nameKey(c);\n const during = opts.wholeReplace ? [] : channelsOf(remote);\n const holders = [...new Map([...during, ...effective.values()].map((c) => [`${idOf(c)}\\n${nameKey(c)}`, c])).values()];\n const clashes = duplicates(holders, nameKey).filter(([, g]) => g.some(introducesName));\n if (clashes.length > 0) {\n throw new Error(\n `the push would save a channel under a name another channel holds:\\n ` +\n clashes.map(([, g]) => `\"${nameOf(g[0]!)}\": ids ${[...new Set(g.map(idOf))].join(', ')}`).join('\\n ') +\n `\\nrename one of them, or delete or rename the other in a push of its own first`,\n );\n }\n\n // Code templates and libraries\n if (libraryScope) {\n const ll = librariesOf(local);\n const rl = librariesOf(remote);\n const inScope = selectedBy(scope.libraries, 'library', ll, rl);\n if (scope.libraries !== undefined) assertNoMovesAcrossScope(ll, rl, inScope);\n const remoteLibById = new Map(rl.map((l) => [idOf(l), l]));\n const remoteTemplates = new Map(rl.flatMap((l) => templatesOf(l).map((t) => [idOf(t), t] as const)));\n const localTemplateIds = new Set(ll.flatMap((l) => templatesOf(l).map(idOf)));\n const deletedTemplateIds = new Set([...remoteTemplates.keys()].filter(id =>\n !localTemplateIds.has(id) && (!known || id in known.codeTemplates)));\n const allChannelIds = [...effective.keys()];\n\n for (const lib of ll.filter(inScope)) {\n const r = remoteLibById.get(idOf(lib));\n let touched = false;\n const effectiveLib = r && !opts.wholeReplace ? withRetainedMembers(lib, r, localTemplateIds, deletedTemplateIds) : lib;\n if (!r || !same(libraryShape(effectiveLib), libraryShape(r))) {\n changes.push({ kind: 'library', op: r ? 'update' : 'create', id: idOf(lib), label: nameOf(lib) });\n touched = true;\n if (r && revisionOf(r) > revisionOf(lib)) conflicts.push(`library \"${nameOf(lib)}\" (server revision ${revisionOf(r)}, tree ${revisionOf(lib)})`);\n }\n for (const t of templatesOf(lib)) {\n const rt = remoteTemplates.get(idOf(t));\n const label = `${nameOf(lib)}/${nameOf(t)}`;\n if (!rt) {\n changes.push({ kind: 'codeTemplate', op: 'create', id: idOf(t), label });\n } else if (!same(stripVolatile(t), stripVolatile(rt))) {\n changes.push({ kind: 'codeTemplate', op: 'update', id: idOf(t), label });\n if (revisionOf(rt) > revisionOf(t)) conflicts.push(`code template \"${label}\" (server revision ${revisionOf(rt)}, tree ${revisionOf(t)})`);\n } else {\n continue;\n }\n touched = true;\n }\n // Channels using it before or after the push both need a redeploy: one\n // losing access to the library must stop running its old code too.\n if (touched) {\n for (const id of channelsUsing(lib, allChannelIds)) deploy.add(id);\n if (r) for (const id of channelsUsing(r, allChannelIds)) deploy.add(id);\n }\n }\n for (const r of rl.filter(inScope)) {\n if (!ll.some((l) => idOf(l) === idOf(r))) {\n if (!opts.wholeReplace && known && idOf(r) in known.libraries && templatesOf(r).some(t => !localTemplateIds.has(idOf(t)) && !(idOf(t) in known.codeTemplates))) {\n throw new Error(`cannot delete library \"${nameOf(r)}\": it contains server-only code templates; pull and review their membership first`);\n }\n const before = changes.length;\n missingLocally('library', r, nameOf(r), known?.libraries);\n if (changes.length > before) for (const id of channelsUsing(r, allChannelIds)) deploy.add(id);\n }\n for (const t of templatesOf(r)) {\n if (!localTemplateIds.has(idOf(t))) missingLocally('codeTemplate', t, `${nameOf(r)}/${nameOf(t)}`, known?.codeTemplates);\n }\n }\n }\n\n // Global scripts\n if ((everything || scope.globalScripts === true) && !same(local['globalScripts'], remote['globalScripts'])) {\n changes.push({ kind: 'globalScripts', op: 'update', id: 'globalScripts', label: 'global scripts' });\n // No revision to compare, so compare against the hash taken at the last sync.\n if (known?.globalScripts && hashGlobalScripts(remote) !== known.globalScripts) {\n conflicts.push('global scripts changed on the server since the last pull');\n }\n }\n\n const notPushed = everything\n ? [...new Set([...Object.keys(local), ...Object.keys(remote)])]\n .filter((k) => !HANDLED.has(k) && !k.startsWith('@') && !same(local[k], remote[k]))\n .sort()\n : [];\n\n // Only enabled channels that will exist after the push can be deployed.\n const enabled = new Set(\n [...effective.values()]\n .filter((c) => {\n const md = isObj(c['exportData']) ? c['exportData']['metadata'] : undefined;\n return !(isObj(md) && md['enabled'] === false);\n })\n .map(idOf),\n );\n\n return {\n changes,\n conflicts,\n serverOnly,\n notPushed,\n deployIds: [...deploy].filter((id) => enabled.has(id)),\n };\n}\n\n/**\n * The full library list to send when the plan has library changes (Mirth only\n * replaces the whole list): the tree's version of each library in scope and the\n * server's version of the rest, so a scoped push never touches other libraries.\n */\nexport function librariesToSend(local: CanonicalConfig, remote: CanonicalConfig, scope: Scope, plan: Plan): Obj[] {\n const ll = librariesOf(local);\n const rl = librariesOf(remote);\n const inScope =\n scope.libraries === undefined ? () => true : (o: Obj) => scope.libraries!.includes(nameOf(o)) || scope.libraries!.includes(idOf(o));\n // Start from the server's list: a library leaves it only through a planned\n // (and approved) delete, so one created on the server since the pull survives.\n const deleted = new Set(plan.changes.filter((c) => c.kind === 'library' && c.op === 'delete').map((c) => c.id));\n const deletedTemplates = new Set(plan.changes.filter(c => c.kind === 'codeTemplate' && c.op === 'delete').map(c => c.id));\n const localTemplateIds = new Set(ll.flatMap(templatesOf).map(idOf));\n const localById = new Map(ll.map((l) => [idOf(l), l]));\n const out: Obj[] = [];\n for (const r of rl) {\n if (deleted.has(idOf(r))) {\n if (templatesOf(r).some(t => !localTemplateIds.has(idOf(t)) && !deletedTemplates.has(idOf(t)))) {\n throw new Error(`cannot delete library \"${nameOf(r)}\": it contains server-only code templates; pull and review their membership first`);\n }\n continue;\n }\n const l = localById.get(idOf(r));\n out.push(l && inScope(l) ? withRetainedMembers(l, r, localTemplateIds, deletedTemplates) : r);\n }\n for (const l of ll) if (inScope(l) && !rl.some((r) => idOf(r) === idOf(l))) out.push(l);\n return out;\n}\n\n/**\n * Planned resources whose server copy changed between `before` (what the plan\n * was made from) and `after`. Run after the confirmation prompt: an edit made\n * in the Administrator while it was open must not be overwritten.\n */\nexport function changedSince(plan: Plan, before: CanonicalConfig, after: CanonicalConfig): string[] {\n const out: string[] = [];\n const libs = (c: CanonicalConfig) => new Map(librariesOf(c).map((l) => [idOf(l), l]));\n const [lb, la] = [libs(before), libs(after)];\n for (const c of plan.changes) {\n let a: Obj | undefined;\n let b: Obj | undefined;\n if (c.kind === 'channel') [b, a] = [findChannel(before, c.id), findChannel(after, c.id)];\n else if (c.kind === 'codeTemplate') [b, a] = [findTemplate(before, c.id), findTemplate(after, c.id)];\n else if (c.kind === 'library') [b, a] = [lb.get(c.id), la.get(c.id)];\n else if (!same(before['globalScripts'], after['globalScripts'])) out.push('global scripts');\n if (c.kind === 'globalScripts') continue;\n if (resourceChanged(c.kind, b, a)) out.push(`${c.kind} \"${c.label}\"`);\n }\n // The library-list save replaces every library, not just the planned ones:\n // any library added, removed or changed meanwhile would be reverted.\n if (plan.changes.some((c) => c.kind === 'library')) {\n if (lb.size !== la.size || [...lb].some(([id, l]) => resourceChanged('library', l, la.get(id)))) {\n out.push('code template libraries (the library list is saved as a whole)');\n }\n }\n return [...new Set(out)];\n}\n\n/** A revision can reset or stay unchanged, so compare the content too. */\nexport function resourceChanged(kind: Change['kind'], before: Obj | undefined, after: Obj | undefined): boolean {\n if (!before || !after) return before !== after;\n const shape = kind === 'library' ? libraryShape : stripVolatile;\n return revisionOf(before) !== revisionOf(after) || !same(shape(before), shape(after));\n}\n\n/** Two server configurations hold the same data (ignoring the export `date`, which every GET changes). */\nexport function sameServerConfig(a: CanonicalConfig, b: CanonicalConfig): boolean {\n const { date: _a, ...ra } = a;\n const { date: _b, ...rb } = b;\n return same(ra as Json, rb as Json);\n}\n\n/** Only adopt a save's revision while the server still holds the content sent. */\nexport function savedChangeMatches(change: Change, local: CanonicalConfig, remote: CanonicalConfig): boolean {\n if (change.kind === 'globalScripts') return same(local['globalScripts'], remote['globalScripts']);\n const find = (config: CanonicalConfig): Obj | undefined => change.kind === 'channel'\n ? findChannel(config, change.id)\n : change.kind === 'codeTemplate'\n ? findTemplate(config, change.id)\n : librariesOf(config).find(l => idOf(l) === change.id);\n const after = find(remote);\n if (change.op === 'delete') return after === undefined;\n const sent = find(local);\n if (!sent || !after) return false;\n const shape = change.kind === 'library' ? libraryShape : stripVolatile;\n return same(shape(sent), shape(after));\n}\n\n/** Find a code template by id in a config. */\nexport function findTemplate(c: CanonicalConfig, id: string): Obj | undefined {\n for (const lib of librariesOf(c)) for (const t of templatesOf(lib)) if (idOf(t) === id) return t;\n return undefined;\n}\n\n/** Find a channel by id in a config. */\nexport function findChannel(c: CanonicalConfig, id: string): Obj | undefined {\n return channelsOf(c).find((ch) => idOf(ch) === id);\n}\n","/**\n * Carry out a push plan against a server, and afterwards copy the server's new\n * revision numbers back into the tree so the next push compares like with like.\n */\nimport { readdir, writeFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport * as path from 'node:path';\n\nimport type { MirthClientExt } from '../client/index.js';\nimport { readJson } from '../json.js';\nimport type { CanonicalConfig, Json } from '../types.js';\nimport {\n ASSOCIATIONS,\n changedSince,\n findChannel,\n findTemplate,\n librariesInSync,\n librariesOf,\n librariesToSend,\n list,\n planPush,\n resourceChanged,\n type Change,\n type Plan,\n type Scope,\n} from './index.js';\n\ntype Obj = Record<string, Json>;\n\nexport interface ApplyResult {\n applied: Change[];\n /** The change that failed, if any; nothing after it was attempted. */\n failed?: { change: Change; error: string };\n /** Ids whose revision the server now holds (for refreshing the tree). */\n touchedIds: Set<string>;\n /** Actual membership payload, including retained server-only templates. */\n sentLibraries?: Obj[];\n}\n\n/** Order matters: templates exist before a library lists them, and leave a library before deletion. */\nconst ORDER: Array<[Change['kind'], Change['op'][]]> = [\n ['codeTemplate', ['create', 'update']],\n ['library', ['create', 'update', 'delete']],\n ['codeTemplate', ['delete']],\n ['channel', ['create', 'update']],\n ['channel', ['delete']],\n ['globalScripts', ['update']],\n];\n\nexport async function applyPlan(\n client: MirthClientExt,\n plan: Plan,\n local: CanonicalConfig,\n remote: CanonicalConfig,\n scope: Scope,\n opts: { force?: boolean } = {},\n): Promise<ApplyResult> {\n const applied: Change[] = [];\n const touchedIds = new Set<string>();\n let librariesSent = false;\n let sentLibraries: Obj[] | undefined;\n\n for (const [kind, ops] of ORDER) {\n for (const change of plan.changes.filter((c) => c.kind === kind && ops.includes(c.op))) {\n try {\n if (kind === 'library') {\n // One PUT replaces the whole list and bumps every library's revision.\n if (!librariesSent) {\n const current = await client.getServerConfiguration();\n const moved = changedSince({ ...plan, changes: plan.changes.filter(c => c.kind === 'library') }, remote, current);\n if (!opts.force && moved.length) throw new Error(`changed on the server during the push: ${moved.join(', ')}; pull and try again`);\n const inSync = librariesInSync(local, current);\n const payload = librariesToSend(local, current, scope, plan);\n await client.putCodeTemplateLibraries(payload);\n sentLibraries = payload;\n librariesSent = true;\n // Take the server's new revision only where the tree now holds what\n // was sent; a stale out-of-scope library must keep its old revision\n // so the next push still sees its conflict.\n const sentFromTree = librariesOf(local).filter(\n (l) => scope.libraries === undefined || scope.libraries.includes(String(l['name'])) || scope.libraries.includes(String(l['id'])),\n );\n for (const l of sentFromTree) touchedIds.add(String(l['id']));\n for (const id of inSync) touchedIds.add(id);\n }\n } else if (kind === 'codeTemplate' && change.op === 'delete') {\n await checkTemplate(client, change, remote, opts.force === true);\n await client.deleteCodeTemplate(change.id);\n } else if (kind === 'codeTemplate') {\n await checkTemplate(client, change, remote, opts.force === true);\n await client.putCodeTemplate(findTemplate(local, change.id)!);\n } else if (kind === 'channel' && change.op === 'delete') {\n const current = await client.getChannel(change.id);\n checkResource(change, findChannel(remote, change.id), current, opts.force === true);\n await client.deleteChannel(change.id);\n } else if (kind === 'channel') {\n const before = findChannel(remote, change.id);\n const channel = findChannel(local, change.id)!;\n if (!before || before['name'] !== channel['name']) {\n // Names introduced since planning must not be overwritten either.\n planPush(local, await client.getServerConfiguration(), scope);\n }\n await client.putChannel(\n await withServerAssociations(client, channel, change, before, opts.force === true),\n );\n } else {\n const current = await client.getServerConfiguration();\n if (!opts.force && changedSince({ ...plan, changes: [change] }, remote, current).length) {\n throw new Error('global scripts changed on the server during the push; pull and try again');\n }\n await client.putGlobalScripts(local['globalScripts']);\n }\n } catch (err) {\n return { applied, failed: { change, error: err instanceof Error ? err.message : String(err) }, touchedIds, sentLibraries };\n }\n applied.push(change);\n touchedIds.add(change.id);\n }\n }\n return { applied, touchedIds, sentLibraries };\n}\n\nfunction checkResource(change: Change, before: Obj | undefined, current: Record<string, unknown> | null, force: boolean): void {\n if (!force && resourceChanged(change.kind, before, (current ?? undefined) as Obj | undefined)) {\n throw new Error(`${change.label} changed on the server during the push (revision ${String(current?.['revision'] ?? 'absent')}, planned against ${String(before?.['revision'] ?? 'absent')}); pull and try again`);\n }\n}\n\nasync function checkTemplate(client: MirthClientExt, change: Change, remote: CanonicalConfig, force: boolean): Promise<void> {\n checkResource(change, findTemplate(remote, change.id), await client.getCodeTemplate(change.id), force);\n}\n\n/**\n * The server configuration we pulled omits a channel's tag and dependency\n * links, so a plain PUT would silently untag the channel (seen on 4.5.2).\n * Carry the server's current links over; push only syncs the channel itself.\n */\nasync function withServerAssociations(\n client: MirthClientExt,\n channel: Obj,\n change: Change,\n planned: Obj | undefined,\n force: boolean,\n): Promise<Obj> {\n const server = await client.getChannel(String(channel['id']));\n // Last check before the save (Mirth itself does not reject a stale\n // revision): someone saved this channel after the plan was made.\n checkResource(change, planned, server, force);\n if (change.op !== 'update') return channel;\n const serverExport = server?.['exportData'] as Obj | undefined;\n if (!serverExport) return channel;\n const exportData: Obj = { ...((channel['exportData'] as Obj | undefined) ?? {}) };\n for (const key of ASSOCIATIONS) if (key in serverExport) exportData[key] = serverExport[key]!;\n return { ...channel, exportData };\n}\n\nexport async function deployChannels(\n client: MirthClientExt,\n ids: string[],\n nameOf: (id: string) => string,\n): Promise<{ deployed: string[]; skipped: string[]; failures: Array<{ name: string; error: string }> }> {\n const deployed: string[] = [];\n const skipped: string[] = [];\n const failures: Array<{ name: string; error: string }> = [];\n for (const id of ids) {\n try {\n // The preview is only a candidate list. An operator may have taken a\n // channel down while saving, or while a previous channel was deploying.\n if (!(await client.getDeployedChannelIds()).has(id)) {\n skipped.push(nameOf(id));\n continue;\n }\n await client.deployChannel(id);\n deployed.push(nameOf(id));\n } catch (err) {\n failures.push({ name: nameOf(id), error: err instanceof Error ? err.message : String(err) });\n }\n }\n return { deployed, skipped, failures };\n}\n\n// --- refresh revisions in the tree ------------------------------------------\n\nfunction copyVersionFields(target: Obj, source: Obj | undefined): boolean {\n if (!source) return false;\n let changed = false;\n for (const key of ['revision', 'lastModified'] as const) {\n if (key in source && JSON.stringify(target[key]) !== JSON.stringify(source[key])) {\n target[key] = source[key]!;\n changed = true;\n }\n }\n const tm = (target['exportData'] as Obj | undefined)?.['metadata'] as Obj | undefined;\n const sm = (source['exportData'] as Obj | undefined)?.['metadata'] as Obj | undefined;\n if (tm && sm && 'lastModified' in sm && JSON.stringify(tm['lastModified']) !== JSON.stringify(sm['lastModified'])) {\n tm['lastModified'] = sm['lastModified']!;\n changed = true;\n }\n return changed;\n}\n\nasync function jsonFiles(dir: string, name: string): Promise<string[]> {\n if (!existsSync(dir)) return [];\n const entries = await readdir(dir, { withFileTypes: true });\n return entries.filter((e) => e.isDirectory()).map((e) => path.join(dir, e.name, name)).filter((f) => existsSync(f));\n}\n\n/**\n * Copy `revision`/`lastModified` from `server` into the tree's JSON for the\n * given ids. Only those fields change; files are rewritten in the format the\n * explode engine uses, so nothing else shows up in git.\n */\nexport async function refreshRevisions(root: string, server: CanonicalConfig, ids: Set<string>): Promise<void> {\n for (const file of await jsonFiles(path.join(root, 'channels'), 'channel.json')) {\n const json = await readJson<Obj>(file);\n if (ids.has(String(json['id'])) && copyVersionFields(json, findChannel(server, String(json['id'])))) {\n await writeFile(file, JSON.stringify(json, null, 2));\n }\n }\n const serverLibs = new Map(librariesOf(server).map((l) => [String(l['id']), l]));\n for (const file of await jsonFiles(path.join(root, 'codeTemplates'), 'library.json')) {\n const json = await readJson<Obj>(file);\n let changed = ids.has(String(json['id'])) && copyVersionFields(json, serverLibs.get(String(json['id'])));\n const container = json['codeTemplates'] as Obj | undefined;\n for (const t of list(container?.['codeTemplate'])) {\n if (ids.has(String(t['id'])) && copyVersionFields(t, findTemplate(server, String(t['id'])))) changed = true;\n }\n if (changed) await writeFile(file, JSON.stringify(json, null, 2));\n }\n}\n\n","/**\n * `.env` file read/update. Updates rewrite only the lines they touch, so\n * comments and hand-added variables survive a pull.\n */\nimport { randomBytes } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { appendFile, chmod, copyFile, mkdir, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises';\nimport * as path from 'node:path';\n\nimport { parse } from 'dotenv';\n\n/**\n * Marks a value stored base64-encoded because no dotenv quoting can carry it\n * exactly (dotenv turns CRLF into LF, and each quote style excludes some\n * characters), e.g. a configuration-map JSON with Windows line endings.\n */\nconst BASE64_PREFIX = 'cv-base64:';\n\n/** Parse env-file text, decoding values channelvault had to store base64-encoded. */\nexport function parseEnv(text: string): Record<string, string> {\n const out = parse(text);\n for (const [k, v] of Object.entries(out)) {\n if (v.startsWith(BASE64_PREFIX)) out[k] = Buffer.from(v.slice(BASE64_PREFIX.length), 'base64').toString('utf8');\n }\n return out;\n}\n\nexport async function readEnvFile(file: string): Promise<Record<string, string>> {\n if (!existsSync(file)) return {};\n return parseEnv(await readFile(file, 'utf8'));\n}\n\n/**\n * Serialize a value so it reads back unchanged. Tries bare, single, backtick\n * and double quotes in turn and proves the choice by parsing it; falls back to\n * base64 for values none of them can carry.\n */\nexport function formatValue(value: string): string {\n const candidates = [\n /^[\\w@%+=:,./-]*$/.test(value) && !value.startsWith(BASE64_PREFIX) ? value : null,\n value.includes(\"'\") ? null : `'${value}'`,\n value.includes('`') ? null : `\\`${value}\\``,\n value.includes('\"') ? null : `\"${value.replace(/\\n/g, '\\\\n').replace(/\\r/g, '\\\\r')}\"`,\n ];\n for (const c of candidates) {\n if (c !== null && parseEnv(`K=${c}`)['K'] === value) return c;\n }\n return `${BASE64_PREFIX}${Buffer.from(value, 'utf8').toString('base64')}`;\n}\n\n/** Set `updates` in `file`, replacing existing assignments in place and appending new ones. */\nexport async function updateEnvFile(file: string, updates: Record<string, string>): Promise<void> {\n const names = Object.keys(updates);\n if (names.length === 0) return;\n const existing = existsSync(file) ? await readFile(file, 'utf8') : '';\n const lines = existing === '' ? [] : existing.replace(/\\r\\n/g, '\\n').replace(/\\n$/, '').split('\\n');\n const written = new Set<string>();\n const out: string[] = [];\n // Inside a multi-line quoted value (of any variable), lines are value text,\n // never assignments. `dropping` marks the continuation lines of a value\n // being replaced.\n let inQuote: string | null = null;\n let dropping = false;\n for (const line of lines) {\n if (inQuote !== null) {\n if (!dropping) out.push(line);\n if (line.includes(inQuote)) [inQuote, dropping] = [null, false];\n continue;\n }\n const m = /^\\s*(?:export\\s+)?([\\w.-]+)\\s*=\\s*(.*)$/.exec(line);\n const q = m?.[2]![0];\n const opens = (q === '\"' || q === \"'\" || q === '`') && m![2]!.lastIndexOf(q) === 0 ? q : null;\n if (m && Object.prototype.hasOwnProperty.call(updates, m[1]!)) {\n // Replace the first assignment and drop later duplicates: dotenv uses the\n // last one, so a stale duplicate would stay in effect.\n if (!written.has(m[1]!)) {\n out.push(`${m[1]}=${formatValue(updates[m[1]!]!)}`);\n written.add(m[1]!);\n }\n if (opens) [inQuote, dropping] = [opens, true];\n continue;\n }\n out.push(line);\n if (opens) inQuote = opens;\n }\n for (const name of names) {\n if (!written.has(name)) out.push(`${name}=${formatValue(updates[name]!)}`);\n }\n const text = `${out.join('\\n')}\\n`;\n // Prove the file says what we mean before replacing it.\n const readBack = parseEnv(text);\n const wrong = names.filter((n) => readBack[n] !== updates[n]);\n if (wrong.length > 0) throw new Error(`env file update would not read back correctly for ${wrong.join(', ')}; nothing written`);\n // Write beside it and rename over it: a crash mid-write must not truncate\n // what may be the only copy of these secrets. Through a link, replace the\n // file it points to, not the link.\n const target = existsSync(file) ? await realpath(file) : file;\n const temp = `${target}.${process.pid}-${randomBytes(4).toString('hex')}.tmp`;\n try {\n await writeFile(temp, text, { encoding: 'utf8', mode: 0o600 });\n await rename(temp, target);\n } catch (err) {\n await rm(temp, { force: true });\n throw err;\n }\n}\n\n/** How many superseded env files to keep; old secrets should not pile up on disk. */\nexport const ENV_BACKUPS_KEPT = 5;\n\n/**\n * Before `updates` overwrite a value already in `file`, copy the file to\n * `<dir>/<name>-<UTC timestamp>` (the tree's git-ignored `.secrets/`), keeping the newest\n * {@link ENV_BACKUPS_KEPT}. Adding new variables loses nothing, so it makes\n * no copy. Returns the backup path, or null if none was needed.\n */\nexport async function backupEnvFile(file: string, updates: Record<string, string>, dir: string): Promise<string | null> {\n if (!existsSync(file)) return null;\n const current = parseEnv(await readFile(file, 'utf8'));\n if (!Object.entries(updates).some(([k, v]) => current[k] !== undefined && current[k] !== v)) return null;\n\n await mkdir(dir, { recursive: true });\n const prefix = `${path.basename(file)}-`;\n // 20260924T173321.123Z: sorts chronologically; a same-millisecond collision gets -02, -03…\n const stamp = new Date().toISOString().replace(/[-:]/g, '');\n let target = path.join(dir, `${prefix}${stamp}`);\n for (let n = 2; existsSync(target); n += 1) target = path.join(dir, `${prefix}${stamp}-${String(n).padStart(2, '0')}`);\n await copyFile(file, target);\n await chmod(target, 0o600);\n\n // Prune the oldest, never the copy just made.\n const others = (await readdir(dir)).filter((f) => f.startsWith(prefix) && f !== path.basename(target)).sort();\n for (const old of others.slice(0, Math.max(0, others.length - (ENV_BACKUPS_KEPT - 1)))) {\n await rm(path.join(dir, old));\n }\n return target;\n}\n\nconst IGNORE_LINES = ['.env', '.env.*', '!.env.example', '.secrets/'];\n\n/** Make sure `dir/.gitignore` keeps env files out of git. Returns true if it changed. */\nexport async function ensureEnvIgnored(dir: string, envFile?: string, treeRoot = dir): Promise<boolean> {\n const file = path.join(dir, '.gitignore');\n const text = existsSync(file) ? await readFile(file, 'utf8') : '';\n const present = new Set(text.split(/\\r?\\n/).map((l) => l.trim()));\n const wanted = [...IGNORE_LINES];\n // The chosen env file itself, when the standard patterns miss its name\n // (e.g. `--dotenv secrets.prod`).\n if (envFile) {\n const rel = path.relative(treeRoot, envFile).split(path.sep).join('/');\n const base = path.basename(envFile);\n const covered = !rel.includes('/') && (base === '.env' || (base.startsWith('.env.') && base !== '.env.example'));\n if (!covered && !rel.startsWith('..') && !path.isAbsolute(rel)) wanted.push(`/${rel}`);\n }\n const missing = wanted.filter((l) => !present.has(l));\n if (missing.length === 0) return false;\n const prefix = text === '' || text.endsWith('\\n') ? '' : '\\n';\n await appendFile(file, `${prefix}# channelvault: secrets and per-environment values\\n${missing.join('\\n')}\\n`);\n return true;\n}\n","/**\n * Server backups: the XML document Mirth's `GET /server/configuration`\n * returns, the same one the Administrator's Backup Config saves, stored as\n * `<server>-<UTC stamp>.xml`. A backup holds every credential in plain text,\n * so files are owner-only (on POSIX; on Windows they inherit the directory's\n * permissions) and a backup directory channelvault creates ignores itself in\n * git.\n *\n * The name in the file name comes from the configuration, which moves between\n * servers (a restore or a whole-server push carries it along). So which server\n * a backup came from is recorded separately, by Mirth's per-installation\n * server ID, in the directory's manifest; choosing and rotating backups go by\n * that.\n */\nimport { randomBytes } from 'node:crypto';\nimport { existsSync, realpathSync } from 'node:fs';\nimport { mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport * as path from 'node:path';\n\nimport type { CanonicalConfig, Json } from '../types.js';\n\n/** Default backup directory, relative to the current directory. */\nexport const DEFAULT_BACKUP_DIR = '.backup';\n/** Backups kept per server unless `--keep` says otherwise. */\nexport const DEFAULT_KEEP = 10;\n\n/** `<server>-20260925T143012Z.xml`, or `-2`, `-3`… after the stamp for a second backup in one second. */\nconst FILE_NAME = /^(.+)-(\\d{8}T\\d{6}Z)(?:-(\\d+))?\\.xml$/;\n\n/** Lower-case letters, digits and single dashes: \"VNS Gov\" -> \"vns-gov\". */\nexport function serverSlug(name: string): string {\n return name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');\n}\n\n/**\n * The name a backup is filed under: the server name, else the environment\n * name (both in Server Settings), else `fallback` (host and port).\n */\nexport function backupName(config: CanonicalConfig, fallback: string): string {\n return configuredName(config) || serverSlug(fallback) || 'mirth';\n}\n\n/** The server or environment name set in Server Settings, as a slug; '' when neither is. */\nexport function configuredName(config: CanonicalConfig): string {\n const settings = config['serverSettings'];\n const field = (key: string): string => {\n const v = settings !== null && typeof settings === 'object' && !Array.isArray(settings) ? (settings as Record<string, Json>)[key] : undefined;\n return typeof v === 'string' ? serverSlug(v) : '';\n };\n return field('serverName') || field('environmentName');\n}\n\n/** `20260925T143012Z` for `date`, in UTC so it sorts and never repeats at a DST change. */\nexport function stamp(date: Date): string {\n return date.toISOString().replace(/[-:]/g, '').replace(/\\.\\d{3}Z$/, 'Z');\n}\n\nexport interface BackupFile {\n file: string;\n server: string;\n stamp: string;\n /** Same-second sequence: 1 for the first. */\n seq: number;\n}\n\n/** Backups in `dir` by file name, oldest first. Other files are ignored. */\nexport async function listBackups(dir: string): Promise<BackupFile[]> {\n if (!existsSync(dir)) return [];\n const out: BackupFile[] = [];\n for (const name of await readdir(dir)) {\n const m = FILE_NAME.exec(name);\n if (m) out.push({ file: path.join(dir, name), server: m[1]!, stamp: m[2]!, seq: m[3] ? Number(m[3]) : 1 });\n }\n return out.sort((a, b) => a.stamp.localeCompare(b.stamp) || a.seq - b.seq);\n}\n\n/** The server a backup file name says it came from, or null for a name channelvault didn't make. */\nexport function serverOfFile(file: string): string | null {\n return FILE_NAME.exec(path.basename(file))?.[1] ?? null;\n}\n\n/** Which server each backup in a directory came from. */\nexport const MANIFEST = 'channelvault-backups.json';\n\n/** Where a backup came from: Mirth's server ID (stable per installation) and, for people, its host. */\nexport interface Origin {\n serverId: string;\n host: string;\n}\n\ntype Manifest = Record<string, Origin>;\n\nasync function readManifest(dir: string): Promise<Manifest> {\n const file = path.join(dir, MANIFEST);\n if (!existsSync(file)) return {};\n try {\n const parsed = JSON.parse(await readFile(file, 'utf8')) as { files?: Manifest };\n return parsed.files ?? {};\n } catch (err) {\n // Without it no backup can be matched to a server, so none is chosen or rotated.\n throw new Error(`${file}: ${err instanceof Error ? err.message : String(err)}; restore it from a copy or delete it`);\n }\n}\n\nasync function writeManifest(dir: string, files: Manifest): Promise<void> {\n const present = Object.fromEntries(Object.entries(files).filter(([name]) => existsSync(path.join(dir, name))));\n await writePrivate(path.join(dir, MANIFEST), `${JSON.stringify({ version: 1, files: present }, null, 2)}\\n`);\n}\n\n/** The backups in `dir` taken from the server with this ID, oldest first. */\nexport async function backupsOf(dir: string, serverId: string): Promise<BackupFile[]> {\n const manifest = await readManifest(dir);\n return (await listBackups(dir)).filter((b) => manifest[path.basename(b.file)]?.serverId === serverId);\n}\n\n/** The recorded origin of `file`, when it is a backup in `dir`'s manifest; else null. */\nexport async function originOf(dir: string, file: string): Promise<Origin | null> {\n if (!existsSync(dir) || !sameFile(path.dirname(file), dir)) return null;\n return (await readManifest(dir))[path.basename(file)] ?? null;\n}\n\n/** The origins recorded in `dir`, for telling someone which servers it has backups of. */\nexport async function originsIn(dir: string): Promise<Origin[]> {\n if (!existsSync(dir)) return [];\n const seen = new Map<string, Origin>();\n for (const o of Object.values(await readManifest(dir))) seen.set(o.serverId, o);\n return [...seen.values()];\n}\n\n/**\n * Save `xml` as the newest backup of the server at `origin`, filed as\n * `<name>-<stamp>.xml` in `dir`, then keep only the newest `keep` backups of\n * that server (never removing `protect`, or any file the manifest doesn't\n * attribute to it). Returns the new file's path.\n */\nexport async function saveBackup(\n dir: string,\n name: string,\n xml: string,\n opts: { keep: number; origin: Origin; now?: Date; protect?: string },\n): Promise<string> {\n await ensureBackupDir(dir);\n const manifest = await readManifest(dir);\n const base = `${name}-${stamp(opts.now ?? new Date())}`;\n let file = path.join(dir, `${base}.xml`);\n for (let n = 2; existsSync(file); n += 1) file = path.join(dir, `${base}-${n}.xml`);\n await writePrivate(file, xml);\n manifest[path.basename(file)] = opts.origin;\n await writeManifest(dir, manifest);\n\n const mine = (await listBackups(dir)).filter((b) => manifest[path.basename(b.file)]?.serverId === opts.origin.serverId);\n for (const old of mine.slice(0, Math.max(0, mine.length - opts.keep))) {\n if (sameFile(old.file, file) || (opts.protect !== undefined && sameFile(old.file, opts.protect))) continue;\n await rm(old.file);\n }\n await writeManifest(dir, manifest);\n return file;\n}\n\n/** Two paths name the same file: links resolved, and case folded where the file system ignores it. */\nfunction sameFile(a: string, b: string): boolean {\n const real = (p: string): string => {\n const resolved = existsSync(p) ? realpathSync.native(p) : path.resolve(p);\n return process.platform === 'win32' || process.platform === 'darwin' ? resolved.toLowerCase() : resolved;\n };\n return real(a) === real(b);\n}\n\n/**\n * Create `dir` if needed. A directory channelvault creates gets a\n * `.gitignore` of `*`, so no repository it sits in can commit its backups;\n * an existing directory is left alone (it may be the user's own folder).\n */\nexport async function ensureBackupDir(dir: string): Promise<void> {\n if (existsSync(dir)) return;\n await mkdir(dir, { recursive: true });\n await writeFile(path.join(dir, '.gitignore'), '# channelvault backups hold credentials in plain text\\n*\\n');\n}\n\n/** Owner-only, written beside the target and renamed into place. */\nexport async function writePrivate(file: string, text: string): Promise<void> {\n const temp = `${file}.${process.pid}-${randomBytes(4).toString('hex')}.tmp`;\n try {\n await writeFile(temp, text, { encoding: 'utf8', mode: 0o600 });\n await rename(temp, file);\n } catch (err) {\n await rm(temp, { force: true });\n throw err;\n }\n}\n\n/** `4.5.2` (or `4.5.2-SNAPSHOT`) as [4, 5, 2]; null when it does not start with a number. */\nexport function numericVersion(v: string): number[] | null {\n const m = /^\\d+(?:\\.\\d+)*/.exec(v.trim());\n return m ? m[0].split('.').map(Number) : null;\n}\n\n/** Compare dotted versions numerically: negative when `a` is older. Both must pass {@link numericVersion}. */\nexport function compareVersions(a: string, b: string): number {\n const pa = numericVersion(a)!;\n const pb = numericVersion(b)!;\n for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {\n const d = (pa[i] ?? 0) - (pb[i] ?? 0);\n if (d !== 0) return d;\n }\n return 0;\n}\n","import { randomUUID } from 'node:crypto';\nimport { constants, existsSync } from 'node:fs';\nimport { copyFile, lstat, mkdir, readlink, realpath, rename, rm, rmdir, unlink, writeFile } from 'node:fs/promises';\nimport { hostname } from 'node:os';\nimport * as path from 'node:path';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport { writePrivate } from '../backup/index.js';\nimport { readJson } from '../json.js';\n\nexport const MANAGED_DIRS = ['server', 'channels', 'codeTemplates', 'channelGroups'];\nexport const STAGING_DIR = '.channelvault-staging';\nexport const JOURNAL = '.channelvault-transaction.json';\nconst ITEMS = [...MANAGED_DIRS, 'channelvault.json', '.gitignore', '.secrets', 'env'];\nconst RM = { recursive: true, force: true, maxRetries: 5, retryDelay: 50 } as const;\ninterface Entry { name: string; hadOld: boolean }\ninterface Journal { version: 1; id: string; state: 'prepared' | 'committed'; envFile: string; entries: Entry[] }\n\nasync function present(file: string): Promise<boolean> {\n return lstat(file).then(() => true, (err: NodeJS.ErrnoException) => { if (err.code === 'ENOENT') return false; throw err; });\n}\n\nasync function canonical(file: string, depth = 0): Promise<string> {\n if (depth > 64) throw new Error(`too many links in path: ${file}`);\n let existing = path.resolve(file);\n while (!(await present(existing)) && path.dirname(existing) !== existing) existing = path.dirname(existing);\n const info = await lstat(existing);\n const base = info.isSymbolicLink()\n ? await canonical(path.resolve(path.dirname(existing), await readlink(existing)), depth + 1)\n : await realpath(existing);\n return path.join(base, path.relative(existing, path.resolve(file)));\n}\nconst samePath = (a: string, b: string) => process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;\n\n/** Retry transient Windows handle contention; every failed swap still has a rollback. */\nasync function move(from: string, to: string): Promise<void> {\n for (let attempt = 0; ; attempt++) {\n try { await rename(from, to); return; }\n catch (err) {\n if (attempt >= 5 || !['EPERM', 'EBUSY', 'ENOTEMPTY', 'EACCES'].includes((err as NodeJS.ErrnoException).code ?? '')) throw err;\n await delay(50 * (attempt + 1));\n }\n }\n}\n\n/** A sibling lock leaves a refused first pull's output directory untouched. */\nexport async function lockTree(root: string): Promise<() => Promise<void>> {\n await mkdir(path.dirname(root), { recursive: true });\n const lock = `${await canonical(root)}.channelvault-lock`;\n const ownerFile = path.join(lock, 'owner.json');\n const owner = { pid: process.pid, host: hostname(), token: randomUUID() };\n try { await mkdir(lock); }\n catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;\n if ((await lstat(lock)).isSymbolicLink()) throw new Error(`refusing a linked working-tree lock: ${lock}`);\n let previous: typeof owner;\n try { previous = await readJson(ownerFile); }\n catch { throw new Error(`working-tree lock has no readable owner: ${lock}; inspect it before removing it`); }\n const dead = () => {\n if (previous.host !== hostname() || !Number.isInteger(previous.pid) || previous.pid <= 0) return false;\n try { process.kill(previous.pid, 0); return false; }\n catch (error) { return (error as NodeJS.ErrnoException).code === 'ESRCH'; }\n };\n if (!dead()) throw new Error(`working tree is locked by process ${previous.pid} on ${previous.host}: ${lock}`);\n // Only one process can reap an abandoned lock. Never recursively remove\n // it: another reaper, or a new owner, must make removal fail safely.\n const reaping = path.join(lock, 'reaping');\n try { await mkdir(reaping); }\n catch { throw new Error(`another process is recovering the working-tree lock: ${lock}; retry`); }\n try {\n const check = await readJson<typeof owner>(ownerFile);\n if (check.token !== previous.token || !dead()) throw new Error(`working-tree lock changed: ${lock}; retry`);\n await unlink(ownerFile);\n } finally { await rmdir(reaping); }\n await rmdir(lock);\n await mkdir(lock);\n }\n try { await writeFile(ownerFile, JSON.stringify(owner), { flag: 'wx', mode: 0o600 }); }\n catch (err) { await rmdir(lock).catch(() => undefined); throw err; }\n return async () => {\n const check = await readJson<typeof owner>(ownerFile);\n if (check.token !== owner.token) throw new Error(`working-tree lock ownership changed: ${lock}`);\n await unlink(ownerFile);\n await rmdir(lock);\n };\n}\n\nasync function assertStage(root: string): Promise<void> {\n for (const suffix of ['', 'next', 'previous']) {\n const stage = path.join(root, STAGING_DIR, suffix);\n const info = await lstat(stage).catch((err: NodeJS.ErrnoException) => {\n if (err.code !== 'ENOENT') throw err;\n return undefined;\n });\n if (info?.isSymbolicLink()) throw new Error(`refusing a linked staging directory: ${stage}`);\n }\n}\n\nfunction targetOf(root: string, journal: Journal, name: string): string {\n return name === 'env' ? journal.envFile : path.join(root, name);\n}\n\nfunction copies(root: string, journal: Journal, name: string): { old: string; next: string } {\n // Both env renames stay beside the selected env file, even on another volume.\n return name === 'env'\n ? { old: `${journal.envFile}.channelvault-${journal.id}.previous`, next: `${journal.envFile}.channelvault-${journal.id}.next` }\n : { old: path.join(root, STAGING_DIR, 'previous', name), next: path.join(root, STAGING_DIR, 'next', name) };\n}\n\nasync function cleanup(root: string, journal: Journal): Promise<void> {\n if (journal.entries.some(e => e.name === 'env')) {\n const { old, next } = copies(root, journal, 'env');\n await rm(old, { force: true });\n await rm(next, { force: true });\n }\n await rm(path.join(root, STAGING_DIR), RM);\n}\n\nasync function rollback(root: string, journal: Journal): Promise<void> {\n for (const entry of [...journal.entries].reverse()) {\n const target = targetOf(root, journal, entry.name);\n const { old, next } = copies(root, journal, entry.name);\n if (await present(old)) {\n await rm(target, RM);\n await move(old, target);\n } else if (!entry.hadOld && !(await present(next))) {\n await rm(target, RM);\n }\n }\n}\n\n/** Run under the tree lock, before reading any part of a working tree. */\nexport async function recoverTree(root: string, envFile: string): Promise<void> {\n const file = path.join(root, JOURNAL);\n if (!existsSync(file)) return;\n await assertStage(root);\n const journal = await readJson<Journal>(file);\n if (journal.version !== 1 || !/^[a-f0-9-]{36}$/.test(journal.id) || !['prepared', 'committed'].includes(journal.state) ||\n !Array.isArray(journal.entries) || journal.entries.some(e => !ITEMS.includes(e.name) || typeof e.hadOld !== 'boolean') ||\n new Set(journal.entries.map(e => e.name)).size !== journal.entries.length ||\n typeof journal.envFile !== 'string' || !samePath(journal.envFile, await canonical(envFile))) {\n throw new Error(`invalid transaction journal or different env file: ${file}; use the original --dotenv selection to recover`);\n }\n if (journal.state === 'prepared') await rollback(root, journal);\n await cleanup(root, journal);\n await unlink(file);\n}\n\n/** Stage everything first, journal the swap, and retain the old generation until commit. */\nexport async function replaceTree(root: string, envFile: string, prepare: (next: string) => Promise<void>): Promise<void> {\n await recoverTree(root, envFile);\n await assertStage(root);\n const stage = path.join(root, STAGING_DIR);\n await rm(stage, RM); // An unjournaled preparation never touched the old generation.\n const next = path.join(stage, 'next');\n await mkdir(next, { recursive: true });\n let journal: Journal | undefined;\n try {\n await prepare(next);\n const targetEnv = await canonical(envFile);\n journal = { version: 1, id: randomUUID(), state: 'prepared', envFile: targetEnv, entries: [] };\n for (const name of ITEMS) {\n if (!MANAGED_DIRS.includes(name) && !existsSync(path.join(next, name === 'env' ? '.env' : name))) continue;\n const target = targetOf(root, journal, name);\n const info = await lstat(target).catch((err: NodeJS.ErrnoException) => { if (err.code !== 'ENOENT') throw err; return undefined; });\n journal.entries.push({ name, hadOld: info !== undefined });\n }\n await mkdir(path.join(stage, 'previous'));\n await writePrivate(path.join(root, JOURNAL), JSON.stringify(journal));\n if (journal.entries.some(e => e.name === 'env')) {\n await mkdir(path.dirname(targetEnv), { recursive: true });\n await copyFile(path.join(next, '.env'), copies(root, journal, 'env').next, constants.COPYFILE_EXCL);\n }\n for (const entry of journal.entries) {\n const target = targetOf(root, journal, entry.name);\n const files = copies(root, journal, entry.name);\n if (entry.hadOld) await move(target, files.old);\n if (existsSync(files.next)) {\n await mkdir(path.dirname(target), { recursive: true });\n await move(files.next, target);\n }\n }\n journal.state = 'committed';\n await writePrivate(path.join(root, JOURNAL), JSON.stringify(journal));\n } catch (err) {\n if (journal && existsSync(path.join(root, JOURNAL))) {\n try { await rollback(root, journal); }\n catch (recoveryError) {\n throw new Error(`replacement failed and recovery is pending in ${path.join(root, JOURNAL)}; retry this command with the same env file`, { cause: recoveryError });\n }\n await cleanup(root, journal);\n await unlink(path.join(root, JOURNAL));\n }\n await rm(stage, RM);\n throw err;\n }\n // Cleanup failure leaves a committed journal: the next command cleans up,\n // rather than rolling back a replacement that has already completed.\n await cleanup(root, journal!);\n await unlink(path.join(root, JOURNAL));\n}\n"],"mappings":";;;AAYA,SAAS,iBAAiB;AAC1B,SAAS,IAAI,SAAAA,QAAO,SAAAC,QAAO,SAAS,WAAAC,UAAS,YAAAC,WAAU,YAAAC,WAAU,MAAAC,KAAI,aAAAC,kBAAiB;AACtF,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,cAAc;AACvB,SAAS,qBAAqB;AAC9B,YAAYC,WAAU;AACtB,SAAS,uBAAuB;AAEhC,SAAS,SAAS,sBAAsB;;;ACJxC,SAAS,yBAAyB;AAClC,SAAS,kBAAkB;AAC3B,SAAS,OAAO,OAAO,YAAAC,WAAU,SAAS,UAAU,iBAAiB;AACrE,YAAY,UAAU;;;ACef,SAAS,UAAU,GAA0B;AAClD,SACE,OAAO,MAAM,YACb,MAAM,QACN,CAAC,MAAM,QAAQ,CAAC,KAChB,OAAO,KAAK,CAAC,EAAE,WAAW,KAC1B,OAAQ,EAA8B,OAAO,MAAM;AAEvD;AAOO,IAAM,YAAY,CAAC,UAAU,MAAM;AAMnC,IAAM,sBAAsB;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;AC5DA,SAAS,gBAAgB;AAGlB,SAAS,UAAuB,MAAc,MAAiB;AACpE,MAAI;AACF,WAAO,KAAK,MAAM,IAAI;AAAA,EACxB,SAAS,KAAK;AACZ,UAAM,IAAI,MAAM,GAAG,IAAI,KAAK,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,EAAE;AAAA,EAChF;AACF;AAEA,eAAsB,SAAsB,MAA0B;AACpE,SAAO,UAAa,MAAM,SAAS,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AAAA,CAAI;AAAA,EACpD;AACA,UAAQ,WAAW;AACrB,CAAC,EAAE,QAAQ,YAAY;AACrB,MAAI,QAAQ;AACV,QAAI;AAAE,YAAM,OAAO;AAAA,IAAG,SACf,KAAK;AACV,cAAQ,OAAO,MAAM,+CAA+C,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,CAAC;AAAA,CAAI;AAC/H,cAAQ,WAAW;AAAA,IACrB;AAAA,EACF;AACF,CAAC;","names":["lstat","mkdir","readdir","readFile","realpath","rm","writeFile","existsSync","path","readFile","readFile","xml","out","path","xml","path","createHash","templatesOf","readdir","writeFile","existsSync","path","nameOf","existsSync","readdir","writeFile","existsSync","mkdir","readFile","readdir","realpath","writeFile","path","stamp","present","randomBytes","existsSync","mkdir","readdir","readFile","rename","rm","writeFile","path","existsSync","readFile","present","xml","rm","mkdir","writeFile","randomBytes","rename","existsSync","copyFile","lstat","mkdir","realpath","rename","rm","writeFile","path","lstat","realpath","rename","mkdir","writeFile","rm","existsSync","copyFile","writeJson","asArray","writeFile","existsSync","lstat","readFile","realpath","nameOf","deployed","serverId","config","mkdir","rm","list","readdir"]}